帮我写一段代码,用pytorch实现的神经网络预测模型
时间: 2024-05-14 17:12:10 浏览: 44
Sure, here's a simple example of a neural network prediction model implemented in PyTorch:
```
import torch
import torch.nn as nn
import torch.optim as optim
# Define the neural network architecture
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.fc1 = nn.Linear(1, 10)
self.fc2 = nn.Linear(10, 1)
def forward(self, x):
x = torch.relu(self.fc1(x))
x = self.fc2(x)
return x
# Create an instance of the neural network
net = Net()
# Define the loss function and optimizer
criterion = nn.MSELoss()
optimizer = optim.SGD(net.parameters(), lr=0.01)
# Generate some sample data for training and testing
x_train = torch.randn(100, 1)
y_train = x_train * 2 + torch.randn(100, 1) * 0.1
x_test = torch.randn(20, 1)
y_test = x_test * 2 + torch.randn(20, 1) * 0.1
# Train the neural network
for epoch in range(1000):
optimizer.zero_grad()
output = net(x_train)
loss = criterion(output, y_train)
loss.backward()
optimizer.step()
if epoch % 100 == 0:
print('Epoch {} - Loss: {:.3f}'.format(epoch, loss.item()))
# Test the neural network
with torch.no_grad():
output = net(x_test)
loss = criterion(output, y_test)
print('Test Loss: {:.3f}'.format(loss.item()))
print('Predictions:')
print(output)
```
This code defines a simple neural network with one input and one output, and trains it on some sample data to predict the output based on the input. The network is trained using stochastic gradient descent with a mean squared error loss function. After training, the network is tested on a separate set of test data, and the predictions are printed to the console.
阅读全文
相关推荐
















