机器学习 | 简单数据拟合及实现 实践篇
数据
X=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
Y=[2.94,4.53,5.96,7.88,9.02,10.94,12.14,13.96,14.74,16.68,
17.79,19.67,21.20,22.07,23.75,25.22,27.17,28.84,29.84,31.78]
拟合直线图
<div align=center></div>
拟合的直线方程
<div align=center>直线方程:y=1.4942105263157894x+1.6167894736842054</div>
代码实现
import numpy as np
import matplotlib.pyplot as plt
from scipy import optimize
# 线性
def f_1(x, A, B):
return A*x + B
# 创建自定义图像
fig=plt.figure()
# 创建单个子图(1×1网格的第一子图)
ax=fig.add_subplot(1,1,1)
# 数据导入
X=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
Y=[2.94,4.53,5.96,7.88,9.02,10.94,12.14,13.96,14.74,16.68,
17.79,19.67,21.20,22.07,23.75,25.22,27.17,28.84,29.84,31.78]
# 标出坐标点,点的大小30,颜色green,标签为point
ax.scatter(X,Y,30,color='green',label='point')
# 线性拟合,得到A1,B2值
A1, B1 = optimize.curve_fit(f_1, X, Y)[0]
# 打印A,B值
print("A:",A1)
print("B:",B1)
# 创建x1数组,0-19,步长为0.1
x1 = np.arange(0, 20, 0.1)
# 代入线性模型,得到y1
y1 = A1*x1 + B1
# 画出关于x和y的直线,颜色blue,线宽2.5,线的标签straight
plt.plot(x1, y1, "blue", linewidth=2.5,label='straight')
# x,y轴的范围,上下限
plt.xlim(0,22)
plt.ylim(0,35)
# x,y轴的标签
plt.xlabel('x')
plt.ylabel('y')
# 左上角显示标签
plt.legend(loc='upper left')
# 显示图像
plt.show()
本作品采用 知识共享署名-相同方式共享 4.0 国际许可协议 进行许可。