深度学习编程练习-用python实现的识别猫神经网络

 python实现识别猫神经网络

用pycharm进行编程实现的,具体细节可参考:

https://blog.csdn.net/qq_34290470/article/details/99849514

百度云pycharm项目源码:https://pan.baidu.com/s/12q_Er1vJpeo-O8h_KQYgCQ

完整python代码:

import numpy as np
import matplotlib.pyplot as plt
import h5py


def load_dataset():
    train_dataset = h5py.File('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('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

index=25
train_set_x_orig , train_set_y , test_set_x_orig , test_set_y , classes = load_dataset() # 加载数据集
plt.imshow(train_set_x_orig[index]) # 查看训练集中的图片
plt.show()

# 打印出当前的训练标签值
# train_set_y是二维数组,使用np.squeeze的目的是压缩维度,即去掉shape中的1
# classe[0]='non-cat',classes[1]='cat'
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_x_orig.shape[0] # 训练集内的图片数量
m_test=test_set_x_orig.shape[0] # 测试集内的图片数量
num_px=train_set_x_orig.shape[1] #训练、测试集里面的图片的宽度和高度(均为64x64)

print("训练集中的数量:m_train=",m_train)
print("测试集中的数量:m_test=",m_test)
print("每张图片的宽/高:num_px=",num_px)
print("每张图片的大小:",train_set_x_orig[0].shape)
print("训练集_图片的维数:",train_set_x_orig.shape)
print("训练集_标签的维数: ",train_set_y.shape)
print("测试集_图片的维数:",test_set_x_orig.shape)
print("测试集_标签的维数:",test_set_y.shape)

# 向量化
# 每张图片的维度是(64,64,3),我们需要将维度降为(64x64x3,1);因此每列代表一张平坦的图片
# 将训练集和测试集都转化为如上形式

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))

# 数据标准化,由于RGB实际是值为0到255的三个向量。因此数据直接除以255,就可以将值缩放到0到1之间
train_set_x=train_set_x_flatten/255
test_set_x=test_set_x_flatten/255



# sigmoid函数

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


# 初始化参数

def initialize_with_zeros(dim):
    '''
    此函数为w创建一个维度为(dim,1)的向量,并将b初始化为0

    参数
    dim - w的矢量大小

    返回
    w - 维度为(dim,1)的初始化向量(对应权重)
    b - 初始化标量(对应偏差)

    '''
    w = np.zeros((dim, 1))
    b = 0

    # 利用断言来确保使用数据的正确
    assert (w.shape == (dim, 1))
    assert (isinstance(b, int) or isinstance(b, float))

    return (w, b)


def propagate(w, b, X, Y):
    '''
    实现前向和后向传播的成本函数及其梯度

    参数
    w - 权重,维度(num_p * num_px * 3,1)
    b - 偏差,标量
    X - 训练集,维度(num_p * num_px * 3,m_train)
    Y - 真实标签,维度(1,m_train)

    返回
    cost- 逻辑回归的负对数似然成本
    dw  - 相对于w的损失梯度,维度与w相同
    db  - 相对于b的损失梯度,维度与b相同

    '''
    m = X.shape[1]

    # 正向传播
    A = sigmoid(np.dot(w.T, X) + b)
    cost = (-1 / m) * np.sum((1 - Y) * np.log(1 - A) + Y * np.log(A))
    cost = np.squeeze(cost)

    # 反向传播
    dw = (1 / m) * np.dot(X, (A - Y).T)
    db = (1 / m) * np.sum(A - Y)

    # 使用断言确保数据的准确性
    assert (dw.shape == w.shape)
    assert (db.dtype == float)

    # 创建一个字典存储dw和db
    grads = {
        'dw': dw,
        'db': db
    }

    return (grads, cost)


