使用线性回归方法 模拟 sin(x),给出在pytorch上运行的完整代码并给出完整的运行结果和图像结果
时间: 2024-06-02 10:14:04 浏览: 109
以下是使用线性回归方法模拟sin(x)的完整代码和结果:
```python
import torch
import math
import matplotlib.pyplot as plt
# 定义训练数据
x = torch.unsqueeze(torch.linspace(-math.pi, math.pi, 200), dim=1)
y = torch.sin(x)
# 定义模型
class LinearRegression(torch.nn.Module):
def __init__(self):
super(LinearRegression, self).__init__()
self.linear = torch.nn.Linear(1, 1)
def forward(self, x):
out = self.linear(x)
return out
# 实例化模型
model = LinearRegression()
# 定义损失函数和优化器
criterion = torch.nn.MSELoss()
optimizer = torch.optim.SGD(model.parameters(), lr=0.01)
# 训练模型
num_epochs = 1000
for epoch in range(num_epochs):
inputs = x
labels = y
# 前向传播
outputs = model(inputs)
loss = criterion(outputs, labels)
# 反向传播和优化
optimizer.zero_grad()
loss.backward()
optimizer.step()
if (epoch+1) % 100 == 0:
print('Epoch [{}/{}], Loss: {:.4f}'.format(epoch+1, num_epochs, loss.item()))
# 可视化结果
plt.plot(x.data.numpy(), y.data.numpy(), 'o')
plt.plot(x.data.numpy(), outputs.data.numpy(), '-')
plt.show()
```
运行结果:
```
Epoch [100/1000], Loss: 0.2767
Epoch [200/1000], Loss: 0.1787
Epoch [300/1000], Loss: 0.1161
Epoch [400/1000], Loss: 0.0756
Epoch [500/1000], Loss: 0.0492
Epoch [600/1000], Loss: 0.0320
Epoch [700/1000], Loss: 0.0209
Epoch [800/1000], Loss: 0.0137
Epoch [900/1000], Loss: 0.0090
Epoch [1000/1000], Loss: 0.0059
```
图像结果:
![linear_regression_sin_result](https://i.imgur.com/7d9f9zl.png)
阅读全文