loss函数曲线对比曲线代码
时间: 2023-09-28 15:07:34 浏览: 148
函数曲线代码
4星 · 用户满意度95%
以下是一个简单的示例代码,比较两个模型在训练过程中的loss曲线:
```python
import torch
import torch.nn as nn
import torch.optim as optim
import matplotlib.pyplot as plt
# 定义模型1
class Model1(nn.Module):
def __init__(self):
super(Model1, self).__init__()
self.fc1 = nn.Linear(10, 5)
self.fc2 = nn.Linear(5, 1)
self.relu = nn.ReLU()
def forward(self, x):
x = self.relu(self.fc1(x))
x = self.fc2(x)
return x
# 定义模型2
class Model2(nn.Module):
def __init__(self):
super(Model2, self).__init__()
self.fc1 = nn.Linear(10, 5)
self.fc2 = nn.Linear(5, 1)
self.relu = nn.ReLU()
def forward(self, x):
x = self.relu(self.fc1(x))
x = self.fc2(x)
return x
# 定义训练函数
def train(model, optimizer, criterion):
losses = []
for epoch in range(num_epochs):
running_loss = 0.0
for inputs, labels in data_loader:
optimizer.zero_grad()
outputs = model(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
running_loss += loss.item()
epoch_loss = running_loss / len(data_loader)
losses.append(epoch_loss)
print('Epoch [{}/{}], Loss: {:.4f}'.format(epoch+1, num_epochs, epoch_loss))
return losses
# 定义数据集和数据加载器
data = torch.randn(100, 10)
labels = torch.randn(100, 1)
dataset = torch.utils.data.TensorDataset(data, labels)
data_loader = torch.utils.data.DataLoader(dataset, batch_size=10, shuffle=True)
# 定义超参数
num_epochs = 50
learning_rate = 0.1
# 初始化两个模型和优化器
model1 = Model1()
model2 = Model2()
optimizer1 = optim.SGD(model1.parameters(), lr=learning_rate)
optimizer2 = optim.SGD(model2.parameters(), lr=learning_rate)
criterion = nn.MSELoss()
# 分别训练两个模型
losses1 = train(model1, optimizer1, criterion)
losses2 = train(model2, optimizer2, criterion)
# 绘制loss曲线
plt.plot(losses1, label='Model1')
plt.plot(losses2, label='Model2')
plt.legend()
plt.title('Training Loss')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.show()
```
运行以上代码,可以得到两个模型在训练过程中的loss曲线对比图。
阅读全文