吴恩达深度学习第一课第二周课后作业

本文详细介绍如何使用神经网络的思想实现逻辑回归,包括从数据预处理到模型搭建、参数优化及预测的全过程。通过具体代码实例,展示了如何将RGB图像转换为特征向量,定义激活函数,初始化参数,并进行前向传播、反向传播和梯度下降优化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.第一课第二周作业

Logistic Regression with a Neural Network mindset

使用神经网络来实现逻辑回归

# -*- coding: utf-8 -*-
import numpy as np
import h5py
import scipy
from PIL import Image
from scipy import ndimage
from lr_utils import load_dataset

train_set_x_orig, train_set_y, test_set_x_orig, test_set_y, classes = load_dataset()
m_train = train_set_x_orig.shape[0]   #训练集样本的个数
m_test = test_set_x_orig.shape[0]     #测试集样本的个数
num_px = train_set_x_orig.shape[1]    #每个样本的height = width

print ("Number of training examples: m_train = " + str(m_train))
print ("Number of testing examples: m_test = " + str(m_test))
print ("Height/Width of each image: num_px = " + str(num_px))
print ("Each image is of size: (" + str(num_px) + ", " + str(num_px) + ", 3)")
print ("train_set_x shape: " + str(train_set_x_orig.shape))
print ("train_set_y shape: " + str(train_set_y.shape))
print ("test_set_x shape: " + str(test_set_x_orig.shape))
print ("test_set_y shape: " + str(test_set_y.shape))

# Reshape the training and test examples
#将rgb图像转换为64*64*3的向量
train_set_x_flatten = train_set_x_orig.reshape(train_set_x_orig.shape[0], -1).T
test_set_x_flatten = test_set_x_orig.reshape(test_set_x_orig.shape[0], -1).T
print ("train_set_x_flatten shape: " + str(train_set_x_flatten.shape))
print ("train_set_y shape: " + str(train_set_y.shape))
print ("test_set_x_flatten shape: " + str(test_set_x_flatten.shape))
print ("test_set_y shape: " + str(test_set_y.shape))
print ("sanity check after reshaping: " + str(train_set_x_flatten[0:5,0]))

#将灰度值转换到0-1之间
train_set_x = train_set_x_flatten/255.
test_set_x = test_set_x_flatten/255.

#定义激活函数
def sigmoid(x):
    s=1/(1+np.exp(-x))
    return s
print ("sigmoid([9, 12]) = " + str(sigmoid(np.array([9,12]))))

#初始化参数
def initialize_with_zeros(dim):
    w = np.zeros((dim, 1))
    b = 0
    assert (w.shape == (dim, 1))
    assert (isinstance(b, float) or isinstance(b, int))
    return w, b

#前向传播算法  一定要分析维数
def propagate(w, b, X, Y):
    m = X.shape[1]
    A = sigmoid(np.dot(w.T, X) + b)  # compute activation
    cost = -1. / m * np.sum(Y * np.log(A) + (1 - Y) * np.log(1 - A))  # compute cost
    dw = 1./ m * np.dot(X, (A - Y).T)
    db = 1./ m * np.sum(A - Y)
    grads = {"dw": dw,
             "db": db}
    return grads, cost

w, b, X, Y = np.array([[1],[2]]), 2, np.array([[1,2],[3,4]]), np.array([[1,0]])
grads, cost = propagate(w, b, X, Y)
print ("dw = " + str(grads["dw"]))
print ("db = " + str(grads["db"]))
print ("cost = " + str(cost))

#Optimization
def optimize(w,b,X,Y,num_iterations,learning_rate,print_cost=False):
    costs=[]
    for i in range(num_iterations):
        grads, cost = propagate(w, b, X, Y)
        dw = grads["dw"]
        db = grads["db"]
        w=w - learning_rate*dw
        b=b-learning_rate*db
        if i %100 ==0:
            costs.append(cost)
        if print_cost and i % 100 == 0:
            print ("Cost after iteration %i: %f" % (i, cost))
    params = {"w": w,
              "b": b}
    grads = {"dw": dw,
             "db": db}
    return params,grads,cost
