全连接神经网络Pytorch(直接可用版)

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())

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值