导入
import numpy as np
import torch
from torch.autograd import Variable
"""矩阵对比"""
data = np.arange(6).reshape((2, 3)) # numpy形式生成2行3列矩阵
tensor = torch.from_numpy(data) # 转换成tensor形式
print("\nnumpy:", data, "\ntorch:", tensor)
"""列表对比"""
data = [-1, -2, 1, 2] # 创建numpy列表
tensor = torch.FloatTensor(data) # 转换成tensor形式
print("\ndata:", data, "\ntensor:", tensor)
"""矩阵相乘对比"""
data = [[1, 2], [3, 4]] # numpy矩阵
tensor = torch.FloatTensor(data) # 转换为tensor形式
print("\ndata:", np.matmul(data, data), "\ntensor:", torch.mm(tensor, tensor)) # 矩阵相乘
"""variable反向传播"""
tensor = torch.FloatTensor([[1, 2], [3, 4]])
variable = Variable(tensor, requires_grad=True) # 转换成Variable形式确定变量是否可以反向传播
print("\ntensor:", tensor, "\nvariable:", variable)
"""mean对比"""
t_out = torch.mean(tensor * tensor)
v_out = torch.mean(variable * variable) # v_out=1/4*sum(variable*variable)
print("\nt_out:", t_out, "\nv_out:", v_out)
"""反向"""
v_out.backward() # 反向,求导求梯度,d(v_out)/d(variable)=1/4*2*variable=1/2*variable
print("\n",variable.grad)