params, grads, costs = optimize(w, b, X, Y, num_iterations= 100, learning_rate = 0.009, print_cost = False)
print ("w = " + str(params["w"]))
print ("b = " + str(params["b"]))
print ("dw = " + str(grads["dw"]))
print ("db = " + str(grads["db"]))
print(costs)

#预测
def predict(w,b,X):
    m = X.shape[1]
    Y_prediction = np.zeros((1, m))
    w = w.reshape(X.shape[0], 1)
    A=sigmoid(np.dot(w.T,X)+b)
    for i in range(A.shape[1]):
        if A[0,i] <= 0.5:
            Y_prediction[0,i]=0
        else:
            Y_prediction[0,i]=1
    assert (Y_prediction.shape ==(1,m))
    return Y_prediction

print ("predictions = " + str(predict(w, b, X)))


#使用神经网络模型
def model(X_train, Y_train, X_test, Y_test, num_iterations = 2000, learning_rate = 0.5, print_cost = False):
    w, b = initialize_with_zeros(X_train.shape[0])
    parameters, grads, costs = optimize(w, b, X_train, Y_train, num_iterations, learning_rate, print_cost)
    w = parameters["w"]
    b = parameters["b"]
    Y_prediction_test = predict(w, b, X_test)
    Y_prediction_train = predict(w, b, X_train)
    print("train accuracy: {} %".format(100 - np.mean(np.abs(Y_prediction_train - Y_train)) * 100))
    print("test accuracy: {} %".format(100. - np.mean(np.abs(Y_prediction_test - Y_test)) * 100))

    d = {"costs": costs,
         "Y_prediction_test": Y_prediction_test,
         "Y_prediction_train": Y_prediction_train,
         "w": w,
         "b": b,
         "learning_rate": learning_rate,
         "num_iterations": num_iterations}

    return d

d = model(train_set_x, train_set_y, test_set_x, test_set_y, num_iterations = 2000, learning_rate = 0.005, print_cost = True)

作业中,给定的训练集为rgb图像  为64x64x3的图像,共有209个,给定的测试集有50个,

1.将rgb图像转换为一个特征向量,该特征向量的维数为64x64x3=12288,即每个图像的特征数为12288个

2.定义激活函数,逻辑回归使用的是sigmoid函数

3.初始化参数w,将其初始化为0,且维数要与给定的特征数相同,即为12288个

4.前向传播,同时求出dw、db

5.不断的更新参数w,程序中,每100次输出一次loss

6.最后对数据进行预测,对于逻辑回归,小于0.5即为0(not)

关于维数:

1.给定的数据为(209,64,64,3)需要将其转换为(64*64*3,209)的矩阵,

其中n为12288,m为训练集的个数。

2.在初始化权重w是,维数为(12288,1)

与测试集做矩阵乘法 

即得到每个样本的z,再带入激活函数sigmoid中,得到最终的输出值

3.在更新w是,求解dw,db,要保证其与w的维数相同,这就对np.dot的使用提出要求

 

需要注意的是:

1.一定要注意维数,在本题中 ,w,dw,x的维数是相同的,程序中使用assert保证其维数相同

2.在计算cost、dw、db时

cost = -1. / m * np.sum(Y * np.log(A) + (1 - Y) * np.log(1 - A)) 
dw = 1. / m * np.dot(X, (A - Y).T)
db = 1. / m * np.sum(A - Y)     

一定要注意是1.而不是1,不然无法正确计算出loss等参数

3.另外,np.dot的使用也需要注意,例如下面的代码

import numpy as np
x=np.array([[1,2,3],[4,5,6],[7,8,9],[6,8,9]])
y=np.array([[1],[2],[3]])
z=np.array([1,2,3])
print(x.dot(y))
print(x.dot(z))

输出为:

[[14]
 [32]
 [50]
 [49]]

[14 32 50 49] 

x为4x3矩阵,y为3x1矩阵,z为1x3矩阵,则2次输出的结果均为其矩阵的算法,第一次为x*y,x的列数等于y的行数3,对于x.dot(z),x的列数3等于z的3,输出为一列

本人拙见,如有错误,还请海涵!

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值