上面的代码没有验证集的作用
时间: 2024-03-01 16:51:13 浏览: 18
非常抱歉,我的代码确实没有使用验证集。以下是一个使用验证集的修改版:
```python
import torch
import torch.nn as nn
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
# 读取数据
data = pd.read_csv('data.csv')
# 划分特征和标签
X = data.iloc[:, :-1].values
y = data.iloc[:, -1].values
# 标准化特征
sc = StandardScaler()
X = sc.fit_transform(X)
# 划分训练集、测试集和验证集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
X_train, X_val, y_train, y_val = train_test_split(X_train, y_train, test_size=0.2, random_state=0)
# 定义模型
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.fc1 = nn.Linear(40, 64)
self.fc2 = nn.Linear(64, 32)
self.fc3 = nn.Linear(32, 1)
def forward(self, x):
x = torch.relu(self.fc1(x))
x = torch.relu(self.fc2(x))
x = self.fc3(x)
return x
# 实例化模型
net = Net()
# 定义损失函数和优化器
criterion = nn.MSELoss()
optimizer = torch.optim.Adam(net.parameters(), lr=0.001)
# 训练模型
for epoch in range(1000):
optimizer.zero_grad()
outputs = net(torch.Tensor(X_train))
loss = criterion(outputs, torch.Tensor(y_train).unsqueeze(1))
loss.backward()
optimizer.step()
if epoch % 100 == 0:
# 在训练集和验证集上测试模型
with torch.no_grad():
train_outputs = net(torch.Tensor(X_train))
train_loss = criterion(train_outputs, torch.Tensor(y_train).unsqueeze(1))
val_outputs = net(torch.Tensor(X_val))
val_loss = criterion(val_outputs, torch.Tensor(y_val).unsqueeze(1))
print('Epoch [{}/{}], Train Loss: {:.4f}, Val Loss: {:.4f}'.format(epoch+1, 1000, train_loss.item(), val_loss.item()))
# 在测试集上测试模型
with torch.no_grad():
outputs = net(torch.Tensor(X_test))
loss = criterion(outputs, torch.Tensor(y_test).unsqueeze(1))
print('Test Loss: {:.4f}'.format(loss.item()))
```
在这个版本的代码中,我们在每100轮训练之后,都在训练集和验证集上测试了模型的性能,这样可以及时发现模型的过拟合情况。同时我们也增加了验证集的划分,并在训练过程中使用验证集对模型进行了验证。最后在测试集上测试了模型的性能。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)