移植吴恩达深度学习01机器学习和神经网络第二周神经网络基础编程作业选修作业到pycharm

目录

    • 环境配置
    • 问题
      • ①imageio.imread
        • 源代码
        • 报错
        • 解决方法一
        • 解决方法二
      • ②scipy.misc.imresize
        • 源代码
        • 报错
        • 解决方法
    • 完整代码
    • 参考

环境配置

windows10
anaconda3
python3.8
pychrm-community-2022.1.3

问题

①imageio.imread

源代码

image = np.array(imageio.imread(fname))

报错

DeprecationWarning: Starting with ImageIO v3 the behavior of this function will switch to that of iio.v3.imread. To keep the current behavior (and make this warning dissapear) use `import imageio.v2 as imageio` or call `imageio.v2.imread` directly.
  image = np.array(imageio.imread(fname))

解决方法一

image = np.array(imageio.v3.imread(fname))

解决方法二

image = np.array(plt.imread(fname))

②scipy.misc.imresize

源代码

my_image = scipy.misc.imresize(image, size=(num_px,num_px)).reshape((1, num_px*num_px*3)).T

报错

module 'scipy.misc' has no attribute 'imresize'

解决方法

首先导入模块

from skimage.transform import resize

修改代码为

my_image = resize(image, output_shape=(num_px, num_px)).reshape((1, num_px * num_px * 3)).T

完整代码

import numpy as np
from matplotlib import pyplot as plt
import h5py
import pylab
from skimage.transform import resize


def load_dataset():
    train_dataset = h5py.File(
        'F:/JupyterNotebook/吴恩达深度学习作业/01.机器学习和神经网络/2.第二周 神经网络基础/编程作业/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(
        'F:/JupyterNotebook/吴恩达深度学习作业/01.机器学习和神经网络/2.第二周 神经网络基础/编程作业/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


train_set_x_orig, train_set_y, test_set_x_orig, test_set_y, classes = load_dataset()

index = 5
plt.imshow(train_set_x_orig[index])
pylab.show()
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]

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("train_set_x 维度: " + str(train_set_x_orig.shape))
print("test_set_x 维度: " + str(test_set_x_orig.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("train_set_x_flatten 维度: " + str(train_set_x_flatten.shape))
print("train_set_y 维度: " + str(train_set_y.shape))
print("test_set_x_flatten 维度: " + str(test_set_x_flatten.shape))
print("test_set_y 维度: " + str(test_set_y.shape))
# 下面两句对比着看更容易理解如何reshape
# print(train_set_x_orig)
# print("重塑后的检查维度: " + str(train_set_x_flatten[0:5, 0]))

train_set_x = train_set_x_flatten / 255
test_set_x = test_set_x_flatten / 255


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


# 测试代码
# print("sigmoid([0, 2]) = " + str(sigmoid(np.array([0, 2]))))

def initialize_with_zeros(dim):
    # !!! zeros括号内填数组行列数时,加一对括号 !!!
    w = np.zeros((dim, 1))
    b = 0
    # assert()检查条件,不符合就终止程序,终止报错“AssertionError”
    assert (w.shape == (dim, 1))
    # isinstance()判断一个变量是否是某个类型
    assert (isinstance(b, float) or isinstance(b, int))
    return w, b


# 测试代码
# dim = 2
# w, b = initialize_with_zeros(dim)
# print("w = " + str(w))
# print("b = " + str(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 (isinstance(db, float))
    cost = np.squeeze(cost)
    assert (cost.shape == ())
    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))


def optmize(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("迭代%i次后的损失是: %f" % (i, cost))
    params = {"w": w,
              "b": b}
    grads = {"dw": dw,
             "db": db}
    return params, grads, costs


# 测试代码
# params, grads, costs = optmize(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("prdictions = " + 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 = optmize(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("训练准确率:{}%".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}
    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=False)

index = 1
plt.imshow(test_set_x[:, index].reshape((num_px, num_px, 3)))
pylab.show()
print("y = " + str(test_set_y[0, index]) + ", you predicted that is a \"" + classes[
    int(d["Y_prediction_test"][0, index])].decode("utf-8") + "\" picture.")

# 绘制损失函数与迭代次数关系图
costs = np.squeeze(d['costs'])
plt.plot(costs)
plt.ylabel('costs')
plt.xlabel('iterations(per hundreds)')
plt.title("Learning rate = " + str(d["learning_rate"]))
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('costs')
plt.xlabel('iterations')

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

fname = 'F:/JupyterNotebook/吴恩达深度学习作业/01.机器学习和神经网络/2.第二周 神经网络基础/编程作业/images/cat_in_iran.jpg'
image = np.array(plt.imread(fname))
my_image = resize(image, output_shape=(num_px, num_px)).reshape((1, num_px * num_px * 3)).T
my_predicted_image = predict(d["w"], d["b"], my_image)
plt.imshow(image)
pylab.show()
print("y = " + str(np.squeeze(my_predicted_image)) + ", your algorithm predicts a \"" + classes[
    int(np.squeeze(my_predicted_image)),].decode("utf-8") + "\" picture.")

注意有3处路径需改成自己的文件路径

参考

吴恩达《深度学习》L1W2作业2

你可能感兴趣的:(深度学习-学习打卡,深度学习,机器学习,神经网络)