pytorch使用线性回归方法 模拟 sin x
时间: 2024-06-11 09:07:26 浏览: 78
Pytorch模拟线性回归
以下是一个使用PyTorch实现线性回归模拟sin x的例子:
首先,我们需要导入必要的库:
```python
import torch
from torch.autograd import Variable
import numpy as np
import matplotlib.pyplot as plt
```
然后,我们定义模型和损失函数:
```python
# 定义模型
class LinearRegression(torch.nn.Module):
def __init__(self, inputSize, outputSize):
super(LinearRegression, self).__init__()
self.linear = torch.nn.Linear(inputSize, outputSize)
def forward(self, x):
out = self.linear(x)
return out
# 定义损失函数
criterion = torch.nn.MSELoss()
```
接下来,我们生成一些模拟数据:
```python
# 生成模拟数据
x = np.linspace(0,2*np.pi,100)
y = np.sin(x)
x_train = np.array(x, dtype=np.float32).reshape(-1, 1)
y_train = np.array(y, dtype=np.float32).reshape(-1, 1)
```
然后,我们将数据转换为PyTorch张量:
```python
# 转换为PyTorch张量
x_train = torch.from_numpy(x_train)
y_train = torch.from_numpy(y_train)
```
接下来,我们实例化模型和优化器:
```python
# 实例化模型和优化器
inputDim = 1 # 输入特征数
outputDim = 1 # 输出特征数
learningRate = 0.01 # 学习率
epochs = 1000 # 迭代次数
model = LinearRegression(inputDim, outputDim)
optimizer = torch.optim.SGD(model.parameters(), lr=learningRate)
```
然后,我们开始训练模型:
```python
# 训练模型
for epoch in range(epochs):
# 将输入和输出传递给模型
inputs = Variable(x_train)
labels = Variable(y_train)
# 清除梯度缓存
optimizer.zero_grad()
# 前向传播
outputs = model(inputs)
# 计算损失
loss = criterion(outputs, labels)
# 反向传播和优化
loss.backward()
optimizer.step()
if epoch % 100 == 0:
print('epoch {}, loss {}'.format(epoch, loss.item()))
```
最后,我们可以使用训练好的模型进行预测,并将结果可视化:
```python
# 对模型进行预测
predicted = model(x_train).detach().numpy()
# 可视化结果
plt.plot(x_train.numpy(), y_train.numpy(), 'ro', label='Original data')
plt.plot(x_train.numpy(), predicted, label='Fitted line')
plt.legend()
plt.show()
```
完整代码如下:
```python
import torch
from torch.autograd import Variable
import numpy as np
import matplotlib.pyplot as plt
# 定义模型
class LinearRegression(torch.nn.Module):
def __init__(self, inputSize, outputSize):
super(LinearRegression, self).__init__()
self.linear = torch.nn.Linear(inputSize, outputSize)
def forward(self, x):
out = self.linear(x)
return out
# 定义损失函数
criterion = torch.nn.MSELoss()
# 生成模拟数据
x = np.linspace(0,2*np.pi,100)
y = np.sin(x)
x_train = np.array(x, dtype=np.float32).reshape(-1, 1)
y_train = np.array(y, dtype=np.float32).reshape(-1, 1)
# 转换为PyTorch张量
x_train = torch.from_numpy(x_train)
y_train = torch.from_numpy(y_train)
# 实例化模型和优化器
inputDim = 1 # 输入特征数
outputDim = 1 # 输出特征数
learningRate = 0.01 # 学习率
epochs = 1000 # 迭代次数
model = LinearRegression(inputDim, outputDim)
optimizer = torch.optim.SGD(model.parameters(), lr=learningRate)
# 训练模型
for epoch in range(epochs):
# 将输入和输出传递给模型
inputs = Variable(x_train)
labels = Variable(y_train)
# 清除梯度缓存
optimizer.zero_grad()
# 前向传播
outputs = model(inputs)
# 计算损失
loss = criterion(outputs, labels)
# 反向传播和优化
loss.backward()
optimizer.step()
if epoch % 100 == 0:
print('epoch {}, loss {}'.format(epoch, loss.item()))
# 对模型进行预测
predicted = model(x_train).detach().numpy()
# 可视化结果
plt.plot(x_train.numpy(), y_train.numpy(), 'ro', label='Original data')
plt.plot(x_train.numpy(), predicted, label='Fitted line')
plt.legend()
plt.show()
```
阅读全文