知识点梳理

python工具使用:

  1. sklearn: 数据挖掘,数据分析工具,内置logistic回归
  2. matplotlib: 做图工具,可绘制等高线等
  3. 绘制散点图: plt.scatter(X[0, :], X[1, :], c=np.squeeze(Y), s=40, cmap=plt.cm.Spectral); s:绘制点大小 cmap:颜色集
  4. 绘制等高线: 先做网格,计算结果,绘图
     x_min, x_max = X[0, :].min() - 1, X[0, :].max() + 1y_min, y_max = X[1, :].min() - 1, X[1, :].max() + 1h = 0.01xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))Z = model(np.c_[xx.ravel(), yy.ravel()])Z = Z.reshape(xx.shape)#xx是x轴值, yy是y轴值, Z是预测结果值, cmap表示采用什么颜色plt.contourf(xx, yy, Z, cmap=plt.cm.Spectral)

关键变量:

  • m: 训练样本数量
  • n_x:一个训练样本的输入数量,输入层大小
  • n_h:隐藏层大小
  • 方括号上标[l]: 第l层
  • 圆括号上标(i): 第i个样本

$$ X = \left[ \begin{matrix} \vdots & \vdots & \vdots & \vdots \\ x^{(1)} & x^{(2)} & \vdots & x^{(m)} \\ \vdots & \vdots & \vdots & \vdots \\ \end{matrix} \right]_{(n\_x, m)} $$

$$ W^{[1]} = \left[ \begin{matrix} \cdots & w^{[1] T}_1 & \cdots \\ \cdots & w^{[1] T}_2 & \cdots \\ \cdots & \cdots & \cdots \\ \cdots & w^{[1] T}_{n\_h} & \cdots \\ \end{matrix} \right]_{(n\_h, n\_x)} $$

$$ b^{[1]} = \left[ \begin{matrix} b^{[1]}_1 \\ b^{[1]}_2 \\ \vdots \\ b^{[1]}_{n\_h} \\ \end{matrix} \right]_{(n\_h, 1)} $$

$$ A^{[1]}= \left[ \begin{matrix} \vdots & \vdots & \vdots & \vdots \\ a^{[1](1)} & a^{[1](2)} & \vdots & a^{[1](m)} \\ \vdots & \vdots & \vdots & \vdots \\ \end{matrix} \right]_{(n\_h, m)} $$

$$ Z^{[1]}= \left[ \begin{matrix} \vdots & \vdots & \vdots & \vdots \\ z^{[1](1)} & z^{[1](2)} & \vdots & z^{[1](m)} \\ \vdots & \vdots & \vdots & \vdots \\ \end{matrix} \right]_{(n\_h, m)} $$


单隐层神经网络关键公式:

  • 前向传播:

$$Z^{[1]}=W^{[1]}X+b^{[1]}$$ $$A^{[1]}=g^{[1]}(Z^{[1]})$$ $$Z^{[2]}=W^{[2]}A^{[1]}+b^{[2]}$$ $$A^{[2]}=g^{[2]}(Z^{[2]})$$

    Z1 = np.dot(W1, X) + b1  A1 = np.tanh(Z1)  Z2 = np.dot(W2, A1) + b2  A2 = sigmoid(Z2)  
  • 反向传播
    dZ2 = A2 - Y   dW2 = 1 / m * np.dot(dZ2, A1.T)  db2 = 1 / m * np.sum(dZ2, axis = 1, keepdims = True)    dZ1 = np.dot(W2.T, dZ2) * (1 - np.power(A1, 2))    dW1 = 1 / m * np.dot(dZ1, X.T)  db1 = 1 / m * np.sum(dZ1, axis = 1, keepdims = True)  
  • cost计算

\[J = - \frac{1}{m} \sum\limits_{i = 0}^{m} \large{(} \small y^{(i)}\log\left(a^{[2] (i)}\right) + (1-y^{(i)})\log\left(1- a^{[2] (i)}\right) \large{)} \small\]

    logprobs = np.multiply(np.log(A2), Y) + np.multiply(np.log(1 - A2), 1 - Y)  cost = - 1 / m * np.sum(logprobs)

单隐层神经网络代码:

