[关闭]
@Perfect-Demo 2018-05-01T08:42:13.000000Z 字数 8271 阅读 1020

deep_learning_week4.2_Deep_Neural_Network

机器学习深度学习

代码已上传github:
https://github.com/PerfectDemoT/my_deeplearning_homework


1.1

首先先导入包,(注意这和上一篇有一点不一样,多了一个包)

  1. import time
  2. import numpy as np
  3. import h5py
  4. import matplotlib.pyplot as plt
  5. import scipy
  6. import pylab #这个包是为了后面显示图片用的
  7. from PIL import Image
  8. from scipy import ndimage
  9. from dnn_app_utils import * #这里导入的就是前一篇写好的各个函数。

然后老样子,和上一篇一样,先设置一下绘图尺寸,颜色啥的。。。

  1. #%matplotlib inline
  2. plt.rcParams['figure.figsize'] = (5.0, 4.0) # set default size of plots
  3. plt.rcParams['image.interpolation'] = 'nearest'
  4. plt.rcParams['image.cmap'] = 'gray'
  5. #%load_ext autoreload
  6. #%autoreload 2 ​
  7. np.random.seed(1)

然后开始导入数据,向量化,归一化,输出看看(之前的几篇文章都有详细一步步介绍,此不赘述,直接贴出代码)

  1. #导入数据
  2. train_x_orig, train_y, test_x_orig, test_y, classes = load_data()
  3. # Example of a picture显示一下
  4. index = 10
  5. plt.imshow(train_x_orig[index])
  6. pylab.show()
  7. print ("y = " + str(train_y[0,index]) + ". It's a " + classes[train_y[0,index]].decode("utf-8") + " picture.")
  8. # Explore your dataset
  9. m_train = train_x_orig.shape[0]
  10. num_px = train_x_orig.shape[1]
  11. m_test = test_x_orig.shape[0]
  12. print ("Number of training examples: " + str(m_train))
  13. print ("Number of testing examples: " + str(m_test))
  14. print ("Each image is of size: (" + str(num_px) + ", " + str(num_px) + ", 3)")
  15. print ("train_x_orig shape: " + str(train_x_orig.shape))
  16. print ("train_y shape: " + str(train_y.shape))
  17. print ("test_x_orig shape: " + str(test_x_orig.shape))
  18. print ("test_y shape: " + str(test_y.shape))
  19. print("================================")
  20. #Reshape the training and test examples 向量化一下
  21. train_x_flatten = train_x_orig.reshape(train_x_orig.shape[0], -1).T # The "-1" makes reshape flatten the remaining dimensions
  22. test_x_flatten = test_x_orig.reshape(test_x_orig.shape[0], -1).T
  23. # Standardize data to have feature values between 0 and 1.
  24. train_x = train_x_flatten/255.
  25. test_x = test_x_flatten/255.
  26. print ("train_x's shape: " + str(train_x.shape))
  27. print ("test_x's shape: " + str(test_x.shape))
  28. print("====================================")

