本系列旨在通过阅读官方pytorch代码熟悉CNN各个框架的实现方式和流程。
【pytorch官方文档学习之二】tensors
本文是对官方文档PyTorch: Tensors的详细注释和个人理解,欢迎交流。
- tensor 与 numpy的区别
Behind the scenes, Tensors can keep track of a computational graph and gradients, but they’re also useful as a generic tool for scientific computing. Also unlike numpy, PyTorch Tensors can utilize GPUs to accelerate their numeric computations. To run a PyTorch Tensor on GPU, you simply need to cast it to a new datatype. - 实例
# -*- coding: utf-8 -*-
import torch
dtype = torch.float
device = torch.device("cpu")
# device = torch.device("cuda:0") # Uncomment this to run on GPU
# 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 = torch.randn(N, D_in, device=device, dtype=dtype) # 定义输入数据及维度并传入cuda
y = torch.randn(N, D_out, device=device, dtype=dtype) # 定义输出数据及维度并传入cuda
# Randomly initialize weights
w1 = torch.randn(D_in, H, device=device, dtype=dtype) # 随机初始化weights并传入cuda
w2 = torch.randn(H, D_out, device=device, dtype=dtype)
learning_rate = 1e-6 #定义lr
for t in range(500):
# Forward pass: compute predicted y forward
h = x.mm(w1)
h_relu = h.clamp(min=0) # torch.clamp(input, min, max, out = None)→tensor 将输入input张量每个元素的夹紧到区间 [min,max],并返回结果到一个新张量。relu的又一实现方法。
y_pred = h_relu.mm(w2)
# Compute and print loss
loss = (y_pred - y).pow(2).sum().item()
if t % 100 == 99: # 迭代99次
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().mm(grad_y_pred)
grad_h_relu = grad_y_pred.mm(w2.t())
grad_h = grad_h_relu.clone()
grad_h[h < 0] = 0
grad_w1 = x.t().mm(grad_h)
# Update weights using gradient descent 更新weights
w1 -= learning_rate * grad_w1
w2 -= learning_rate * grad_w2
除cuda内容之外,tensor的框架跟numpy一致。