Pytorch构建神经网络多元线性回归模型

1.模型线性方程y = W ∗ X + b 

from torch import nn
import torch

#手动设置的W参数(待模型学习),这里设置为12个,自己随意设置

weight_set=torch.tensor([[1.5,2.38,4.22,6.5,7.2,3.21,4.44,6.55,2.48,-1.75,-3.26,4.78]])

#手动设置的偏置b
bias=torch.tensor([7.25])

#生成100个随机的12个特征的点
torch.random.manual_seed(100)
x=torch.randint(1,10,(100,12))
x=x.float()
#将参数转置
weight_set_trans=weight_set.transpose(0,1)
#y=w*x+b
y_true=torch.matmul(x,weight_set_trans)+bias

2.定义单层的网络结构

#定义模型

class linear_model(nn.Module):
    def __init__(self):
        super().__init__()
        self.layer = nn.Linear(12,1)
    def forward (self, x):
        y = self.layer(x)
        return y
model=linear_model()
h=model(x)
for name ,param in model.named_parameters():
    print(f"{name}:{param}")

output:

layer.weight:Parameter containing:
tensor([[ 0.2429,  0.0523, -0.2873,  0.2485,  0.1396, -0.0960,  0.2534,  0.2423,
          0.0123, -0.2309, -0.22
使用 PyTorch 构建多元线性回归的全连接神经网络,可按以下步骤进行: ### 1. 导入依赖库 需要导入必要的库,如 `numpy` 用于数据处理,`matplotlib.pyplot` 用于数据可视化,`torch` 及其子模块用于构建和训练神经网络。 ```python import numpy as np import matplotlib.pyplot as plt import torch from torch import nn, optim ``` 这里 `numpy` 用来构建数据,`matplotlib.pyplot` 可将构建好的数据可视化,`torch.nn` 包含了 torch 已经准备好的层、激活函数、全连接层等,`torch.optim` 提供了神经网络的一系列优化算法,如 SGD、Adam 等 [^3]。 ### 2. 构建数据 准备多元线性回归所需的数据,通常包括输入特征和对应的目标值。 ```python # 示例:生成一些随机的多元数据 n_samples = 100 n_features = 3 x = np.random.randn(n_samples, n_features) # 真实的权重和偏置 true_weights = np.array([2, -3, 1]) true_bias = 0.5 # 生成目标值 y = np.dot(x, true_weights) + true_bias + 0.1 * np.random.randn(n_samples) # 将数据转换为 PyTorch 张量 x_tensor = torch.tensor(x, dtype=torch.float32) y_tensor = torch.tensor(y, dtype=torch.float32).view(-1, 1) ``` ### 3. 编写神经网络 构建一个简单的全连接神经网络,对于多元线性回归,只需要一个线性层。 ```python class MultipleLinearRegression(nn.Module): def __init__(self, input_size): super(MultipleLinearRegression, self).__init__() self.linear = nn.Linear(input_size, 1) def forward(self, x): return self.linear(x) # 初始化模型 model = MultipleLinearRegression(n_features) ``` ### 4. 定义损失函数和优化器 选择合适的损失函数和优化器。对于线性回归,通常使用均方误差(MSE)作为损失函数,优化器可选择随机梯度下降(SGD)或 Adam 等。 ```python criterion = nn.MSELoss() optimizer = optim.SGD(model.parameters(), lr=0.01) ``` ### 5. 训练神经网络 通过多次迭代训练模型,更新模型的参数。 ```python num_epochs = 1000 for epoch in range(num_epochs): # 前向传播 outputs = model(x_tensor) loss = criterion(outputs, y_tensor) # 反向传播和优化 optimizer.zero_grad() loss.backward() optimizer.step() if (epoch + 1) % 100 == 0: print(f'Epoch [{epoch+1}/{num_epochs}], Loss: {loss.item():.4f}') ``` ### 6. 可视化结果(可选) 可以使用 `matplotlib` 可视化训练结果,观察模型的拟合情况。 ```python # 预测结果 with torch.no_grad(): predicted = model(x_tensor).numpy() plt.scatter(y, predicted) plt.xlabel('True Values') plt.ylabel('Predictions') plt.show() ``` ### 完整代码示例 ```python import numpy as np import matplotlib.pyplot as plt import torch from torch import nn, optim # 生成数据 n_samples = 100 n_features = 3 x = np.random.randn(n_samples, n_features) true_weights = np.array([2, -3, 1]) true_bias = 0.5 y = np.dot(x, true_weights) + true_bias + 0.1 * np.random.randn(n_samples) x_tensor = torch.tensor(x, dtype=torch.float32) y_tensor = torch.tensor(y, dtype=torch.float32).view(-1, 1) # 定义模型 class MultipleLinearRegression(nn.Module): def __init__(self, input_size): super(MultipleLinearRegression, self).__init__() self.linear = nn.Linear(input_size, 1) def forward(self, x): return self.linear(x) model = MultipleLinearRegression(n_features) # 定义损失函数和优化器 criterion = nn.MSELoss() optimizer = optim.SGD(model.parameters(), lr=0.01) # 训练模型 num_epochs = 1000 for epoch in range(num_epochs): outputs = model(x_tensor) loss = criterion(outputs, y_tensor) optimizer.zero_grad() loss.backward() optimizer.step() if (epoch + 1) % 100 == 0: print(f'Epoch [{epoch+1}/{num_epochs}], Loss: {loss.item():.4f}') # 可视化结果 with torch.no_grad(): predicted = model(x_tensor).numpy() plt.scatter(y, predicted) plt.xlabel('True Values') plt.ylabel('Predictions') plt.show() ```
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值