import torch
import torch.nn as nn
import torch.optim as optim
import numpy as np
import matplotlib.pyplot as plt
# 生成一些样例数据
np.random.seed(0)
X_train = torch.FloatTensor(np.random.rand(1000, 3)) # 多维特征数据
y_train = 2 * X_train[:, 0] + 3 * X_train[:, 1] - 5 * X_train[:, 2] + 2 + 0.1 * torch.randn(1000) # 线性关系的标签数据
# 定义 PyTorch 模型
class SimpleModel(nn.Module):
def __init__(self):
super(SimpleModel, self).__init__()
self.fc1 = nn.Linear(3, 5) # 隐藏层1
self.fc2 = nn.Linear(5, 3) # 隐藏层2
self.fc3 = nn.Linear(3, 1) # 输出层
def forward(self, x):
x = torch.relu(self.fc1(x))
x = torch.relu(self.fc2(x))
x = self.fc3(x)
return x
# 创建模型实例
model = SimpleModel()
# 定义损失函数和优化器
criterion = nn.MSELoss()
optimizer = optim.Adam(model.parameters(), lr=0.001)
# 训练模型
epochs = 100
losses = []
for epoch in range(epochs):
# Forward pass
outputs = model(X_train)
loss = criterion(outputs, y_train.view(-1, 1))
# Backward pass and optimization
optimizer.zero_grad()
loss.backward()
optimizer.step()
losses.append(loss.item())
# 绘制训练过程的曲线
plt.plot(losses)
plt.xlabel('Epochs')
plt.ylabel('Loss')
plt.show()
# 预测新数据
X_new = torch.FloatTensor([[0.2, 0.3, 0.4], [0.5, 0.6, 0.7], [0.8, 0.9, 1.0]])
predictions = model(X_new)
print("Predictions:")
print(predictions.detach().numpy())
全连接神经网络Pytorch(直接可用版)
最新推荐文章于 2024-07-16 11:20:53 发布