2092240e04
Date: 20240427 Design by JRNitre
26 lines
587 B
Python
26 lines
587 B
Python
import numpy as np
|
|
import matplotlib.pyplot as plt
|
|
|
|
# 转化矩阵
|
|
x = np.linspace(0, 10, 30).reshape(-1, 1)
|
|
|
|
# 斜率和截距 随机生成
|
|
w = np.random.randint(1, 5, 1)
|
|
b = np.random.randint(1, 10, 1)
|
|
|
|
# 根据一元一次方程计算目标值 y , 并加上 噪声, 数据上下有波动
|
|
y = x * w + b + np.random.randn(30, 1)
|
|
plt.scatter(x, y)
|
|
|
|
# 重构 x, b 截距
|
|
x = np.column_stack([x, np.full((30, 1), 1)])
|
|
|
|
# 正规方程求解
|
|
a = np.linalg.inv(x.T.dot(x)).dot(x.T).dot(y).round(2)
|
|
|
|
print(w, b)
|
|
print(a)
|
|
|
|
# 输出回归线性图
|
|
plt.plot(x[:, 0], x.dot(a), 'green')
|
|
plt.show() |