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

1 .导入库

import numpy as np
import matplotlib.pyplot as plt
import h5py
from lr_utils import load_dataset

对于图像来说:

image.shape[0]——图片高

image.shape[1]——图片长

image.shape[2]——图片通道数

而对于矩阵来说:

shape[0]:表示矩阵的行数

shape[1]:表示矩阵的列数

2.lr_utils.py代码里的东西

import numpy as np
import h5py

def load_dataset():
#取训练集
train_dataset=h5py.File(‘datasets/train_catvnoncat.h5’,“r”)
#本训练集有209张64x64x3的图像
train_set_x_orig=np.array(train_dataset[“train_set_x”][:])
(m_train,num_px,num_px,3)
#训练之的图像对应的分类,即是否为猫
按列取出训练集和测试集
train_set_y_orig=np.array(train_dataset[“train_set_y”][:])
test_dataset=h5py.File(‘datasets/train_catvnoncat.h5’,“r”)
test_set_x_orig=np.array(test_dataset[“test_set_x”][:])
test_set_y_orig=np.array(test_dataset[“test_set_y”][:])
#此时取出的数据是n行一列的
classes=np.array(test_dataset[“list_classes”][:])
train_set_y_orig=train_set_y_orig.reshape((1,train_set_y_orig.shape[0]))
test_set_y_orig=test_set_y_orig.reshape((1,test_set_y_orig.shape[0]))
return train_set_x_orig,train_set_y_orig,test_set_x_orig,test_set_y_orig,classes
#一行n列

train_set_x_orig,train_set_y,test_set_x_orig,test_set_y,classes=load_dataset()
#检查
index=25
plt.imshow(train-set_x_orig[index]

print(“y=”+str(train_set_y[:,index]+",it’s a " +classes[np.squeeze(train_set_y[:,index])].decode(“utf-8)+”'picture
#维度压缩
m_train=train_set_y.shape[1]
m_test=test_set_y.shape[1]
num_px=train_set_x_orig.shape[1]

#现在看一看我们加载的东西的具体情况
print(“训练集的数量:m_train= “+str(m_train))
print(“测试集的数量:m_test=”+str(m_test))
print(“每张图片的宽/高:num_px=”+str(num_px))
print(“每张图片的大小:(”+str(num_px)+”,”+str(num_px)+“,3)”)
print(“训练集_图片的维数:”+str(train_set_x_orig.shape))
print(“训练集_标签的维数”+str(train_set_y_orig.shape))
print(“测试集——图片的维数”+str(test_set_x_orig.shape))
print(“测试集_标签的维数”+str(test_set_y.shape))
#降维
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(“训练集降维最后的维度:”+str(train_set_x_flatten.shape))
print(“训练集_标签的维度”+str(train_set_y.shape))
print(“测试集降维之后的维度:”+str(test_set_x_flatten.shape))
print(“测试集_标签的维数:”+str(test_set_y.shape))

3.建立神经网络的主要步骤

1.定义模型结构
2.初始化模型的参数

3.循环:
3.1计算当前损失(正向传播)
3.2计算当前梯度(反向传播)
3.3 更新参数(梯度下降)

def sigmoid(z):
s=1/(1+np.exp(-z))
return s

print(“======测试sigmoid”)
print("sigmoid(0)= "+str(sigmoid(0)))
print("sigmoid(9.2)= "+str(sigmoid(9.2)))

得分initialize_with_zeros(dim):
w=np.zeros(shape=(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)
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)
assert(dw.shape==w.shape)
assert(db.type==float)
cost=np.squeeze(cost)
assert(cost.shape==())

grads={"dw":dw,"db":db}
return (grads,cost)

print(“测试propagate========”)
#初试话一些参数
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))

#更新参数
def optimize(w,b,X,Y,num_iteration,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("迭代的次数:%i,误差值:%f"%(i,cost))

params={"w":w,"b":b}

grads={"dw":dw,"db":db}
return (params,grads,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]):
    Y_prediction[0,i]=1 uf A[0,i]>0.5 else 0
    
assert(Y_prediction.shape==(1,m))
return Y_prediction

print(“=============测试predict”)
w,b,X,Y=np.array([[1],[2]]),2,np.array([[1,2],[3,4]],np.array([[1,0]]))
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,b=parameters["w"],parameters["b"]
Y_prediction_test=predict(w,b,X_test)
Y_prediction_train=predict(w,b,X_train)

print("训练集尊缺陷:",format(100-np.mean(np.abs(Y_prediction_train-Y_train))*100),"%")
print("测试集准确性:",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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

热爱技术的小曹

你的鼓励是我的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值