机器学习深入篇(一)——多项式回归源码实现
最近准备深入学习机器学习,随笔记录,希望可以对大家有帮助。看吴恩达的 机器学习,良心课程
一、多项式回归原理
略(课程有详解)多项式回归有两种计算θ的方法,分别是梯度下降法和正规方程法,本篇使用梯度下降法计算theta值,下一篇将使用正规方程法。
二、Python代码实现
import numpy as np
from matplotlib import pyplot as plt
#定义样本数据
a = np.random.standard_normal((1, 500))
x = np.arange(0, 50, 0.1)
y = x ** 2 + x * 2 + 5
y = y - a * 100
y = y[0]
x1 = x * x
# 特征放缩,减少梯度下降的速度
def scaling(x, x1):
n_x = (x - np.mean(x)) / 50
n_x1 = (x1 - np.mean(x)) / 2500
return n_x, n_x1
#迭代计算θ值
def Optimization(x, x1, y, theta, learning_rate):
for i in range(iter):#迭代计算theta
theta = Updata(x, x1, y, theta, learning_rate)
return theta
def Updata(x, x1, y, theta, learning_rate):#梯度下降不断求得Thera
m = len(x1)
sum = 0.0
sum1 = 0.0
sum2 = 0.0
n_x, n_x1 = scaling(x, x1)#归一化
alpha = learning_rate#设置学习率
h = 0
for i in range(m):
h = theta[0] + theta[1] * x[i] + theta[2] * x1[i]#假设函数
sum += (h - y[i])
sum1 += (h - y[i]) * n_x[i]
sum2 += (h - y[i]) * n_x1[i]
theta[0] -= alpha * sum / m
theta[1] -= alpha * sum1 / m
theta[2] -= alpha * sum2 / m
return theta
# 数据初始化
learning_rate = 0.0001#学习率对结果产生很大的影响,小一点效果会好
theta = [0, 0, 0]
iter = 3000#迭代次数
theta = Optimization(x, x1, y, theta, learning_rate)
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
plt.figure(figsize=(35,35))
plt.scatter(x,y,marker='o')
plt.xticks(fontsize=40)
plt.yticks(fontsize=40)
plt.xlabel('特征X',fontsize=40)
plt.ylabel('Y',fontsize=40)
plt.title('样本',fontsize=40)
plt.savefig("样本.jpg")
b = np.arange(0, 50)
c = theta[0] + b * theta[1] + b ** 2 * theta[2]
plt.figure(figsize=(35, 35))
plt.scatter(x, y, marker='o')
plt.plot(b, c)
plt.xticks(fontsize=40)
plt.yticks(fontsize=40)
plt.xlabel('特征X', fontsize=40)
plt.ylabel('Y', fontsize=40)
plt.title('结果', fontsize=40)
plt.savefig("结果.jpg")```
三、结果展示