import torch
from torch import nn
# 自定义数据集
# 确定随机数种子
torch.manual_seed(7)
# 产生7张2*2的图片
x = torch.rand((7, 2, 2))
# 标签为0,1,2
y = torch.randint(0, 3, (7,))
print(x)
print(y)
tensor([[[0.5349, 0.1988],
[0.6592, 0.6569]],
[[0.2328, 0.4251],
[0.2071, 0.6297]],
[[0.3653, 0.8513],
[0.8549, 0.5509]],
[[0.2868, 0.2063],
[0.4451, 0.3593]],
[[0.7204, 0.0731],
[0.9699, 0.1078]],
[[0.8829, 0.4132],
[0.7572, 0.6948]],
[[0.5209, 0.5932],
[0.8797, 0.6286]]])
tensor([0, 2, 0, 1, 0, 1, 1])
class LinearNet(nn.Module):
def __init__(self):
super(LinearNet, self).__init__()
self.dense = nn.Linear(4, 3)
self.softmax = nn.Softmax(dim = 1)
def forward(self, x):
y = self.dense(x.view(-1,4))
y = self.softmax(y)
return y
net = LinearNet()
loss = nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(net.parameters(), lr=0.1)
y_hat = net(x)
print(y_hat)
tensor([[0.4235, 0.4221, 0.1544],
[0.3856, 0.4015, 0.2129],
[0.3261, 0.4576, 0.2163],
[0.4156, 0.3965, 0.1878],
[0.4704, 0.3792, 0.1505],
[0.4407, 0.3966, 0.1627],
[0.3677, 0.4519, 0.1804]], grad_fn=<SoftmaxBackward0>)
for epoch in range(70):
train_loss = 0.0
y_hat = net(x)
l = loss(y_hat, y)
optimizer.zero_grad()
l.sum().backward()
optimizer.step()
train_loss += l
if epoch >= 5:
continue
print('epoch %d, loss %.4f' % (epoch + 1, train_loss))
epoch 1, loss 1.0086
epoch 2, loss 1.0086
epoch 3, loss 1.0085
epoch 4, loss 1.0085
epoch 5, loss 1.0084