请用python写一个拥有5个变量神经网络预测模型代码
时间: 2024-05-12 10:16:57 浏览: 104
好的,以下是一个简单的使用PyTorch框架编写的拥有5个变量的神经网络预测模型代码示例:
```python
import torch
import torch.nn as nn
from torch.utils.data import DataLoader, Dataset
# 定义数据集
class MyDataset(Dataset):
def __init__(self, x, y):
self.x = torch.from_numpy(x).float()
self.y = torch.from_numpy(y).float()
def __getitem__(self, index):
return self.x[index], self.y[index]
def __len__(self):
return len(self.x)
# 定义神经网络模型
class MyModel(nn.Module):
def __init__(self):
super(MyModel, self).__init__()
self.fc1 = nn.Linear(5, 10)
self.fc2 = nn.Linear(10, 1)
def forward(self, x):
x = torch.relu(self.fc1(x))
x = self.fc2(x)
return x
# 定义训练函数
def train(model, loader, optimizer, criterion, epochs):
for epoch in range(epochs):
running_loss = 0.0
for inputs, labels in loader:
optimizer.zero_grad()
outputs = model(inputs)
loss = criterion(outputs, labels.unsqueeze(1))
loss.backward()
optimizer.step()
running_loss += loss.item()
print('Epoch {} loss: {}'.format(epoch+1, running_loss/len(loader)))
# 定义测试函数
def test(model, loader):
with torch.no_grad():
total_loss = 0.0
for inputs, labels in loader:
outputs = model(inputs)
loss = criterion(outputs, labels.unsqueeze(1))
total_loss += loss.item()
print('Test loss: {}'.format(total_loss/len(loader)))
# 定义数据集和加载器
x_train = np.random.rand(1000, 5)
y_train = np.sum(x_train, axis=1) + np.random.normal(0, 0.1, size=(1000,))
dataset_train = MyDataset(x_train, y_train)
loader_train = DataLoader(dataset_train, batch_size=32, shuffle=True)
x_test = np.random.rand(100, 5)
y_test = np.sum(x_test, axis=1)
dataset_test = MyDataset(x_test, y_test)
loader_test = DataLoader(dataset_test, batch_size=32)
# 初始化模型、损失函数和优化器
model = MyModel()
criterion = nn.MSELoss()
optimizer = torch.optim.Adam(model.parameters())
# 训练模型并测试
train(model, loader_train, optimizer, criterion, epochs=10)
test(model, loader_test)
```
这个模型采用了一个两层的全连接神经网络,包含5个输入变量和1个输出变量,用于对输入数据进行回归预测。训练过程使用了均方误差作为损失函数,并采用了Adam优化算法进行模型参数的更新。在使用时,需要将输入数据以Numpy数组的形式传入,并使用PyTorch的DataLoader对象进行批量加载和训练。
阅读全文