一元线性回归爱心散点图代码
时间: 2024-06-09 17:03:15 浏览: 123
一元线性回归的爱心散点图代码示例如下:
```python
import matplotlib.pyplot as plt
import numpy as np
# 生成随机数据
x = np.array([1, 2, 3, 4, 5, 6, 7, 8])
y = np.array([3, 5, 7, 9, 11, 13, 15, 17])
# 计算斜率和截距
slope, intercept = np.polyfit(x, y, 1)
# 计算预测值
predict_y = slope * x + intercept
# 绘制散点图和回归线
plt.scatter(x, y, color='red', marker='o')
plt.plot(x, predict_y, color='blue')
# 添加标题和坐标轴标签
plt.title('Linear Regression')
plt.xlabel('X')
plt.ylabel('Y')
# 显示图像
plt.show()
```
相关问题
贝叶斯一元线性回归和经典一元线性回归的代码
贝叶斯一元线性回归和经典一元线性回归都是用于建立一个自变量与因变量之间的关系模型的方法。它们的区别在于对模型参数的估计方式不同。经典一元线性回归是通过最小二乘法来估计模型参数,而贝叶斯一元线性回归则是基于贝叶斯定理,利用先验分布和数据集来计算后验分布并进行参数估计。
以下是一个经典一元线性回归的Python代码示例:
```
import numpy as np
import matplotlib.pyplot as plt
# 构造数据集
x = np.array([1, 2, 3, 4, 5])
y = np.array([2.3, 4.5, 6.7, 8.9, 11.1])
# 计算模型参数
n = len(x)
sum_x = np.sum(x)
sum_y = np.sum(y)
sum_xy = np.sum(x * y)
sum_x_square = np.sum(x ** 2)
a = (n * sum_xy - sum_x * sum_y) / (n * sum_x_square - sum_x ** 2)
b = (sum_y - a * sum_x) / n
# 绘制数据散点图和拟合曲线
plt.scatter(x, y)
plt.plot(x, a * x + b, color='r')
plt.show()
```
以下是一个贝叶斯一元线性回归的Python代码示例:
```
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import norm
# 构造数据集
x = np.array([1, 2, 3, 4, 5])
y = np.array([2.3, 4.5, 6.7, 8.9, 11.1])
# 定义先验分布的参数
m0 = 0
s0 = 1
a0 = 1
b0 = 1
# 计算后验分布的参数
n = len(x)
sum_x = np.sum(x)
sum_y = np.sum(y)
sum_xy = np.sum(x * y)
sum_x_square = np.sum(x ** 2)
S = s0 + sum_x_square - (sum_x ** 2) / n
M = (a0 * b0 + sum_xy - a0 * sum_x * sum_y / n) / S
A = a0 + n / 2
B = b0 + s0 / 2 + (sum_y ** 2 + M ** 2 * S - 2 * M * sum_y * sum_x + sum_x_square * S) / 2
# 绘制数据散点图和拟合曲线
plt.scatter(x, y)
# 绘制后验分布的曲线
x_range = np.linspace(0, 6, 100)
y_range = norm.pdf(x_range, loc=M, scale=np.sqrt(S/A))
plt.plot(x_range, y_range, color='g')
plt.show()
```
一元线性回归程序逻辑图
以下是一元线性回归程序的逻辑图:
```
开始
输入数据集 x 和 y
计算 x 和 y 的均值
计算 x 和 y 的标准差
计算 Pearson 相关系数 r
计算斜率 k 和截距 b
计算预测值 y_pred
计算残差 e
计算平均误差 ME 和均方误差 MSE
绘制散点图和回归线
输出斜率 k,截距 b,相关系数 r,平均误差 ME 和均方误差 MSE
结束
```
该逻辑图包括以下步骤:
1. 输入数据集 x 和 y。
2. 计算 x 和 y 的均值和标准差。
3. 计算 Pearson 相关系数 r,判断 x 和 y 是否呈线性关系。
4. 如果呈线性关系,计算斜率 k 和截距 b。
5. 计算预测值 y_pred 和残差 e。
6. 计算平均误差 ME 和均方误差 MSE。
7. 绘制散点图和回归线,用于可视化展示。
8. 输出斜率 k,截距 b,相关系数 r,平均误差 ME 和均方误差 MSE。
9. 结束。
阅读全文
相关推荐
