def optimize(w, b, X, Y, num_iterations, learning_rate, print_cost):
    '''此函数通过运行梯度下降算法来优化w和b

    参数:
        w  - 权重,大小不等的数组(num_px * num_px * 3,1)
        b  - 偏差,一个标量
        X  - 维度为(num_px * num_px * 3,训练数据的数量)的数组。
        Y  - 真正的“标签”矢量(如果非猫则为0,如果是猫则为1),矩阵维度为(1,训练数据的数量)
        num_iterations  - 优化循环的迭代次数
        learning_rate  - 梯度下降更新规则的学习率
        print_cost  - 每100步打印一次损失值

    返回:
        params  - 包含权重w和偏差b的字典
        grads  - 包含权重和偏差相对于成本函数的梯度的字典
        成本 - 优化期间计算的所有成本列表,将用于绘制学习曲线。'''

    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, "误差:", cost)

    params = {
        "w": w,
        "b": b
    }
    grads = {
        'dw': dw,
        'db': db
    }

    return (params, grads, costs)


def predict(w, b, X):
    '''
    使用学习逻辑回归参数logistic (w,b)预测标签是0还是1,

    参数:
        w  - 权重,大小不等的数组(num_px * num_px * 3,1)
        b  - 偏差,一个标量
        X  - 维度为(num_px * num_px * 3,训练数据的数量)的数据

    返回:
        Y_prediction  - 包含X中所有图片的所有预测【0 | 1】的一个numpy数组(向量)'''

    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 if A[0, i] > 0.5 else 0  # 将概率转化为实际值

    assert (Y_prediction.shape == (1, m))

    return Y_prediction


def model(X_train, Y_train, X_test, Y_test, num_iterations=2000, learning_rate=0.5, print_cost=False):
    """
    通过调用之前实现的函数来构建逻辑回归模型

    参数:
        X_train  - numpy的数组,维度为(num_px * num_px * 3,m_train)的训练集
        Y_train  - numpy的数组,维度为(1,m_train)(矢量)的训练标签集
        X_test   - numpy的数组,维度为(num_px * num_px * 3,m_test)的测试集
        Y_test   - numpy的数组,维度为(1,m_test)的(向量)的测试标签集
        num_iterations  - 表示用于优化参数的迭代次数的超参数
        learning_rate  - 表示optimize()更新规则中使用的学习速率的超参数
        print_cost  - 设置为true以每100次迭代打印成本

    返回:
        d  - 包含有关模型信息的字典。
    """
    w, b = initialize_with_zeros(X_train.shape[0])  # 初始化参数

    paramters, grads, costs = optimize(w, b, X_train, Y_train, num_iterations, learning_rate, print_cost)

    w, b = paramters['w'], paramters['b']

    Y_prediction_train = predict(w, b, X_train)
    Y_prediction_test = predict(w, b, X_test)

    print("测试集的准确性:", format(100 - np.mean(np.abs(Y_prediction_test - Y_test))), "%")
    print("训练集的准确性:", format(100 - np.mean(np.abs(Y_prediction_train - Y_train))), "%")

    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)

# 可视化
costs=d['costs']
plt.plot(costs)
plt.title("Learning rate = 0.005")
plt.xlabel("iterations (per hundreds)")
plt.ylabel("Cost")
plt.show()

learning_rates = [0.01, 0.001, 0.0001]
models = {}
for i in learning_rates:
    print ("learning rate is: " + str(i))
    models[str(i)] = model(train_set_x, train_set_y, test_set_x, test_set_y, num_iterations = 1500, learning_rate = i, print_cost = False)
    print ('\n' + "-------------------------------------------------------" + '\n')

for i in learning_rates:
    plt.plot(np.squeeze(models[str(i)]["costs"]), label= str(models[str(i)]["learning_rate"]))

plt.ylabel('cost')
plt.xlabel('iterations')

legend = plt.legend(loc='upper center', shadow=True)
frame = legend.get_frame()
frame.set_facecolor('0.90')
plt.show()

 

你可能感兴趣的:(深度学习,python,机器学习,深度学习,识别猫神经网络,python深度学习实战,深度学习实战)