代码教程:https://www.bilibili.com/video/BV1nV41177ko
import torch
import torch.nn as nn
import numpy
from torch import tensor
x = torch.empty(5,3)#创建一个shape(5,3)的0tensor
print(x)
y = torch.rand(5,3)#创建一个shape(5,3)的随机tensor
print(y) #输出为tensor,tensor是一个框架,也是底层,类似与举证
x = torch.tensor([5.5,3])
print(x)#传值,内丝于numpy
x = x.new_ones(5,3,dtype=torch.double)#创建一个元素都为1的tensor
print(x)
x = torch.rand_like(x,dtype = torch.double)
print(x)
print(x.size())#打印大小,类似shape
#view操作可以改变举证的维度
x = torch.randn(4,4)
y = x.view(16)
z = x.view(-1,4)#-1表示自动计算
print(x.size(), y.size(), z.size())
#与numpy的协同操作
#1.tensor转numpy
a = torch.ones(5)
b = a.numpy()
print(b)
#2.numpy转tensor
a = numpy.array([1,2])
b = torch.from_numpy(a)
print(b)
#设置require_grad会自动求导
x = torch.ones(3,4,requires_grad=True)
b = torch.randn(3,4,requires_grad=True)
t = x*x*x + b
print(t.requires_grad) #也支持求导
y = t.sum()
print(y)
y.backward()#反向传播,但是如果不清零会累加
#y.backward(retain_graph=True) retain_qraph允许代码重复执行
print(x.grad)
#x.is_leaf 是否为叶子
#例子:线性回归于模型
#1.初始化训练数据和标签
x_values = [i for i in range(11)]
x_train = numpy.array(x_values,dtype=numpy.float32)
x_train = x_train.reshape(-1,1)
y_values = [i*2+1 for i in range(11)]
y_train = numpy.array(x_values,dtype=numpy.float32)
y_train = x_train.reshape(-1,1)
2.#设计一个类,继承torch.nn的Module
class LinearRegressModel(nn.Module):
def __init__(self,input_dim,output_dim):
#调用父类的构造方法
super(LinearRegressModel, self).__init__()
#创建模型
self.linear = nn.Linear(input_dim,output_dim)
#向前传播
def forward(self,x):
out = torch.sigmoid(self.linear(x))
#out是tensor
return out
input_dim = 1
output_dim = 1
model = LinearRegressModel(input_dim, output_dim)
epochs = 1000
learning_rate = 0.01
optimizer = torch.optim.SGD(model.parameters(),lr=learning_rate)
criterion = nn.MSELoss() #损失函数
x = torch.tensor([1,2,3,4,5,6,7,8,9,10,11], dtype=torch.double)
print(x)
x = x.view(-1,1)
for epoch in range(epochs):
inputs = torch.from_numpy(x_train)
labels = torch.from_numpy(y_train)
optimizer.zero_grad()
outputs = model(inputs)
loss = criterion(outputs,labels)
loss.backward()
optimizer.step() #刷新
if epoch % 50 == 0:
print("epoch {}, loss {}".format(epoch, loss))
#Scalar
x = tensor(42.)
print(x)
print(x.dim()) #打印维度
print(x.item()) #打印
x = tensor([[2,3,4],[4,5,6]])
try:
print(x.item())
except:
print("错误:只有一个元素张量可以转换为向量标量")
#Vector
#例如:[-5,2,0],在深度学习中通常指特征,列入词向量特征,某一维度特征等
v = tensor([1.5,-0.5,3.0])
print(v.size())
print(v.dim())
#Matrix
M = tensor([[1,2],[3,4]])
print(M.matmul(M))