一、导入需要的库

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轴重合的直线逐渐收敛到最佳拟合直线。

Logo

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

更多推荐