1. 程式人生 > >吳恩達 神經網路和深度學習 第3周程式設計作業

吳恩達 神經網路和深度學習 第3周程式設計作業

由於csdn的markdown編輯器及其難用,已將本文轉移至此處

Note

These are my personal programming assignments at the third week after studying the course neural-networks-deep-learning and the copyright belongs to deeplearning.ai.

planar data classification with one hidden layer

1 Packages

Let’s first import all the packages that you will need during this assignment.

  • numpy is the fundamental package for scientific computing with Python.
  • sklearn provides simple and efficient tools for data mining and data analysis.
  • matplotlib is a library for plotting graphs in Python.
  • testCases_v2 provides some test examples to assess the correctness of your functions
  • planar_utils provide various useful functions used in this assignment
1
2
3
4
5
6
7
8
9
10
11
12
# Package imports
import numpy as np;
import matplotlib.pyplot as plt;
import sklearn;
import sklearn.datasets;
import sklearn.linear_model;
from testCases_v2 import *;
from planar_utils import plot_decision_boundary, sigmoid, load_planar_dataset, load_extra_datasets;

%matplotlib inline
np.random.seed(1); # set a seed so that the results are consistent

You can get the support code from here.

2 Dataset

First, let’s get the dataset you will work on. The following code will load a “flower” 2-class dataset into variables X and Y.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
def load_planar_dataset():  #generate two random array X and Y
    np.random.seed(1)
    m=400     #樣本的數量
    N=int(m/2) #每一類的數量,共有倆類資料
    D=2  #維數,二維資料
    X=np.zeros((m,D)) # 生成(m,2)獨立的樣本
    Y=np.zeros((m,1),dtype='uint8')  #生成(m,1)矩陣的樣本
    a=4 #maximum ray of the flower
    for j in range(2):
        ix=range(N*j,N*(j+1))  #範圍在[N*j,N*(j+1)]之間
        t=np.linspace(j*3.12,(j+1)*3.12,N)+np.random.randn(N)*0.2  #theta
        r=a*np.sin(4*t)+np.random.randn(N)*0.2  #radius
        X[ix]=np.c_[r*np.sin(t),r*np.cos(t)]   # (m,2),使用np.c_是為了形成(m,2)矩陣
        Y[ix]=j  
    X=X.T   #(2,m)
    Y=Y.T   # (1,m) 
    return X,Y

Visualize the dataset using matplotlib. The data looks like a “flower” with some red (label y=0) and some blue (y=1) points. Your goal is to build a model to fit this data.

1
2
3
X,Y = load_planar_dataset();
plt.scatter(X[0,:], X[1,:], c=np.squeeze(Y),s=40,cmap=plt.cm.Spectral);
plt.show();

png

You have:

  • a numpy-array (matrix) X that contains your features (x1, x2)
  • a numpy-array (vector) Y that contains your labels (red:0, blue:1).

Lets first get a better sense of what our data is like.

Exercise: How many training examples do you have? In addition, what is the shape of the variables X and Y?

Hint: How do you get the shape of a numpy array? (help)

1
2
3
4
5
6
7
8
9
### START CODE HERE ### (≈ 3 lines of code)
shape_X = X.shape
shape_Y = Y.shape
m = X.shape[1]  # training set size
### END CODE HERE ###

print ('The shape of X is: ' + str(shape_X))
print ('The shape of Y is: ' + str(shape_Y))
print ('I have m = %d training examples!' % (m))
The shape of X is: (2, 400)
The shape of Y is: (1, 400)
I have m = 400 training examples!

3 Simple Logistic Regression

Before building a full neural network, lets first see how logistic regression performs on this problem. You can use sklearn’s built-in functions to do that. Run the code below to train a logistic regression classifier on the dataset.

1
2
3
# Train the logistic regression classifier
clf = sklearn.linear_model.LogisticRegressionCV();
clf.fit(X.T, np.squeeze(Y.T));

You can now plot the decision boundary of these models. Run the code below.

1
2
3
4
5
6
7
8
# Plot the decision boundary for logistic regression
plot_decision_boundary(lambda x: clf.predict(x), X, Y)
plt.title("Logistic Regression")

# Print accuracy
LR_predictions = clf.predict(X.T)
print ('Accuracy of logistic regression: %d ' % float((np.dot(Y,LR_predictions) + np.dot(1-Y,1-LR_predictions))/float(Y.size)*100) +
       '% ' + "(percentage of correctly labelled datapoints)")
Accuracy of logistic regression: 47 % (percentage of correctly labelled datapoints)

png

plot_decision_boundary:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
def plot_decision_boundary(model, X, y):
    # Set min and max values and give it some padding
    x_min, x_max = X[0, :].min() - 1, X[0, :].max() + 1
    y_min, y_max = X[1, :].min() - 1, X[1, :].max() + 1
    h = 0.01
    # Generate a grid of points with distance h between them
    xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))
    # Predict the function value for the whole grid
    Z = model(np.c_[xx.ravel(), yy.ravel()])
    Z = Z.reshape(xx.shape)
    # Plot the contour and training examples
    plt.contourf(xx, yy, Z, cmap=plt.cm.Spectral)
    plt.ylabel('x2')
    plt.xlabel('x1')
    plt.scatter(X[0, :], X[1, :], c=np.squeeze(y), cmap=plt.cm.Spectral)