1.2 慢慢一步步来,并且对照效果,我们这里先试一试两层神经的网络的分类器模型(前面的文章对此已经介绍过,此不详细说明啦)

  1. #来看看这个两层的模型
  2. # GRADED FUNCTION: two_layer_model
  3. def two_layer_model(X, Y, layers_dims, learning_rate=0.0075, num_iterations=3000, print_cost=False):
  4. """
  5. Implements a two-layer neural network: LINEAR->RELU->LINEAR->SIGMOID.
  6. Arguments:
  7. X -- input data, of shape (n_x, number of examples)
  8. Y -- true "label" vector (containing 0 if cat, 1 if non-cat), of shape (1, number of examples)
  9. layers_dims -- dimensions of the layers (n_x, n_h, n_y)
  10. num_iterations -- number of iterations of the optimization loop
  11. learning_rate -- learning rate of the gradient descent update rule
  12. print_cost -- If set to True, this will print the cost every 100 iterations
  13. Returns:
  14. parameters -- a dictionary containing W1, W2, b1, and b2
  15. """
  16. np.random.seed(1)
  17. grads = {}
  18. costs = [] # to keep track of the cost
  19. m = X.shape[1] # number of examples
  20. (n_x, n_h, n_y) = layers_dims
  21. # Initialize parameters dictionary, by calling one of the functions you'd previously implemented
  22. ### START CODE HERE ### (≈ 1 line of code)
  23. parameters = initialize_parameters(n_x, n_h, n_y)
  24. ### END CODE HERE ###
  25. # Get W1, b1, W2 and b2 from the dictionary parameters.
  26. W1 = parameters["W1"]
  27. b1 = parameters["b1"]
  28. W2 = parameters["W2"]
  29. b2 = parameters["b2"]
  30. # Loop (gradient descent)
  31. for i in range(0, num_iterations):
  32. # Forward propagation: LINEAR -> RELU -> LINEAR -> SIGMOID. Inputs: "X, W1, b1". Output: "A1, cache1, A2, cache2".
  33. ### START CODE HERE ### (≈ 2 lines of code)
  34. A1, cache1 = linear_activation_forward(X, W1, b1, activation = 'relu')
  35. A2, cache2 = linear_activation_forward(A1, W2, b2, activation = 'sigmoid')
  36. ### END CODE HERE ###
  37. # Compute cost
  38. ### START CODE HERE ### (≈ 1 line of code)
  39. cost = compute_cost(A2, Y)
  40. ### END CODE HERE ###
  41. # Initializing backward propagation
  42. dA2 = - (np.divide(Y, A2) - np.divide(1 - Y, 1 - A2))
  43. # Backward propagation. Inputs: "dA2, cache2, cache1". Outputs: "dA1, dW2, db2; also dA0 (not used), dW1, db1".
  44. ### START CODE HERE ### (≈ 2 lines of code)
  45. dA1, dW2, db2 = linear_activation_backward(dA2, cache2, activation = 'sigmoid')
  46. dA0, dW1, db1 = linear_activation_backward(dA1, cache1, activation = 'relu')
  47. ### END CODE HERE ###
  48. # Set grads['dWl'] to dW1, grads['db1'] to db1, grads['dW2'] to dW2, grads['db2'] to db2
  49. grads['dW1'] = dW1
  50. grads['db1'] = db1
  51. grads['dW2'] = dW2
  52. grads['db2'] = db2
  53. # Update parameters.
  54. ### START CODE HERE ### (approx. 1 line of code)
  55. parameters = update_parameters(parameters, grads, learning_rate)
  56. ### END CODE HERE ###
  57. # Retrieve W1, b1, W2, b2 from parameters
  58. W1 = parameters["W1"]
  59. b1 = parameters["b1"]
  60. W2 = parameters["W2"]
  61. b2 = parameters["b2"]
  62. # Print the cost every 100 training example
  63. if print_cost and i % 100 == 0:
  64. print("Cost after iteration {}: {}".format(i, np.squeeze(cost)))
  65. if print_cost and i % 100 == 0:
  66. costs.append(cost)
  67. # plot the cost
  68. plt.plot(np.squeeze(costs))
  69. plt.ylabel('cost')
  70. plt.xlabel('iterations (per tens)')
  71. plt.title("Learning rate =" + str(learning_rate))
  72. plt.show()
  73. return parameters
  74. #调用一下
  75. parameters = two_layer_model(train_x, train_y, layers_dims = (n_x, n_h, n_y), num_iterations = 2500, print_cost=True)
  76. #下面用训练集和验证集分别看看准确度
  77. #predictions_train = predict(train_x, train_y, parameters)
  78. #训练集准确度百分之百
  79. #predictions_test = predict(test_x, test_y, parameters)
  80. #测试集准确度百分之七十二

说明一下,上面的函数虽然用了,layers_dims数组来存储所有的神经网络层的结点个数,不过内部只进行了两层的计算,所以没有扩展到N层的能力。


2.1 好了,现在开始真正的表演,建立一个可扩展的(即:可以自己设定要多少层网络,以及每层多少个结点)

