paddle完成一个简单线性回归最后输出一个散点图
时间: 2024-09-23 09:04:32 浏览: 35
Paddle(PyTorch的开源版本)是一个强大的深度学习框架,用于实现机器学习模型。对于简单的线性回归任务,你可以按照以下步骤操作:
1. 导入必要的库:
```python
import paddle
import numpy as np
from sklearn import datasets
import matplotlib.pyplot as plt
```
2. 加载数据集并预处理:
```python
boston_dataset = datasets.load_boston()
X_train, y_train = boston_dataset.data, boston_dataset.target
```
3. 创建模型,这里是一个基础的线性回归模型:
```python
class LinearRegression(paddle.nn.Layer):
def __init__(self):
super(LinearRegression, self).__init__()
self.linear = paddle.nn.Linear(in_features=13, out_features=1)
def forward(self, x):
return self.linear(x)
```
4. 初始化模型并设置损失函数和优化器:
```python
model = LinearRegression()
criterion = paddle.nn.MSELoss() # Mean Squared Error Loss for regression
optimizer = paddle.optimizer.SGD(parameters=model.parameters(), learning_rate=0.01)
```
5. 训练模型:
```python
num_epochs = 100
for epoch in range(num_epochs):
pred = model(X_train) # Predictions
loss = criterion(pred, y_train.reshape(-1, 1)) # Compute loss
loss.backward() # Backpropagation
optimizer.step()
optimizer.zero_grad()
if (epoch+1) % 10 == 0:
print(f"Epoch {epoch+1}, Loss: {loss.item():.4f}")
```
6. 完成训练后,可以预测新数据并绘制散点图展示结果:
```python
# Generate predictions for the whole dataset and plot them
y_pred = model(X_train).numpy()
plt.scatter(X_train, y_train, color='blue')
plt.plot(X_train, y_pred, color='red', linewidth=2)
plt.xlabel('Feature')
plt.ylabel('Target')
plt.title('Boston Housing Linear Regression Result')
plt.show()
```
阅读全文