Advertisement
ERENARD63

Convolutional Neural Networks: Application

Apr 12th, 2018
504
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 21.44 KB | None | 0 0
  1.  
  2. # coding: utf-8
  3.  
  4. # # Convolutional Neural Networks: Application
  5. #
  6. # Welcome to Course 4's second assignment! In this notebook, you will:
  7. #
  8. # - Implement helper functions that you will use when implementing a TensorFlow model
  9. # - Implement a fully functioning ConvNet using TensorFlow
  10. #
  11. # **After this assignment you will be able to:**
  12. #
  13. # - Build and train a ConvNet in TensorFlow for a classification problem
  14. #
  15. # We assume here that you are already familiar with TensorFlow. If you are not, please refer the *TensorFlow Tutorial* of the third week of Course 2 ("*Improving deep neural networks*").
  16.  
  17. # ## 1.0 - TensorFlow model
  18. #
  19. # In the previous assignment, you built helper functions using numpy to understand the mechanics behind convolutional neural networks. Most practical applications of deep learning today are built using programming frameworks, which have many built-in functions you can simply call.
  20. #
  21. # As usual, we will start by loading in the packages.
  22.  
  23. # In[ ]:
  24.  
  25. import math
  26. import numpy as np
  27. import h5py
  28. import matplotlib.pyplot as plt
  29. import scipy
  30. from PIL import Image
  31. from scipy import ndimage
  32. import tensorflow as tf
  33. from tensorflow.python.framework import ops
  34. from cnn_utils import *
  35.  
  36. get_ipython().magic('matplotlib inline')
  37. np.random.seed(1)
  38.  
  39.  
  40. # Run the next cell to load the "SIGNS" dataset you are going to use.
  41.  
  42. # In[ ]:
  43.  
  44. # Loading the data (signs)
  45. X_train_orig, Y_train_orig, X_test_orig, Y_test_orig, classes = load_dataset()
  46.  
  47.  
  48. # As a reminder, the SIGNS dataset is a collection of 6 signs representing numbers from 0 to 5.
  49. #
  50. # <img src="images/SIGNS.png" style="width:800px;height:300px;">
  51. #
  52. # The next cell will show you an example of a labelled image in the dataset. Feel free to change the value of `index` below and re-run to see different examples.
  53.  
  54. # In[ ]:
  55.  
  56. # Example of a picture
  57. index = 289
  58. #print (X_train_orig.shape)
  59. plt.imshow(X_train_orig[index])
  60. print ("y = " + str(np.squeeze(Y_train_orig[:, index])))
  61.  
  62.  
  63. # In Course 2, you had built a fully-connected network for this dataset. But since this is an image dataset, it is more natural to apply a ConvNet to it.
  64. #
  65. # To get started, let's examine the shapes of your data.
  66.  
  67. # In[ ]:
  68.  
  69. X_train = X_train_orig/255.
  70. X_test = X_test_orig/255.
  71. Y_train = convert_to_one_hot(Y_train_orig, 6).T
  72. Y_test = convert_to_one_hot(Y_test_orig, 6).T
  73. print ("number of training examples = " + str(X_train.shape[0]))
  74. print ("number of test examples = " + str(X_test.shape[0]))
  75. print ("X_train shape: " + str(X_train.shape))
  76. print ("Y_train shape: " + str(Y_train.shape))
  77. print ("X_test shape: " + str(X_test.shape))
  78. print ("Y_test shape: " + str(Y_test.shape))
  79. conv_layers = {}
  80.  
  81.  
  82. # ### 1.1 - Create placeholders
  83. #
  84. # TensorFlow requires that you create placeholders for the input data that will be fed into the model when running the session.
  85. #
  86. # **Exercise**: Implement the function below to create placeholders for the input image X and the output Y. You should not define the number of training examples for the moment. To do so, you could use "None" as the batch size, it will give you the flexibility to choose it later. Hence X should be of dimension **[None, n_H0, n_W0, n_C0]** and Y should be of dimension **[None, n_y]**.  [Hint](https://www.tensorflow.org/api_docs/python/tf/placeholder).
  87.  
  88. # In[ ]:
  89.  
  90. # GRADED FUNCTION: create_placeholders
  91.  
  92. def create_placeholders(n_H0, n_W0, n_C0, n_y):
  93.     """
  94.    Creates the placeholders for the tensorflow session.
  95.    
  96.    Arguments:
  97.    n_H0 -- scalar, height of an input image
  98.    n_W0 -- scalar, width of an input image
  99.    n_C0 -- scalar, number of channels of the input
  100.    n_y -- scalar, number of classes
  101.        
  102.    Returns:
  103.    X -- placeholder for the data input, of shape [None, n_H0, n_W0, n_C0] and dtype "float"
  104.    Y -- placeholder for the input labels, of shape [None, n_y] and dtype "float"
  105.    """
  106.  
  107.     ### START CODE HERE ### (≈2 lines)
  108.    
  109.     X = tf.placeholder(tf.float32, shape=(None,n_H0, n_W0, n_C0))
  110.     Y = tf.placeholder(tf.float32, shape=(None,n_y))
  111.     ### END CODE HERE ###
  112.    
  113.     return X, Y
  114.  
  115.  
  116. # In[ ]:
  117.  
  118. X, Y = create_placeholders(64, 64, 3, 6)
  119. print ("X = " + str(X))
  120. print ("Y = " + str(Y))
  121.  
  122.  
  123. # **Expected Output**
  124. #
  125. # <table>
  126. # <tr>
  127. # <td>
  128. #     X = Tensor("Placeholder:0", shape=(?, 64, 64, 3), dtype=float32)
  129. #
  130. # </td>
  131. # </tr>
  132. # <tr>
  133. # <td>
  134. #     Y = Tensor("Placeholder_1:0", shape=(?, 6), dtype=float32)
  135. #
  136. # </td>
  137. # </tr>
  138. # </table>
  139.  
  140. # ### 1.2 - Initialize parameters
  141. #
  142. # You will initialize weights/filters $W1$ and $W2$ using `tf.contrib.layers.xavier_initializer(seed = 0)`. You don't need to worry about bias variables as you will soon see that TensorFlow functions take care of the bias. Note also that you will only initialize the weights/filters for the conv2d functions. TensorFlow initializes the layers for the fully connected part automatically. We will talk more about that later in this assignment.
  143. #
  144. # **Exercise:** Implement initialize_parameters(). The dimensions for each group of filters are provided below. Reminder - to initialize a parameter $W$ of shape [1,2,3,4] in Tensorflow, use:
  145. # ```python
  146. # W = tf.get_variable("W", [1,2,3,4], initializer = ...)
  147. # ```
  148. # [More Info](https://www.tensorflow.org/api_docs/python/tf/get_variable).
  149.  
  150. # In[ ]:
  151.  
  152. # GRADED FUNCTION: initialize_parameters
  153.  
  154. def initialize_parameters():
  155.     """
  156.    Initializes weight parameters to build a neural network with tensorflow. The shapes are:
  157.                        W1 : [4, 4, 3, 8]
  158.                        W2 : [2, 2, 8, 16]
  159.    Returns:
  160.    parameters -- a dictionary of tensors containing W1, W2
  161.    """
  162.    
  163.     tf.set_random_seed(1)                              # so that your "random" numbers match ours
  164.        
  165.     ### START CODE HERE ### (approx. 2 lines of code)
  166.     W1 = tf.get_variable("W1", [4, 4, 3, 8], initializer = tf.contrib.layers.xavier_initializer(seed = 0))
  167.     W2 = tf.get_variable("W2", [2, 2, 8, 16], initializer = tf.contrib.layers.xavier_initializer(seed = 0))
  168.     ### END CODE HERE ###
  169.  
  170.     parameters = {"W1": W1,
  171.                   "W2": W2}
  172.    
  173.     return parameters
  174.  
  175.  
  176. # In[ ]:
  177.  
  178. tf.reset_default_graph()
  179. with tf.Session() as sess_test:
  180.     parameters = initialize_parameters()
  181.     init = tf.global_variables_initializer()
  182.     sess_test.run(init)
  183.     print("W1 = " + str(parameters["W1"].eval()[1,1,1]))
  184.     print("W2 = " + str(parameters["W2"].eval()[1,1,1]))
  185.  
  186.  
  187. # ** Expected Output:**
  188. #
  189. # <table>
  190. #
  191. #     <tr>
  192. #         <td>
  193. #         W1 =
  194. #         </td>
  195. #         <td>
  196. # [ 0.00131723  0.14176141 -0.04434952  0.09197326  0.14984085 -0.03514394 <br>
  197. #  -0.06847463  0.05245192]
  198. #         </td>
  199. #     </tr>
  200. #
  201. #     <tr>
  202. #         <td>
  203. #         W2 =
  204. #         </td>
  205. #         <td>
  206. # [-0.08566415  0.17750949  0.11974221  0.16773748 -0.0830943  -0.08058 <br>
  207. #  -0.00577033 -0.14643836  0.24162132 -0.05857408 -0.19055021  0.1345228 <br>
  208. #  -0.22779644 -0.1601823  -0.16117483 -0.10286498]
  209. #         </td>
  210. #     </tr>
  211. #
  212. # </table>
  213.  
  214. # ### 1.2 - Forward propagation
  215. #
  216. # In TensorFlow, there are built-in functions that carry out the convolution steps for you.
  217. #
  218. # - **tf.nn.conv2d(X,W1, strides = [1,s,s,1], padding = 'SAME'):** given an input $X$ and a group of filters $W1$, this function convolves $W1$'s filters on X. The third input ([1,f,f,1]) represents the strides for each dimension of the input (m, n_H_prev, n_W_prev, n_C_prev). You can read the full documentation [here](https://www.tensorflow.org/api_docs/python/tf/nn/conv2d)
  219. #
  220. # - **tf.nn.max_pool(A, ksize = [1,f,f,1], strides = [1,s,s,1], padding = 'SAME'):** given an input A, this function uses a window of size (f, f) and strides of size (s, s) to carry out max pooling over each window. You can read the full documentation [here](https://www.tensorflow.org/api_docs/python/tf/nn/max_pool)
  221. #
  222. # - **tf.nn.relu(Z1):** computes the elementwise ReLU of Z1 (which can be any shape). You can read the full documentation [here.](https://www.tensorflow.org/api_docs/python/tf/nn/relu)
  223. #
  224. # - **tf.contrib.layers.flatten(P)**: given an input P, this function flattens each example into a 1D vector it while maintaining the batch-size. It returns a flattened tensor with shape [batch_size, k]. You can read the full documentation [here.](https://www.tensorflow.org/api_docs/python/tf/contrib/layers/flatten)
  225. #
  226. # - **tf.contrib.layers.fully_connected(F, num_outputs):** given a the flattened input F, it returns the output computed using a fully connected layer. You can read the full documentation [here.](https://www.tensorflow.org/api_docs/python/tf/contrib/layers/fully_connected)
  227. #
  228. # In the last function above (`tf.contrib.layers.fully_connected`), the fully connected layer automatically initializes weights in the graph and keeps on training them as you train the model. Hence, you did not need to initialize those weights when initializing the parameters.
  229. #
  230. #
  231. # **Exercise**:
  232. #
  233. # Implement the `forward_propagation` function below to build the following model: `CONV2D -> RELU -> MAXPOOL -> CONV2D -> RELU -> MAXPOOL -> FLATTEN -> FULLYCONNECTED`. You should use the functions above.
  234. #
  235. # In detail, we will use the following parameters for all the steps:
  236. #      - Conv2D: stride 1, padding is "SAME"
  237. #      - ReLU
  238. #      - Max pool: Use an 8 by 8 filter size and an 8 by 8 stride, padding is "SAME"
  239. #      - Conv2D: stride 1, padding is "SAME"
  240. #      - ReLU
  241. #      - Max pool: Use a 4 by 4 filter size and a 4 by 4 stride, padding is "SAME"
  242. #      - Flatten the previous output.
  243. #      - FULLYCONNECTED (FC) layer: Apply a fully connected layer without an non-linear activation function. Do not call the softmax here. This will result in 6 neurons in the output layer, which then get passed later to a softmax. In TensorFlow, the softmax and cost function are lumped together into a single function, which you'll call in a different function when computing the cost.
  244.  
  245. # In[ ]:
  246.  
  247. # GRADED FUNCTION: forward_propagation
  248.  
  249. def forward_propagation(X, parameters):
  250.     """
  251.    Implements the forward propagation for the model:
  252.    CONV2D -> RELU -> MAXPOOL -> CONV2D -> RELU -> MAXPOOL -> FLATTEN -> FULLYCONNECTED
  253.    
  254.    Arguments:
  255.    X -- input dataset placeholder, of shape (input size, number of examples)
  256.    parameters -- python dictionary containing your parameters "W1", "W2"
  257.                  the shapes are given in initialize_parameters
  258.  
  259.    Returns:
  260.    Z3 -- the output of the last LINEAR unit
  261.    """
  262.    
  263.     # Retrieve the parameters from the dictionary "parameters"
  264.     W1 = parameters['W1']
  265.     W2 = parameters['W2']
  266.    
  267.     ### START CODE HERE ###
  268.     # CONV2D: stride of 1, padding 'SAME'
  269.     Z1 = tf.nn.conv2d(X,W1, strides = [1,1,1,1], padding = 'SAME')
  270.     # RELU
  271.     A1 = tf.nn.relu(Z1)
  272.     # MAXPOOL: window 8x8, sride 8, padding 'SAME'
  273.     P1 = tf.nn.max_pool(A1, ksize = [1,8,8,1], strides = [1,8,8,1], padding = 'SAME')
  274.     # CONV2D: filters W2, stride 1, padding 'SAME'
  275.     Z2 = tf.nn.conv2d(P1,W2, strides = [1,1,1,1], padding = 'SAME')
  276.     # RELU
  277.     A2 = tf.nn.relu(Z2)
  278.     # MAXPOOL: window 4x4, stride 4, padding 'SAME'
  279.     P2 = tf.nn.max_pool(A2, ksize = [1,4,4,1], strides = [1,4,4,1], padding = 'SAME')
  280.     # FLATTEN
  281.     P2 = tf.contrib.layers.flatten(P2)
  282.     # FULLY-CONNECTED without non-linear activation function (not not call softmax).
  283.     # 6 neurons in output layer. Hint: one of the arguments should be "activation_fn=None"
  284.     Z3 = tf.contrib.layers.fully_connected(P2, 6, activation_fn=None )
  285.     ### END CODE HERE ###
  286.  
  287.     return Z3
  288.  
  289.  
  290. # In[ ]:
  291.  
  292. tf.reset_default_graph()
  293.  
  294. with tf.Session() as sess:
  295.     np.random.seed(1)
  296.     X, Y = create_placeholders(64, 64, 3, 6)
  297.     parameters = initialize_parameters()
  298.     Z3 = forward_propagation(X, parameters)
  299.     init = tf.global_variables_initializer()
  300.     sess.run(init)
  301.     a = sess.run(Z3, {X: np.random.randn(2,64,64,3), Y: np.random.randn(2,6)})
  302.     print("Z3 = " + str(a))
  303.  
  304.  
  305. # **Expected Output**:
  306. #
  307. # <table>
  308. #     <td>
  309. #     Z3 =
  310. #     </td>
  311. #     <td>
  312. #     [[-0.44670227 -1.57208765 -1.53049231 -2.31013036 -1.29104376  0.46852064] <br>
  313. #  [-0.17601591 -1.57972014 -1.4737016  -2.61672091 -1.00810647  0.5747785 ]]
  314. #     </td>
  315. # </table>
  316.  
  317. # ### 1.3 - Compute cost
  318. #
  319. # Implement the compute cost function below. You might find these two functions helpful:
  320. #
  321. # - **tf.nn.softmax_cross_entropy_with_logits(logits = Z3, labels = Y):** computes the softmax entropy loss. This function both computes the softmax activation function as well as the resulting loss. You can check the full documentation  [here.](https://www.tensorflow.org/api_docs/python/tf/nn/softmax_cross_entropy_with_logits)
  322. # - **tf.reduce_mean:** computes the mean of elements across dimensions of a tensor. Use this to sum the losses over all the examples to get the overall cost. You can check the full documentation [here.](https://www.tensorflow.org/api_docs/python/tf/reduce_mean)
  323. #
  324. # ** Exercise**: Compute the cost below using the function above.
  325.  
  326. # In[ ]:
  327.  
  328. # GRADED FUNCTION: compute_cost
  329.  
  330. def compute_cost(Z3, Y):
  331.     """
  332.    Computes the cost
  333.    
  334.    Arguments:
  335.    Z3 -- output of forward propagation (output of the last LINEAR unit), of shape (6, number of examples)
  336.    Y -- "true" labels vector placeholder, same shape as Z3
  337.    
  338.    Returns:
  339.    cost - Tensor of the cost function
  340.    """
  341.    
  342.     ### START CODE HERE ### (1 line of code)
  343.     cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits = Z3, labels = Y))
  344.     ### END CODE HERE ###
  345.    
  346.     return cost
  347.  
  348.  
  349. # In[ ]:
  350.  
  351. tf.reset_default_graph()
  352.  
  353. with tf.Session() as sess:
  354.     np.random.seed(1)
  355.     X, Y = create_placeholders(64, 64, 3, 6)
  356.     parameters = initialize_parameters()
  357.     Z3 = forward_propagation(X, parameters)
  358.     cost = compute_cost(Z3, Y)
  359.     init = tf.global_variables_initializer()
  360.     sess.run(init)
  361.     a = sess.run(cost, {X: np.random.randn(4,64,64,3), Y: np.random.randn(4,6)})
  362.     print("cost = " + str(a))
  363.  
  364.  
  365. # **Expected Output**:
  366. #
  367. # <table>
  368. #     <td>
  369. #     cost =
  370. #     </td>
  371. #    
  372. #     <td>
  373. #     2.91034
  374. #     </td>
  375. # </table>
  376.  
  377. # ## 1.4 Model
  378. #
  379. # Finally you will merge the helper functions you implemented above to build a model. You will train it on the SIGNS dataset.
  380. #
  381. # You have implemented `random_mini_batches()` in the Optimization programming assignment of course 2. Remember that this function returns a list of mini-batches.
  382. #
  383. # **Exercise**: Complete the function below.
  384. #
  385. # The model below should:
  386. #
  387. # - create placeholders
  388. # - initialize parameters
  389. # - forward propagate
  390. # - compute the cost
  391. # - create an optimizer
  392. #
  393. # Finally you will create a session and run a for loop  for num_epochs, get the mini-batches, and then for each mini-batch you will optimize the function. [Hint for initializing the variables](https://www.tensorflow.org/api_docs/python/tf/global_variables_initializer)
  394.  
  395. # In[ ]:
  396.  
  397. # GRADED FUNCTION: model
  398.  
  399. def model(X_train, Y_train, X_test, Y_test, learning_rate = 0.009,
  400.           num_epochs = 100, minibatch_size = 64, print_cost = True):
  401.     """
  402.    Implements a three-layer ConvNet in Tensorflow:
  403.    CONV2D -> RELU -> MAXPOOL -> CONV2D -> RELU -> MAXPOOL -> FLATTEN -> FULLYCONNECTED
  404.    
  405.    Arguments:
  406.    X_train -- training set, of shape (None, 64, 64, 3)
  407.    Y_train -- test set, of shape (None, n_y = 6)
  408.    X_test -- training set, of shape (None, 64, 64, 3)
  409.    Y_test -- test set, of shape (None, n_y = 6)
  410.    learning_rate -- learning rate of the optimization
  411.    num_epochs -- number of epochs of the optimization loop
  412.    minibatch_size -- size of a minibatch
  413.    print_cost -- True to print the cost every 100 epochs
  414.    
  415.    Returns:
  416.    train_accuracy -- real number, accuracy on the train set (X_train)
  417.    test_accuracy -- real number, testing accuracy on the test set (X_test)
  418.    parameters -- parameters learnt by the model. They can then be used to predict.
  419.    """
  420.    
  421.     ops.reset_default_graph()                         # to be able to rerun the model without overwriting tf variables
  422.     tf.set_random_seed(1)                             # to keep results consistent (tensorflow seed)
  423.     seed = 3                                          # to keep results consistent (numpy seed)
  424.     (m, n_H0, n_W0, n_C0) = X_train.shape            
  425.     n_y = Y_train.shape[1]                            
  426.     costs = []                                        # To keep track of the cost
  427.    
  428.     # Create Placeholders of the correct shape
  429.     ### START CODE HERE ### (1 line)
  430.     X, Y = create_placeholders(n_H0, n_W0, n_C0, n_y)
  431.     ### END CODE HERE ###
  432.  
  433.     # Initialize parameters
  434.     ### START CODE HERE ### (1 line)
  435.     parameters = initialize_parameters()
  436.     ### END CODE HERE ###
  437.    
  438.     # Forward propagation: Build the forward propagation in the tensorflow graph
  439.     ### START CODE HERE ### (1 line)
  440.     Z3 = forward_propagation(X, parameters)
  441.     ### END CODE HERE ###
  442.    
  443.     # Cost function: Add cost function to tensorflow graph
  444.     ### START CODE HERE ### (1 line)
  445.     cost = compute_cost(Z3, Y)
  446.     ### END CODE HERE ###
  447.    
  448.     # Backpropagation: Define the tensorflow optimizer. Use an AdamOptimizer that minimizes the cost.
  449.     ### START CODE HERE ### (1 line)
  450.     optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)
  451.     ### END CODE HERE ###
  452.    
  453.     # Initialize all the variables globally
  454.     init = tf.global_variables_initializer()
  455.      
  456.     # Start the session to compute the tensorflow graph
  457.     with tf.Session() as sess:
  458.        
  459.         # Run the initialization
  460.         sess.run(init)
  461.         #print(num_epochs)
  462.         # Do the training loop
  463.         for epoch in range(num_epochs):
  464.  
  465.             #print("epoch",epoch)
  466.             minibatch_cost = 0.
  467.             num_minibatches = int(m / minibatch_size) # number of minibatches of size minibatch_size in the train set
  468.             seed = seed + 1
  469.             minibatches = random_mini_batches(X_train, Y_train, minibatch_size, seed)
  470.  
  471.             for minibatch in minibatches:
  472.  
  473.                 # Select a minibatch
  474.                 (minibatch_X, minibatch_Y) = minibatch
  475.                 # IMPORTANT: The line that runs the graph on a minibatch.
  476.                 # Run the session to execute the optimizer and the cost, the feedict should contain a minibatch for (X,Y).
  477.                 ### START CODE HERE ### (1 line)
  478.                 #_,temp_cost = sess.run(optimizer,cost,feed_dict={X_train:minibatch_X, Y_train:minibatch_Y})
  479.                 ##optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)
  480.                 _,temp_cost = sess.run([optimizer, cost], feed_dict={X: minibatch_X, Y: minibatch_Y})
  481.                 ##_,temp_cost = sess.run([optimizer, cost], feed_dict={X: minibatch_X, Y: minibatch_Y})
  482.                 ### END CODE HERE ###
  483.                
  484.                 minibatch_cost += temp_cost / num_minibatches
  485.                
  486.  
  487.             # Print the cost every epoch
  488.             if print_cost == True and epoch % 5 == 0:
  489.                 print ("Cost after epoch %i: %f" % (epoch, minibatch_cost))
  490.             if print_cost == True and epoch % 1 == 0:
  491.                 costs.append(minibatch_cost)
  492.        
  493.        
  494.         # plot the cost
  495.         plt.plot(np.squeeze(costs))
  496.         plt.ylabel('cost')
  497.         plt.xlabel('iterations (per tens)')
  498.         plt.title("Learning rate =" + str(learning_rate))
  499.         plt.show()
  500.  
  501.         # Calculate the correct predictions
  502.         predict_op = tf.argmax(Z3, 1)
  503.         correct_prediction = tf.equal(predict_op, tf.argmax(Y, 1))
  504.        
  505.         # Calculate accuracy on the test set
  506.         accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
  507.         print(accuracy)
  508.         train_accuracy = accuracy.eval({X: X_train, Y: Y_train})
  509.         test_accuracy = accuracy.eval({X: X_test, Y: Y_test})
  510.         print("Train Accuracy:", train_accuracy)
  511.         print("Test Accuracy:", test_accuracy)
  512.                
  513.         return train_accuracy, test_accuracy, parameters
  514.  
  515.  
  516. # Run the following cell to train your model for 100 epochs. Check if your cost after epoch 0 and 5 matches our output. If not, stop the cell and go back to your code!
  517.  
  518. # In[ ]:
  519.  
  520. _, _, parameters = model(X_train, Y_train, X_test, Y_test)
  521.  
  522.  
  523. # **Expected output**: although it may not match perfectly, your expected output should be close to ours and your cost value should decrease.
  524. #
  525. # <table>
  526. # <tr>
  527. #     <td>
  528. #     **Cost after epoch 0 =**
  529. #     </td>
  530. #
  531. #     <td>
  532. #       1.917929
  533. #     </td>
  534. # </tr>
  535. # <tr>
  536. #     <td>
  537. #     **Cost after epoch 5 =**
  538. #     </td>
  539. #
  540. #     <td>
  541. #       1.506757
  542. #     </td>
  543. # </tr>
  544. # <tr>
  545. #     <td>
  546. #     **Train Accuracy   =**
  547. #     </td>
  548. #
  549. #     <td>
  550. #       0.940741
  551. #     </td>
  552. # </tr>
  553. #
  554. # <tr>
  555. #     <td>
  556. #     **Test Accuracy   =**
  557. #     </td>
  558. #
  559. #     <td>
  560. #       0.783333
  561. #     </td>
  562. # </tr>
  563. # </table>
  564.  
  565. # Congratulations! You have finised the assignment and built a model that recognizes SIGN language with almost 80% accuracy on the test set. If you wish, feel free to play around with this dataset further. You can actually improve its accuracy by spending more time tuning the hyperparameters, or using regularization (as this model clearly has a high variance).
  566. #
  567. # Once again, here's a thumbs up for your work!
  568.  
  569. # In[ ]:
  570.  
  571. fname = "images/thumbs_up.jpg"
  572. image = np.array(ndimage.imread(fname, flatten=False))
  573. my_image = scipy.misc.imresize(image, size=(64,64))
  574. plt.imshow(my_image)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement