生成向量
# Create tensors of shape (10, 3) and (10, 2).
x = torch.randn(10, 3)
y = torch.randn(10, 2)
构建网络结构
# Build a fully connected layer。线性,输入三个特征,输出两个特征
linear = nn.Linear(3, 2)
损失函数
# Build loss function and optimizer. uild loss function and optimizer. 均方损失函数,随机梯度下降法
criterion = nn.MSELoss()
optimizer = torch.optim.SGD(linear.parameters(), lr=0.01)
计算结果,比较误差
# Forward pass.
pred = linear(x)
# Compute loss.
loss = criterion(pred, y)
迭代
# Backward pass.
loss.backward()
optimizer.step()
算是完成了一个完整训练过程,后面再调整权值,重复训练即可。