生成如下代码:损失函数为交叉熵损失,学习率为1e-2,历元为10,优化器为SGD。 请打印每个纪元的损失,并将最终模型另存为“./Model/Model.pth”,设计训练过程
时间: 2024-05-31 10:07:40 浏览: 78
tensorflow中常用交叉熵损失函数(cross_entropy)的比较总结与代码示例
import torch
import torch.nn as nn
import torch.optim as optim
# 定义模型
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.fc1 = nn.Linear(10, 5)
self.fc2 = nn.Linear(5, 2)
def forward(self, x):
x = torch.relu(self.fc1(x))
x = self.fc2(x)
return x
# 准备数据
x = torch.randn(100, 10)
y = torch.randint(0, 2, (100,))
# 定义损失函数和优化器
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(net.parameters(), lr=1e-2)
# 训练模型
net = Net()
for epoch in range(10):
optimizer.zero_grad()
outputs = net(x)
loss = criterion(outputs, y)
loss.backward()
optimizer.step()
print('Epoch [{}/{}], Loss: {:.4f}'.format(epoch+1, 10, loss.item()))
# 保存模型
torch.save(net.state_dict(), './Model/Model.pth')
阅读全文