4 Neural Network model

Logistic regression did not work well on the “flower dataset”. You are going to train a Neural Network with a single hidden layer.

Here is our model:

Mathematically:

For one example x(i):
z[1](i)=W[1]x(i)+b[1](i)

a[1](i)=tanh(z[1](i))

z[2](i)=W[2]a[1](i)+b[2](i)

ˆy(i)=a[2](i)=σ(z[2](i))

$$y^{(i)}_{prediction} = \begin{cases} 1 & \mbox{if } a^{2} > 0.5 \\ 0 & \mbox{otherwise } \end{cases}\tag{5}$$

Given the predictions on all the examples, you can also compute the cost J as follows:

J=1mmi=0(y(i)log(a[2](i))+(1y(i))log(1a[2](i)))

Reminder:

The general methodology to build a Neural Network is to:

  1. Define the neural network structure ( # of input units, # of hidden units, etc).
  2. Initialize the model’s parameters
  3. Loop:
    • Implement forward propagation
    • Compute loss
    • Implement backward propagation to get the gradients
    • Update parameters (gradient descent)

You often build helper functions to compute steps 1-3 and then merge them into one function we call nn_model(). Once you’ve built nn_model() and learnt the right parameters, you can make predictions on new data.

4.1 Defining the neural network structure

Exercise: Define three variables:

  • nx : the size of the input layer
  • nh : the size of the hidden layer (set this to 4)
  • ny : the size of the output layer

Hint: Use shapes of X and Y to find nx and ny. Also, hard code the hidden layer size to be 4.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# GRADED FUNCTION: layer_sizes

def layer_sizes(X, Y):
    """
    Arguments:
    X -- input dataset of shape (input size, number of examples)
    Y -- labels of shape (output size, number of examples)

    Returns:
    n_x -- the size of the input layer
    n_h -- the size of the hidden layer
    n_y -- the size of the output layer
    """
    ### START CODE HERE ### (≈ 3 lines of code)
    n_x = X.shape[0]; # size of input layer
    n_h = 4;
    n_y = Y.shape[0];# size of output layer
    ### END CODE HERE ###
    return (n_x, n_h, n_y);
1
2
3
4
5
X_assess, Y_assess = layer_sizes_test_case();
(n_x, n_h, n_y) = layer_sizes(X_assess, Y_assess);
print("The size of the input layer is: n_x = " + str(n_x));
print("The size of the hidden layer is: n_h = " + str(n_h));
print("The size of the output layer is: n_y = " + str(n_y));
The size of the input layer is: n_x = 5
The size of the hidden layer is: n_h = 4
The size of the output layer is: n_y = 2

4.2 Initialize the model’s parameters

Exercise: Implement the function initialize_parameters().

Instructions:

  • Make sure your parameters’ sizes are right. Refer to the neural network figure above if needed.
  • You will initialize the weights matrices with random values.
  • Use: np.random.randn(a,b) * 0.01 to randomly initialize a matrix of shape (a,b).
  • You will initialize the bias vectors as zeros.
  • Use: np.zeros((a,b)) to initialize a matrix of shape (a,b) with zeros.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
            
           

相關推薦

神經網路深度學習 3程式設計作業

由於csdn的markdown編輯器及其難用,已將本文轉移至此處NoteThese are my personal programming assignments at the third week after studying the course neural-netwo

神經網路深度學習 4程式設計作業

由於csdn的markdown編輯器及其難用,已將本文轉移至此處NoteThese are my personal programming assignments at the 4th week after studying the course neural-network

Coursera deep learning 神經網路深度學習 四周 程式設計作業 Building your Deep Neural Network

def two_layer_model(X, Y, layers_dims, learning_rate = 0.0075, num_iterations = 3000, print_cost=False):     """     Implements a two-layer neural network

Coursera 深度學習 deep learning.ai 神經網路深度學習 第一課 第二週 程式設計作業 Python Basics with Numpy

Python Basics with Numpy (optional assignment) Welcome to your first assignment. This exercise gives you a brief introduction to P

DeepLearning.ai(神經網路深度學習) 第二週程式設計作業

轉載於:http://blog.csdn.net/Koala_Tree/article/details/78057033吳恩達Coursera課程 DeepLearning.ai 程式設計作業系列,本文為《神經網路與深度學習》部分的第二週“神經網路基礎”的課程作業(做了無用部分的刪減)。Part 1:Pyth

神經網路深度學習——神經網路基礎習題1

python numpy 基礎 1.使用iPython Notebooks 2.使用numpy 函式 and numpy矩陣或向量操作 3.理解"broadcasting" 4.向量化程式碼 用numpy建立一個基礎函式 sigmoid 函式 math庫

神經網路深度學習——神經網路基礎習題2

神經網路思維的邏輯迴歸 1.初始化引數 2.計算代價函式及其導數 3.使用梯度下降 判斷影象上是否有貓 影象預處理 問題敘述 你得到了一個數據集(“data.h5”),包含: -標記為cat ( y = 1 )或非cat ( y = 0 )的m個訓練集 -標

神經網路深度學習——深度神經網路習題4:DNN分類應用

吳恩達神經網路與深度學習——深度神經網路習題4 DNN影象分類應用 將上次實現的DNN應用於貓分類問題 包 import time import numpy as np import h5py import matplotlib.pyplot as plt i

第一門-神經網路深度學習三週6-10學習筆記

吳恩達第一門-神經網路和深度學習第三週6-10學習筆記 3.6啟用函式 啟用函式 圖中給出了前面課程中所學到的利用神經網路計算輸出值的具體步驟。其中的 σ

第一門-神經網路深度學習第二週6-10學習筆記

神經網路和深度學習第二週6-10學習筆記 6.更多導數的例子 在本節中,為上一節的導數學習提供更多的例子。在上一節中,我們複習了線性函式的求導方法,其導數值在各點中是相等的。本節以y=a^2這一二次函式為例,介紹了導數值在各點處發生變化時的求導方法。求導大家都會,y=x ^3的導數是

Coursera--深度學習-神經網路深度學習-week1-測驗

本文章內容: Coursera吳恩達深度學習課程,第一課神經網路和深度學習Neural Networks and Deep Learning, 第一週:深度學習引言(Introduction to Deep Learning) 部分的測驗,題目及答案截圖。 正確:ABC

Coursera深度學習課程筆記(1-1)神經網路深度學習-深度學習概論

這系列文章是我在學習吳恩達教授深度學習課程時為了加深自己理解,同時方便後來對內容進行回顧而做的筆記,其中難免有錯誤的理解和不太好的表述方式,歡迎各位大佬指正並提供建議。1、什麼是神經網路               在簡單的從房屋面積預測價格時,神經網路可以理解為將輸入的房屋

Deeplearning.ai筆記之神經網路深度學習1

Introduction to Deep Learning What is a neural neural network? 當對於房價進行預測時,因為我們知道房子價格是不可能會有負數的,因此我們讓面積小於某個值時,價格始終為零。 其實對於以上這麼一個預測的模型就可以看

Deeplearning.ai筆記之神經網路深度學習3

Shallow Neural Network Neural Networks Overview 同樣,反向傳播過程也分成兩層。第一層是輸出層到隱藏層,第二層是隱藏層到輸入層。其細節部分我們之後再來討論。 Neural Network Representation

視訊學習課後作業(01.神經網路深度學習--week2/assignment2_2)

最近從頭開始學習深度學習,想借此記錄學習過程用於日後複習或者回看,以下是個人見解,如有錯誤請見諒並指出,謝謝。 目的 Assignment2_2作業主要是引導新手從頭開始建一個用邏輯迴歸分類器( classififier, LR)來識別影象中是否有貓。簡單來說,邏輯迴

學習日記】深度學習工程師微專業第一課:神經網路深度學習

以下內容是我聽吳恩達深度學習微專業第一課做的學習筆記,主要是按自己的理解回答一些問題,並非全部出自課程內容。1. 什麼是神經網路?神經網路是諸多機器學習方法中的一種,受人類大腦工作方式的啟發而發明的。人類大腦的一個神經元通過多個樹突來接收來自不同神經元的訊號,接著細胞核處理訊

深度學習-神經網路深度學習》4--深層神經網路

1. 深層神經網路長什麼樣?所謂深層神經網路其實就是含有更多的隱藏層或隱藏層單元的神經網路。2. 前向傳播深層神經網路前向傳播的向量化實現:這裡需要逐層計算每層的z和a,一般只能用for迴圈(從第1層到第L層,輸入層被稱為第0層)3. 如何確定矩陣的維數n[0]是輸入層的特徵

deeplearning.ai】深度學習(9):迴圈神經網路

隨深度學習技術的發展,使用迴圈神經網路(Recurrent Neural Network,RNN)建立的各種序列模型,使語音識別、機器翻譯及自然語言理解等應用成為可能。 表示與型別 自然語言、音訊等資料都是前後相互關聯的資料,比如理解一句話要通過一整句而

深度學習筆記(四)——神經網路深度學習(淺層神經網路

1.神經網路概覽 神經網路的結構與邏輯迴歸類似,只是神經網路的層數比邏輯迴歸多一層,多出來的中間那層稱為隱藏層或中間層。從計算上來說,神經網路的正向傳播和反向傳播過程只是比邏輯迴歸多了一次重複的計算。正向傳播過程分成兩層,第一層是輸入層到隱藏層,用上標[1]來表示;第二層是隱藏層到輸出層,用上標

神經網路深度學習基本原理

這是看到的一篇對神經網路的講解的文章,我覺得寫得很好,也仔細學習了學習,最近我可能也得用這個東西,現在確實是很火啊,也很實用。   神經網路和深度學習 神經網路:一種可以通過觀測資料使計算機學習的仿生語言範例 深度學習:一組強大的神經網路學習技術