请随机创建一份单输入单输出的200个数据点的数据集,以7:3的比例分为训练集和测试集。并用以paddlepaddle 2.3.2框架写一份单输入单输出,中间层为一层有10个神经元的全连接神经网络代码,对训练集进行回归训练,对测试集进行预测,并进行mae和rmse评估,绘出R图。最后将模型保存。要求代码每一步骤有详细的注释
时间: 2023-12-20 09:03:49 浏览: 63
用pandas划分数据集实现训练集和测试集
5星 · 资源好评率100%
创建数据集:
```python
import numpy as np
# 创建数据集
data_x = np.random.rand(200, 1).astype(np.float32)
noise = np.random.normal(scale=0.1, size=(200, 1)).astype(np.float32)
data_y = data_x * 3.14 + 1.59 + noise
# 划分训练集和测试集
train_size = int(len(data_x) * 0.7)
train_x, test_x = np.split(data_x, [train_size])
train_y, test_y = np.split(data_y, [train_size])
```
建立模型:
```python
import paddle
from paddle.nn import Linear
class Net(paddle.nn.Layer):
def __init__(self):
super(Net, self).__init__()
# 定义一层线性全连接层
self.fc = Linear(in_features=1, out_features=10)
# 定义一层线性全连接层,输出一个标量值,即预测值
self.predict = Linear(in_features=10, out_features=1)
def forward(self, x):
# 前向传播
x = self.fc(x)
x = paddle.nn.functional.relu(x)
x = self.predict(x)
return x
```
训练模型:
```python
# 定义模型
model = Net()
# 定义优化器
opt = paddle.optimizer.Adam(learning_rate=0.01, parameters=model.parameters())
# 定义损失函数
loss_fn = paddle.nn.MSELoss()
# 训练模型
epochs = 500
batch_size = 10
train_dataset = paddle.dataset.TensorDataset(train_x, train_y)
train_loader = paddle.io.DataLoader(train_dataset, batch_size=batch_size, shuffle=True)
for epoch in range(epochs):
for batch_id, data in enumerate(train_loader()):
x_data = paddle.to_tensor(data[0])
y_data = paddle.to_tensor(data[1])
y_pred = model(x_data)
loss = loss_fn(y_pred, y_data)
loss.backward()
opt.step()
opt.clear_grad()
# 每10个epoch输出一次损失值
if epoch % 10 == 0:
print("Epoch {} loss: {}".format(epoch, loss.numpy()))
```
预测并评估模型:
```python
from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score
import matplotlib.pyplot as plt
# 预测
test_x_tensor = paddle.to_tensor(test_x)
test_y_tensor = paddle.to_tensor(test_y)
y_pred = model(test_x_tensor).numpy()
# 评估
mae = mean_absolute_error(test_y, y_pred)
rmse = np.sqrt(mean_squared_error(test_y, y_pred))
r2 = r2_score(test_y, y_pred)
print("MAE:", mae)
print("RMSE:", rmse)
print("R2:", r2)
# 绘制R图
plt.scatter(test_y, y_pred)
plt.plot(test_y, test_y, color='r')
plt.xlabel('True Value')
plt.ylabel('Predict Value')
plt.show()
```
保存模型:
```python
# 保存模型参数
paddle.save(model.state_dict(), 'model_state.pdparams')
# 加载模型
model.load_dict(paddle.load('model_state.pdparams'))
```
阅读全文