在上面给出的代码里加入预测值和对应的实际值的散点图作为模型的拟合效果展示图,请给出完整代码
时间: 2024-03-19 17:46:23 浏览: 67
好的,以下是加入预测值和实际值散点图的完整代码:
```
import numpy as np
import matplotlib.pyplot as plt
# 构造数据
np.random.seed(42)
x = np.linspace(0, 10, 100)
y = x**2 + np.random.normal(loc=0, scale=5, size=100)
# 数据可视化
plt.scatter(x, y)
plt.show()
# 将数据分为训练集和测试集
split_idx = int(len(x) * 0.8)
x_train, y_train = x[:split_idx], y[:split_idx]
x_test, y_test = x[split_idx:], y[split_idx:]
# 定义模型
def linear_regression(x_train, y_train):
x_mean = np.mean(x_train)
y_mean = np.mean(y_train)
numerator = 0
denominator = 0
for i in range(len(x_train)):
numerator += (x_train[i] - x_mean) * (y_train[i] - y_mean)
denominator += (x_train[i] - x_mean) ** 2
slope = numerator / denominator
intercept = y_mean - slope * x_mean
return slope, intercept
# 训练模型
slope, intercept = linear_regression(x_train, y_train)
# 预测
y_pred = slope * x_test + intercept
# 计算均方误差
mse = np.mean((y_pred - y_test) ** 2)
print("均方误差:", mse)
# 可视化拟合效果
plt.scatter(x_test, y_test, label="实际值")
plt.plot(x_test, y_pred, color="orange", label="预测值")
plt.legend()
plt.show()
# 可视化预测值和实际值的散点图
plt.scatter(y_pred, y_test)
plt.xlabel("预测值")
plt.ylabel("实际值")
plt.show()
```
在加入预测值和实际值散点图的部分,我们首先创建一个新的图表对象,然后使用 `plt.scatter` 函数绘制预测值和实际值的散点图。其中,x 轴表示预测值,y 轴表示实际值。最后调用 `plt.show` 函数显示图表即可。
阅读全文