本篇文章大部分内容翻译自learning pytorch with examples。
1.PyTorch介绍
PyTorch是使用GPU和CPU优化的深度学习张量库,该项目2017年1月由facebook开源,短短两年时间,github上星数已经有25000+,增长速度非常快。
PyTorch的底层和Torch框架一样,但是使用Python重新写了很多内容,不仅更加灵活,支持动态图,而且提供了Python接口。是一个以Python优先的深度学习框架,PyTorch既可以看作加入了GPU支持的numpy,同时也可以看成一个拥有自动求导功能的强大的深度神经网络。除了Facebook外,它已经被Twitter、CMU和Salesforce等机构采用。最近看到大神贾清扬的一段采访,说目前facebook一半以上的应用使用pytorch搭建,fb对此的投入还是很大的。
下面代码来自文献2官方的example,说说深度学习与反向传播及python如何实现。输入batch为64,长度为1000的张量,经过FC + ReLU + FC,损失函数定义为MSE,输出batch为64,长度为10的张量。
2.examples
(1)numpy实现
numpy是python进行数值计算的库,这个库中主要的处理都是由C和C++实现的,因此效率还是很高的。
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) #64*1000
y = np.random.randn(N, D_out) #64*10
# Randomly initialize weights
w1 = np.random.randn(D_in, H) #1000*100
w2 = np.random.randn(H, D_out) #100*10
learning_rate = 1e-6
for t in range(500):
# Forward pass: compute predicted y
h = x.dot(w1) #same to np.dot(x,w1), h:64*100
h_relu = np.maximum(h, 0) #64*100
y_pred = h_relu.dot(w2) #64*10
# 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_p