# Package imports
import numpy as np
import matplotlib.pyplot as plt
import sklearn
import sklearn.datasets
import sklearn.linear_model
from planar_utils import plot_decision_boundary, sigmoid, load_planar_dataset, load_extra_datasets%matplotlib inlinenp.random.seed(1) # set a seed so that the results are consistentdef initialize_parameters(n_x, n_h, n_y):np.random.seed(2) # we set up a seed so that your output matches ours although the initialization is random.W1 = np.random.randn(n_h, n_x) * 0.01b1 = np.zeros((n_h, 1))W2 = np.random.randn(n_y, n_h)b2 = np.zeros((n_y, 1))assert (W1.shape == (n_h, n_x))assert (b1.shape == (n_h, 1))assert (W2.shape == (n_y, n_h))assert (b2.shape == (n_y, 1))parameters = {"W1": W1,"b1": b1,"W2": W2,"b2": b2}return parametersdef forward_propagation(X, parameters):# Retrieve each parameter from the dictionary "parameters"W1 = parameters["W1"]b1 = parameters["b1"]W2 = parameters["W2"]b2 = parameters["b2"]# Implement Forward Propagation to calculate A2 (probabilities)Z1 = np.dot(W1, X) + b1A1 = np.tanh(Z1)Z2 = np.dot(W2, A1) + b2A2 = sigmoid(Z2)assert(A2.shape == (1, X.shape[1]))cache = {"Z1": Z1,"A1": A1,"Z2": Z2,"A2": A2}return A2, cachedef compute_cost(A2, Y, parameters):m = Y.shape[1] # number of example# Compute the cross-entropy costlogprobs = np.multiply(np.log(A2), Y) + np.multiply(np.log(1 - A2), 1 - Y)cost = - 1 / m * np.sum(logprobs)cost = np.squeeze(cost)     # makes sure cost is the dimension we expect. # E.g., turns [[17]] into 17 assert(isinstance(cost, float))return costdef backward_propagation(parameters, cache, X, Y):m = X.shape[1]# First, retrieve W1 and W2 from the dictionary "parameters".W1 = parameters["W1"]W2 = parameters["W2"]# Retrieve also A1 and A2 from dictionary "cache".A1 = cache["A1"]A2 = cache["A2"]# Backward propagation: calculate dW1, db1, dW2, db2. dZ2 = A2 - Y dW2 = 1 / m * np.dot(dZ2, A1.T)db2 = 1 / m * np.sum(dZ2, axis = 1, keepdims = True)dZ1 = np.dot(W2.T, dZ2) * (1 - np.power(A1, 2)) dW1 = 1 / m * np.dot(dZ1, X.T)db1 = 1 / m * np.sum(dZ1, axis = 1, keepdims = True)grads = {"dW1": dW1,"db1": db1,"dW2": dW2,"db2": db2}return gradsdef update_parameters(parameters, grads, learning_rate = 0.8):# Retrieve each parameter from the dictionary "parameters"W1 = parameters["W1"]b1 = parameters["b1"]W2 = parameters["W2"]b2 = parameters["b2"]# Retrieve each gradient from the dictionary "grads"dW1 = grads["dW1"]db1 = grads["db1"]dW2 = grads["dW2"]db2 = grads["db2"]# Update rule for each parameterW1 = W1 - learning_rate * dW1b1 = b1 - learning_rate * db1W2 = W2 - learning_rate * dW2b2 = b2 - learning_rate * db2parameters = {"W1": W1,"b1": b1,"W2": W2,"b2": b2}return parametersdef nn_model(X, Y, n_h, num_iterations = 10000, print_cost=False):np.random.seed(3)n_x = X.shape[0]n_y = Y.shape[0]# Initialize parameters, then retrieve W1, b1, W2, b2. Inputs: "n_x, n_h, n_y". Outputs = "W1, b1, W2, b2, parameters".parameters = initialize_parameters(n_x, n_h, n_y)W1 = parameters["W1"]b1 = parameters["b1"]W2 = parameters["W2"]b2 = parameters["b2"]# Loop (gradient descent)for i in range(0, num_iterations):# Forward propagation. Inputs: "X, parameters". Outputs: "A2, cache".A2, cache = forward_propagation(X, parameters)# Cost function. Inputs: "A2, Y, parameters". Outputs: "cost".cost = compute_cost(A2, Y, parameters)# Backpropagation. Inputs: "parameters, cache, X, Y". Outputs: "grads".grads = backward_propagation(parameters, cache, X, Y)# Gradient descent parameter update. Inputs: "parameters, grads". Outputs: "parameters".parameters = update_parameters(parameters, grads)# Print the cost every 1000 iterationsif print_cost and i % 1000 == 0:print ("Cost after iteration %i: %f" %(i, cost))return parametersdef predict(parameters, X):# Computes probabilities using forward propagation, and classifies to 0/1 using 0.5 as the threshold.A2, cache =  forward_propagation(X, parameters)predictions = A2 > 0.5return predictionsX, Y = load_planar_dataset()
# Build a model with a n_h-dimensional hidden layer
parameters = nn_model(X, Y, n_h = 4, num_iterations = 10000, print_cost=True)# Plot the decision boundary
plot_decision_boundary(lambda x: predict(parameters, x.T), X, np.squeeze(Y))
plt.title("Decision Boundary for hidden layer size " + str(4))
# planar_utils.py
import matplotlib.pyplot as plt
import numpy as np
import sklearn
import sklearn.datasets
import sklearn.linear_modeldef plot_decision_boundary(model, X, y):# Set min and max values and give it some paddingx_min, x_max = X[0, :].min() - 1, X[0, :].max() + 1y_min, y_max = X[1, :].min() - 1, X[1, :].max() + 1h = 0.01# Generate a grid of points with distance h between them# 创造网格,以0.01为间隔划分整个区间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# xx是x轴值, yy是y轴值, Z是预测结果值, cmap表示采用什么颜色plt.contourf(xx, yy, Z, cmap=plt.cm.Spectral) #等位线plt.ylabel('x2')plt.xlabel('x1')plt.scatter(X[0, :], X[1, :], c=y, cmap=plt.cm.Spectral)def sigmoid(x):"""Compute the sigmoid of xArguments:x -- A scalar or numpy array of any size.Return:s -- sigmoid(x)"""s = 1/(1+np.exp(-x))return sdef load_planar_dataset():np.random.seed(1)m = 400 # number of examplesN = int(m/2) # number of points per classD = 2 # dimensionalityX = np.zeros((m,D)) # data matrix where each row is a single exampleY = np.zeros((m,1), dtype='uint8') # labels vector (0 for red, 1 for blue)a = 4 # maximum ray of the flowerfor j in range(2):ix = range(N*j,N*(j+1))t = np.linspace(j*3.12,(j+1)*3.12,N) + np.random.randn(N)*0.2 # thetar = a*np.sin(4*t) + np.random.randn(N)*0.2 # radiusX[ix] = np.c_[r*np.sin(t), r*np.cos(t)]Y[ix] = jX = X.TY = Y.Treturn X, Ydef load_extra_datasets():  N = 200noisy_circles = sklearn.datasets.make_circles(n_samples=N, factor=.5, noise=.3)noisy_moons = sklearn.datasets.make_moons(n_samples=N, noise=.2)blobs = sklearn.datasets.make_blobs(n_samples=N, random_state=5, n_features=2, centers=6)gaussian_quantiles = sklearn.datasets.make_gaussian_quantiles(mean=None, cov=0.5, n_samples=N, n_features=2, n_classes=2, shuffle=True, random_state=None)no_structure = np.random.rand(N, 2), np.random.rand(N, 2)return noisy_circles, noisy_moons, blobs, gaussian_quantiles, no_structure

