我们首先使用 numpy 来实现这个神经网络。
numpy 提供了一个 n 维数组对象和许多操作这些数组的函数。numpy 是一个通用的科学计算框架;它没有计算图、深度学习和梯度的概念。然而我们可以很容易的使用 numpy 的操作手动实现前向传播和反向传播让一个两层的网络来拟合随机数据:
import numpy as np
# N is batch size; D_in is input dimension;
# H is hidden dimension; D_out is output dimension.
N, D_in, H, D_out = 64, 1000, 100, 10
# Create random input and output data
x = np.random.randn(N, D_in)
y = np.random.randn(N, D_out)
# Randomly initialize weights
w1 = np.random.randn(D_in, H)
w2 = np.random.randn(H, D_out)
learning_rate = 1e-6
for t in range(500):
# Forward pass: compute predicted y
h = x.dot(w1)
h_relu = np.maximum(h, 0)
y_pred = h_relu.dot(w2)
# Compute and print loss
loss = np.square(y_pred - y).sum()
print(t, loss)
# Backprop to compute gradients of w1 and w2 with respect to loss
grad_y_pred = 2.0 * (y_pred - y)
grad_w2 = h_relu.T.dot(grad_y_pred)
grad_h_relu = grad_y_pred.dot(w2.T)
grad_h = grad_h_relu.copy()
grad_h_relu[h<0] = 0
grad_w1 = x.T.dot(grad_h)
# update weights
w1 -= learning_rate * grad_w1
w2 -= learning_rate * grad_w2
作者:MaosongRan
链接:https://www.jianshu.com/p/52684285e335
來源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。