机器学习初实战!梯度下降法
在写完我的笔记后,我打算写一个代码来预测成绩和学分之间的关系。在这里使用的是XDU禾府少主大一一年的真实成绩。排除了文史、思政、选修后的禾府少主的GPA也是高的惊人。但是禾府少主一向飞扬跋扈,所以当然要预测一下他的四年成绩走向。
First verison
Lastest verison
当我们运行完,就可以看到,其实在不久的将来,学分会越来越低,课程是越来越多,所以我们马上就可以农奴翻身做主人[滑稽]。
反思与后记:
2019年7月4日:
在写完以后,我发现有些时候因为无法退出循环所以程序死掉了。原因就出在这一行:
if sum1(theta_0, theta_1) == 0 and sum2(theta_0, theta_1) == 0:
pass
所以有两种方法解决,一种是定义一个极小量,当小于极小量退出循环,或计时。比较了一下两种方法,我选择了第二种。
2019年7月5日:
当学习了多元线性回归后,我又对程序进行了小修改,提高程序的可读性,不需要temp0
&temp1
这样的一个个变量来表示,一个列表就够了。
2019年7月5日:
再次对程序进行完善,对程序稍作修改后,将 J J J的值显性化,我们可以看到,在进行了350次运算后,代价函数已经非常平稳,所以我们设置的时间是完全多余的,所以我们可以把时间改为一秒足以(在本情况中)。
最新代码:
# -*- coding:utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
import time
def plot_initial():
plt.title(u'Grade Prediction')
plt.xlabel('Credit')
plt.ylabel('Grade')
plt.yticks([80, 84, 90, 95], [r"B+", r"A-", r"A", r"A+"])
for grade in data:
plt.scatter(grade[0], grade[1], c="black")
def gradient_descent():
theta_0 = 0
theta_1 = 0
error = "Please change ALPHA, we have a set of theta, but not the best."
start = time.clock()
temp = [0, 0]
while True:
temp[0] = theta_0 - sum1(theta_0, theta_1)
temp[1] = theta_1 - sum2(theta_0, theta_1)
theta_0, theta_1 = tuple(temp)
end = time.clock()
if sum1(theta_0, theta_1) == 0 and sum2(theta_0, theta_1) ==0:
break
if end - start >= 1:
print(error)
break
return theta_0, theta_1
def sum1(t0, t1):
sum_this = 0
for g in data:
sum_this += (t0 + t1 * g[0] - g[1])
return sum_this * ALPHA / len(data)
def sum2(t0, t1):
sum_this = 0
for g in data:
sum_this += (t0 + t1 * g[0] - g[1]) * g[0]
return sum_this * ALPHA / len(data)
def x_y_initial():
(theta0, theta1) = gradient_descent()
x = np.arange(0, 6)
y = theta0 + theta1 * x
plt.plot(x, y, "r", label="Hypothesis")
plt.legend()
print("y = " + str(round(theta1,3)) + "x" + "+ (" + str(round(theta0, 3)) + ")")
data = [(3.5, 86), (2.5, 96), (5, 93), (2, 90),
(3, 86), (3, 81), (3.5, 96), (5, 90),
(2, 93), (2, 85), (4, 90)]
if __name__ == "__main__":
ALPHA = 0.1
plot_initial()
x_y_initial()
plt.savefig("Grade Prediction")
plt.show()
第一次的代码
# -*- coding:utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
def plot_initial():
plt.title(u'Grade Prediction')
plt.xlabel('Credit')
plt.ylabel('Grade')
plt.yticks([80, 84, 90, 95], [r"B+", r"A-", r"A", r"A+"])
for grade in data:
plt.scatter(grade[0], grade[1], c="black")
def gradient_descent():
theta_0 = 0
theta_1 = 0
while True:
temp0 = theta_0 - sum1(theta_0, theta_1)
temp1 = theta_1 - sum2(theta_0, theta_1)
theta_0 = temp0
theta_1 = temp1
if sum1(theta_0, theta_1) == 0 and sum2(theta_0, theta_1) == 0:
break
return theta_0, theta_1
def sum1(t0, t1):
sum_this = 0
for g in data:
sum_this += (t0 + t1 * g[0] - g[1])
return sum_this * alpha / len(data)
def sum2(t0, t1):
sum_this = 0
for g in data:
sum_this += (t0 + t1 * g[0] - g[1]) * g[0]
return sum_this * alpha / len(data)
def x_y_initial():
(theta0, theta1) = gradient_descent()
x = np.arange(0, 6)
y = theta0 + theta1 * x
plt.plot(x, y, "r", label="Hypothesis")
plt.legend() #显示label
data = [(3.5, 86), (2.5, 96), (5, 93), (2, 90),
(3, 86), (3, 81), (3.5, 96), (5, 90),
(2, 93), (2, 85), (4, 90)]
if __name__ == "__main__":
alpha = 0.1
plot_initial()
x_y_initial()
plt.savefig("Grade Prediction")
plt.show()