[Pytorch][转载]用numpy实现两层神经网络

一个全连接ReLU神经网络,一个隐藏层,没有bias。用来从x预测y,使用L2 Loss。

 

这一实现完全使用numpy来计算前向神经网络,loss,和反向传播。

 

numpy ndarray是一个普通的n维array。它不知道任何关于深度学习或者梯度(gradient)的知识,也不知道计算图(computation graph),只是一种用来计算数学运算的数据结构。
 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

    

    # loss = (y_pred - y) ** 2

    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[h < 0] = 0

    grad_w1 = x.T.dot(grad_h)

 

    # Update weights

    w1 -= learning_rate * grad_w1

    w2 -= learning_rate * grad_w2

总结:从上面可以看出,所谓神经网络本质就是前向传播--->求LOSS--->反向传播求梯度---->更新权重。面试经常问这个必须要掌握哦 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

FL1623863129

你的打赏是我写文章最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值