一、線性迴歸
1、環境:Pycharm2017.2,Win7,python3.6
2、方法:損失函數一般用均方誤差來表示,對損失函數進行微分,可以得到梯度,使用梯度下降法不斷迭代,可以將參數調整爲最佳(前提條件是損失函數爲凸函數,並且學習率比較合適)。使用公式: weight = weight - 梯度*學習率
3、目標函數:
4、損失函數:
5、梯度函數(即求偏導):
求偏導方法:第一、求和符號對求偏導沒有啥影響,不要受其干擾,第二、求導,複雜情況下,先整體再局部,複雜的函數往往是一個函數套在另一個函數
6、編程測試:
import numpy as np
import matplotlib.pyplot as plt
m = 25
learning_rate = 0.01
X0 = np.arange(0, m, 1).reshape(m, 1) # m*1
X1 = np.ones(m).reshape(m, 1) # m*1, 作爲偏置項
X = np.hstack((X0, X1)) # m*2 橫向堆疊
y = np.array([0.9, 2.1, 3.2, 4.1, 4.9, 6.2, 7.1, 8.1, 9.2, 10.2, 11.2,
12.1, 13.1, 14.1, 15.2, 15.9, 17.1, 18.2, 19.1, 19.9, 21.0, 22.0, 23.1, 23.99, 25.8]).reshape(m, 1) # m*1
"""
函數說明:計算損失值,使用1/2便於微分, 使用均方差mse
Parameters:
theta --訓練得到的參數 2*1
X --x座標值 m*2
y --標籤值,即y值 m*1
Returns:
損失值
"""
def error_function(thera, X, y):
diff = np.dot(X, thera) - y
return 1./(2*m)*np.dot(np.transpose(diff), diff)
"""
函數說明:返回梯度
Parameters:
theta --訓練得到的參數
X --x座標值
y --標籤值,即y值
Returns:
返回梯度
"""
def gradient_function(thera, X, y):
diff = np.dot(X, thera) - y
return 1./m*np.dot(np.transpose(X), diff) # 2*m m*1
"""
函數說明:顯示結果
Parameters:
theta --訓練得到的參數
Returns:
無
"""
def display(theta, y):
fig = plt.figure()
ax = fig.add_subplot(111) # 添加subplot
ax.scatter(X0.reshape(m, ), y.reshape(m, ), s=10, c='red', marker='s', alpha=.5)
x = np.arange(-3.0, 26.0, 0.1)
y = theta[0] + theta[1] * x
ax.plot(x, y)
plt.title('BestFit') # 繪製title
plt.xlabel('X')
plt.ylabel('Y') # 繪製label
plt.show()
"""
函數說明:使用梯度下降法求最優參數
Parameters:
無
Returns:
訓練得到的最優參數
"""
def gradientDown():
theta = np.array([2, 1]).reshape(2, 1)
gradient = gradient_function(theta, X, y)
while abs(gradient[0]) > 1e-10 or abs(gradient[1]) > 1e-10:
theta = theta - learning_rate * gradient
gradient = gradient_function(theta, X, y)
print('損失值:\n', error_function(theta, X, y))
print(theta)
return theta
if __name__ == '__main__':
theta = gradientDown()
print('最低損失值:\n', error_function(theta, X, y))
print(theta)
display(theta, y)
7、效果:
參數:
[[1.0043]
[1.06 ]]
損失值:
[[0.01449398]]
參考文章:
https://www.jianshu.com/p/f5570f21e5be
https://blog.csdn.net/nextdoor6/article/details/82597765
https://www.jianshu.com/p/c7e642877b0e