【深度学习】吴恩达网易公开课练习(class1 week3)相关推荐

  1. 深度学习-吴恩达-笔记-7-超参数调试、Batch正则化和程序框架

    目录 调试处理 为超参数选择合适的范围 超参数调试实践: Pandas VS Caviar 归一化网络的激活函数 将 Batch Norm 拟合进神经网络 Batch Norm 为什么奏效? 测试时的 ...

  2. 深度学习-吴恩达-笔记-6-优化算法

    目录 Mini-batch 梯度下降 理解 mini-batch 梯度下降法 指数加权平均数 理解指数加权平均数 指数加权平均的偏差修正 动量梯度下降法 ( Gradient descent with ...

  3. 深度学习-吴恩达-笔记-5-深度学习的实践层面

    目录 训练.验证.测试集 偏差.方差 机器学习基础 正则化 为什么正则化有利于预防过拟合 dropout正则化 理解dropout 其它正则化方法 归一化输入 梯度消失/梯度爆炸 神经网络的权重初始化 ...

  4. 深度学习-吴恩达-笔记-4-深层神经网络

    目录 深层神经网络 前向传播和反向传播 深层网络中的前向传播 核对矩阵的维数 为什么使用深层表示 搭建神经网络块 参数 VS 超参数 深度学习和大脑的关联性 [此为本人学习吴恩达的深度学习课程的笔记记 ...

  5. 深度学习-吴恩达-笔记-3-浅层神经网络

    目录 神经网络概述 神经网络的表示 计算一个神经网络的输出 多样本向量化 向量化实现的解释 激活函数 为什么需要非线性激活函数 激活函数的导数 神经网络的梯度下降 直观理解反向传播 随机初始化 [此为 ...

  6. 深度学习-吴恩达-笔记-2-神经网络的编程基础

    目录 二分类 逻辑回归 逻辑回归的代价函数 梯度下降法 导数 计算图 使用计算图求导 逻辑回归中的梯度下降 m个样本的梯度下降 向量化 向量化的更多例子 向量化逻辑回归 向量化逻辑回归的梯度输出 Py ...

  7. 深度学习-吴恩达-笔记-1-深度学习引言

    目录 什么是神经网络 神经网络的监督学习 为什么深度学习会兴起 [此为本人学习吴恩达的深度学习课程的笔记记录,有错误请指出!] 什么是神经网络 让我们从一个房价预测的例子开始讲起,如根据房子面积来预测 ...

  8. 吴恩达卷积神经网络笔记,吴恩达人工智能公开课

    吴恩达是个谁 吴恩达(1976-,英文名:AndrewNg),华裔美国人,是斯坦福大学计算机科学系和电子工程系副教授,人工智能实验室主任.吴恩达是人工智能和机器学习领域国际上最权威的学者之一. 吴恩达 ...

  9. 【深度学习-吴恩达】L1-4 深层神经网络 作业

    L1 深度学习概论 4 深层神经网络 作业链接:吴恩达<深度学习> - Heywhale.com 0 作业任务 构建一个任意层数的深度神经网络 实现构建深度神经网络所需的所有函数 使用这些 ...

最新文章

  1. 计划任务执行php文件,linux系统下添加计划任务执行php文件方法
  2. 链表问题11——两个单链表相交的系列问题(三):判断两个有环链表是否相交
  3. android的文本框内容居中显示图片,DIV+CSS中让布局居中_背景图片居中_文字内容居中...
  4. python.freelycode.com-Python中的并行处理 -- 实例编程指南
  5. 解决Uncaught SyntaxError: Unexpected token var报错问题
  6. 在Servlet中实现页面转发
  7. 【Java代码】道格拉斯-普克 Douglas-Peucker 抽稀算法分析及15w个坐标点抽稀到3.7w耗时从360s+优化到365ms接近1000倍的速度提升源码分享(并行流+多线程+泛型)
  8. Java命令行界面(第20部分):JSAP
  9. IIS 7.0 安装SSL证书过程
  10. 深度解析PolarDB数据库并行查询技术
  11. 信息学奥赛一本通 1029:计算浮点数相除的余 | OpenJudge NOI 1.3 11
  12. 天津理工大学计算机工程学院院长,王法玉
  13. 基于zookeeper实现配置集中管理【转】
  14. 李宏毅机器学习 1.Machine Learning_introduction
  15. 大数据分析常见的几种方法
  16. MATLAB控制系统视频教程
  17. Visio2013激活/破解
  18. SQL Server2005+SQL Server2000下载
  19. 桌面软件图标变白怎么解决
  20. 批量取消关注和删除微博

热门文章

  1. 第二百五十三节,Bootstrap项目实战-资讯
  2. 静态存储区、堆和栈的区别
  3. Go语言 读写锁互斥锁原理剖析(1)
  4. struct的初始化
  5. 分辨率与栅格系统的对应关系:
  6. 编程类-----matlab基础语法复习(1)
  7. Python+Selenium+PIL+Tesseract真正自动识别验证码进行一键登录
  8. iOS----------使用cocoapods遇到的问题
  9. 检测session用户信息跳转首页界面
  10. 【模板】并查集 两种路径压缩写法(类模板和函数模板)