前言
重新又实现了一遍DNN,调整代码结构向课程提供的课件看齐,还是稍有不同,主要为了自己容易理解。完成课程作业——识别猫,实验程序较简单,主要是根据课件给的做数据预处理,直接调用dnn训练即可。
程序学习地址(一个同学学习小组,自己太没意思了):https://github.com/ConstellationBJUT/Coursera-DL-Study-Notes
数据预处理
这部分代码直接copy的课件。
主要是数据预处理,读取图片数据->resize图片->每个图片变换为一列作为输入特征->标准化->送入DNN
数据变换过程如下:
程序涉及文件
这次作业涉及到的程序文件:week4_dnn文件夹下
dnn_v3_cat_classfier.py
dnn_v2.py
datasets文件夹
images文件夹
结果
测试图片
模型训练准确率:
train: 0.9856459330143541
test: 0.8
y = 1.0, your L-layer model predicts a “cat” picture.
主要代码
"""
@Time : 2019/10/1 19:47 PM
@Author : bjjoy2009
判断图片是否是猫的实验,week4作业2,使用课程提供数据
结果与课程提供notebook一样
"""
import h5py
import numpy as np
from PIL import Image
from week4_dnn.dnn_v2 import DNN
def load_data():
train_dataset = h5py.File('datasets/train_catvnoncat.h5', "r")
train_set_x_orig = np.array(train_dataset["train_set_x"][:]) # your train set features
train_set_y_orig = np.array(train_dataset["train_set_y"][:]) # your train set labels
test_dataset = h5py.File('datasets/test_catvnoncat.h5', "r")
test_set_x_orig = np.array(test_dataset["test_set_x"][:]) # your test set features
test_set_y_orig = np.array(test_dataset["test_set_y"][:]) # your test set labels
classes = np.array(test_dataset["list_classes"][:]) # the list of 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
def is_cat(my_image, nn, num_px, classes, is_show=False):
image = Image.open(my_image)
x = np.array(image.resize((num_px, num_px)))
x = x.reshape(num_px*num_px*3, -1)
x = x/255
my_predicted_image = nn.score(x, np.array([1]))
print("y = " + str(np.squeeze(my_predicted_image)) + ', your L-layer model predicts a \"' + classes[int(np.squeeze(my_predicted_image)),].decode("utf-8") + "\" picture.")
if is_show:
image.show()
if __name__ == '__main__':
np.random.seed(1)
train_x_orig, train_y, test_x_orig, test_y, classes = load_data()
# Reshape the training and test examples
train_x_flatten = train_x_orig.reshape(train_x_orig.shape[0], -1).T
test_x_flatten = test_x_orig.reshape(test_x_orig.shape[0], -1).T
# Standardize data to have feature values between 0 and 1.
train_x = train_x_flatten/255.
test_x = test_x_flatten/255.
layers_dims = [12288, 20, 7, 5, 1]
nn = DNN(X=train_x, Y=train_y, layer_dims=layers_dims, max_iter=2500, alpha=0.0075, print_loss=True, activation='relu')
nn.fit()
accuracy = nn.score(train_x, train_y)
print('train:', accuracy)
print('test:', nn.score(test_x, test_y))
is_cat('images/my_image.jpg', nn, 64, classes, is_show=True)