python可视化线性拟合的机器学习(Machine Learning)过程
一、导入需要的库import numpy as npimport pandas as pdimport matplotlib.pyplot as plt二、初始化参数x_points = [1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]y_points = [1, 2, 3, 1, 4, 5, 6, 5, 7, 10, 15, 9]m = 0b = 0y = lambd
·
一、导入需要的库
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
二、初始化参数
x_points = [1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
y_points = [1, 2, 3, 1, 4, 5, 6, 5, 7, 10, 15, 9]
m = 0
b = 0
y = lambda x: m * x + b
learn = 0.01
三、编写权重更新函数
def summation(y, x_points, y_points):
total1 = 0
total2 = 0
for i in range(1, len(x_points)):
total1 += y(x_points[i]) - y_points[i]
total2 += (y(x_points[i]) - y_points[i]) * x_points[i]
return total1 / len(x_points), total2 / len(x_points)
四、编写可视化作图函数
def plot_line(y, data_points):
x_values = [i for i in range(int(min(x_points) - 1), int(max(x_points)) + 2)]
y_values = [y(x) for x in x_values]
plt.plot(x_values, y_values, 'r')
五、使用for循环模拟并且可视化学习过程
plt.figure(1)
for i in range(5):
s1, s2 = summation(y, x_points, y_points)
m = m - learn * s2
b = b - learn * s1
plot_line(y, x_points)
plt.plot(x_points, y_points, 'bo')
plt.figure(2)
for i in range(5):
s1, s2 = summation(y, x_points, y_points)
m = m - learn * s2
b = b - learn * s1
plot_line(y, x_points)
plt.plot(x_points, y_points, 'bo')
plt.figure(3)
for i in range(5):
s1, s2 = summation(y, x_points, y_points)
m = m - learn * s2
b = b - learn * s1
plot_line(y, x_points)
plt.plot(x_points, y_points, 'bo')
plt.show()
六、运行结果
我们可以看到,直线从一根与x轴重合的直线逐渐收敛到最佳拟合直线。

DAMO开发者矩阵,由阿里巴巴达摩院和中国互联网协会联合发起,致力于探讨最前沿的技术趋势与应用成果,搭建高质量的交流与分享平台,推动技术创新与产业应用链接,围绕“人工智能与新型计算”构建开放共享的开发者生态。
更多推荐
所有评论(0)