先上代码:

  1. #接下来开始N层的神经网络
  2. ### CONSTANTS ###
  3. #先设置一下各层的神经元数目
  4. #当然,也可以在后面调用的时候设置这个数组
  5. layers_dims = [12288 , 20 , 7 , 5 , 1] # 5-layer model
  6. # GRADED FUNCTION: L_layer_model
  7. def L_layer_model(X, Y, layers_dims, learning_rate=0.0075, num_iterations=3000, print_cost=False): # lr was 0.009
  8. """
  9. Implements a L-layer neural network: [LINEAR->RELU]*(L-1)->LINEAR->SIGMOID.
  10. Arguments:
  11. X -- data, numpy array of shape (number of examples, num_px * num_px * 3)
  12. Y -- true "label" vector (containing 0 if cat, 1 if non-cat), of shape (1, number of examples)
  13. layers_dims -- list containing the input size and each layer size, of length (number of layers + 1).
  14. learning_rate -- learning rate of the gradient descent update rule
  15. num_iterations -- number of iterations of the optimization loop
  16. print_cost -- if True, it prints the cost every 100 steps
  17. Returns:
  18. parameters -- parameters learnt by the model. They can then be used to predict.
  19. """
  20. np.random.seed(1)
  21. costs = [] # keep track of cost
  22. # Parameters initialization.
  23. ### START CODE HERE ###
  24. parameters = initialize_parameters_deep(layers_dims)
  25. ### END CODE HERE ###
  26. # Loop (gradient descent)
  27. for i in range(0, num_iterations):
  28. #Forward propagation: [LINEAR -> RELU]*(L-1) -> LINEAR -> SIGMOID.
  29. ### START CODE HERE ### (≈ 1 line of code)
  30. AL, caches = L_model_forward(X, parameters)
  31. ### END CODE HERE ###
  32. # Compute cost.
  33. ### START CODE HERE ### (≈ 1 line of code)
  34. cost = compute_cost(AL, Y)
  35. ### END CODE HERE ###
  36. # Backward propagation.
  37. ### START CODE HERE ### (≈ 1 line of code)
  38. grads = L_model_backward(AL, Y, caches)
  39. ### END CODE HERE ###
  40. # Update parameters.
  41. ### START CODE HERE ### (≈ 1 line of code)
  42. parameters = update_parameters(parameters, grads, learning_rate)
  43. ### END CODE HERE ###
  44. # Print the cost every 100 training example
  45. if print_cost and i % 100 == 0:
  46. print("Cost after iteration %i: %f" % (i, cost))
  47. if print_cost and i % 100 == 0:
  48. costs.append(cost)
  49. # plot the cost
  50. plt.plot(np.squeeze(costs))
  51. plt.ylabel('cost')
  52. plt.xlabel('iterations (per tens)')
  53. plt.title("Learning rate =" + str(learning_rate))
  54. plt.show()
  55. return parameters

上面就是这个分类器了,赶紧来调用一下

  1. #调用一下
  2. parameters = L_layer_model(train_x, train_y, layers_dims, num_iterations = 2500, print_cost = True)

别慌,这个一调用,会花不少训练时间,在此期间可以看看每经过100次运算,你所得到的cost函数是多少
过程如下:

  1. Cost after iteration 0: 0.771749
  2. Cost after iteration 100: 0.673350
  3. Cost after iteration 200: 0.648247
  4. Cost after iteration 300: 0.620384
  5. Cost after iteration 400: 0.568401
  6. Cost after iteration 500: 0.520754
  7. Cost after iteration 600: 0.469203
  8. Cost after iteration 700: 0.487263
  9. Cost after iteration 800: 0.358436
  10. Cost after iteration 900: 0.347641
  11. Cost after iteration 1000: 0.291955
  12. Cost after iteration 1100: 0.273223
  13. Cost after iteration 1200: 0.229250
  14. Cost after iteration 1300: 0.196667
  15. Cost after iteration 1400: 0.176585
  16. Cost after iteration 1500: 0.157727
  17. Cost after iteration 1600: 0.142742
  18. Cost after iteration 1700: 0.139015
  19. Cost after iteration 1800: 0.123863
  20. Cost after iteration 1900: 0.111514
  21. Cost after iteration 2000: 0.105953
  22. Cost after iteration 2100: 0.098199
  23. Cost after iteration 2200: 0.094213
  24. Cost after iteration 2300: 0.087161
  25. Cost after iteration 2400: 0.082077

真是跑了一会儿啊,这多几层,,,跑一天不是梦。。。

然后输出cost-num_itera的曲线
cost下降曲线

然后输出了对于训练集和测试集的准确率

  1. #看看训练集的准确度
  2. pred_train = predict(train_x, train_y, parameters)
  3. #看看测试集的准确度
  4. pred_test = predict(test_x, test_y, parameters)

得到:

  1. train_Accuracy: 1.0
  2. test_Accuracy: 0.84

现在可以拿自己的图跑一跑啦,看看它认不认识你的猫咪

  1. #测试一下自己的图片
  2. ## START CODE HERE ##
  3. my_image = "my_image.jpg" # change this to the name of your image file
  4. my_label_y = [1] # the true class of your image (1 -> cat, 0 -> non-cat)
  5. ## END CODE HERE ##
  6. fname = "images/" + my_image
  7. image = np.array(ndimage.imread(fname, flatten=False))
  8. my_image = scipy.misc.imresize(image, size=(num_px,num_px)).reshape((num_px*num_px*3,1))
  9. my_predicted_image = predict(my_image, my_label_y, parameters)
  10. plt.imshow(image)
  11. pylab.show()
  12. 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.")

会显示一下你的图片,然后下面输出预测:

猫咪预测

  1. y = 1.0, your L-layer model predicts a "cat" picture.

好了,我们的猫咪检测器就这样做好了!!!

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注