一、梯度下降法
# 梯度下降不是一種算法,是一種最優(yōu)化方法
# 上節(jié)課講解的梯度下降的案例 是一個簡單的一元二次方程
# 最簡單的線性回歸:只有一個特征的線性回歸,有兩個theta
#
二、在多元線性回歸中使用梯度下降求解
三、### R squared error
使用真實數(shù)據(jù)來進(jìn)行梯度下降的過程
# 如果特征數(shù)多,樣本數(shù)少,梯度下降法占優(yōu)
# 如果特征數(shù)少,樣本數(shù)多,梯度下降法的效率會比較低
import numpy as np
def r2_score(y_true, y_predict):
return 1 - ((np.sum((y_true - y_predict) ** 2) / len(y_true)) / np.var(y_true))
class MyLinearGression:
def __init__(self):
self._theta = None # theta參數(shù)
self.coef_ = None # 系數(shù)
self.interception_ = None # 截距
def fit_gd(self, X_train, y, eta=0.01, n_iters=1e3, epsilon=1e-8): # 使用梯度下降的方式來訓(xùn)練數(shù)據(jù)
def j(theta, X_b, y):
try:
return np.sum((y - X_b.dot(theta)) ** 2) / len(X_b)
except:
return float('inf')
def dj(theta, X_b, y):
# res = np.empty(len(theta))
# res[0] = np.sum((X_b.dot(theta) - y))
# for i in range(1, len(theta)):
# res[i] = (X_b.dot(theta) - y).dot(X_b[:, i])
# return res * 2 / len(X_b)
return X_b.T.dot(X_b.dot(theta) - y)
def gradient_descent(X_b, y, eta, initial_theta, n_iters=1e3, epsilon=1e-8):
theta = initial_theta
i_iter = 1
while i_iter < n_iters:
last_theta = theta
theta = theta - eta * dj(theta, X_b, y)
if abs(j(theta, X_b, y) - j(last_theta, X_b, y)) < epsilon:
break
i_iter += 1
return theta
# eta = 0.01
X_b = np.hstack([np.ones(len(X_train)).reshape(-1, 1), X_train])
initial_theta = np.zeros(X_b.shape[1])
self._theta = gradient_descent(X_b, y, eta, initial_theta)
self.interception_ = self._theta[0]
self.coef_ = self._theta[1:]
return self
def __repr__(self):
return "MyLinearGression()"
def score(self, X_predict, y_test):
y_predict = self.predict(X_predict)
return r2_score(y_test, y_predict)
def predict(self, X_predict):
X_b = np.hstack([np.ones(len(X_predict)).reshape(-1, 1), X_predict])
return X_b.dot(self._theta)
四、總結(jié)
knn算法 線性回歸 數(shù)據(jù)的預(yù)處理(標(biāo)準(zhǔn)化) 模型好壞的校驗
五 梯度下降法
# 梯度下降不是一個機(jī)器學(xué)習(xí)算法,既不是再做監(jiān)督學(xué)習(xí),也不是在做非監(jiān)督學(xué)習(xí),是一種基于搜索的最優(yōu)化方法
# 作用:最小化一個損失函數(shù)
# 梯度上升法:最大化一個效用函數(shù)
# eta叫做學(xué)習(xí)率,learning rate
# eta的取值影響我們求得最優(yōu)解的速度
# eta如果取值過小,收斂太慢
# eta取值過大,可能甚至得不到最優(yōu)解
# eta他是梯度下降法的一個超參數(shù)
# 并不是所有的函數(shù)都有唯一的極值點
# 線性回歸的損失函數(shù)具有唯一的最優(yōu)解
# gradient inscent
import numpy as np
import matplotlib.pyplot as plt
plt_x = np.linspace(-1,6,141)
plt_y = (plt_x-2.5)**2-1
plt.plot(plt_x,plt_y)
plt.show()
def dj(theta):
return 2*(theta-2.5) # 傳入theta,求theta點對應(yīng)的導(dǎo)數(shù)
def j(theta):
return (theta-2.5)**2-1 # 傳入theta,獲得目標(biāo)函數(shù)的對應(yīng)值
eta = 0.1
theta =0.0
epsilon = 1e-8
while True:
gradient = dj(theta)
last_theta = theta
theta = theta-gradient*eta
if np.abs(j(theta)-j(last_theta))<epsilon:
break
print(theta)
print(dj(theta))
print(j(theta))
eta = 0.1
theta =0.0
epsilon = 1e-8
theta_history = [theta]
while True:
gradient = dj(theta)
last_theta = theta
theta = theta-gradient*eta
theta_history.append(theta)
if np.abs(j(theta)-j(last_theta))<epsilon:
break
print(theta)
print(dj(theta))
print(j(theta))
len(theta_history)文章來源:http://www.zghlxwxcb.cn/news/detail-801550.html
plt.plot(plt_x,plt_y)
plt.plot(theta_history,[(i-2.5)**2-1 for i in theta_history],color='r',marker='+')
plt.show()
def gradient_descent(eta,initial_theta,n_iters=1e3,epsilon = 1e-8):
theta = initial_theta
theta_history = [initial_theta]
i_iter = 1
def dj(theta):
try:
return 2*(theta-2.5) # 傳入theta,求theta點對應(yīng)的導(dǎo)數(shù)
except:
return float('inf')
def j(theta):
return (theta-2.5)**2-1 # 傳入theta,獲得目標(biāo)函數(shù)的對應(yīng)值
while i_iter<=n_iters:
gradient = dj(theta)
last_theta = theta
theta = theta-gradient*eta
theta_history.append(theta)
if np.abs(j(theta)-j(last_theta))<epsilon:
break
i_iter+=1
return theta_history
def plot_gradient(theta_history):
plt.plot(plt_x,plt_y)
plt.plot(theta_history,[(i-2.5)**2-1 for i in theta_history],color='r',marker='+')
plt.show()
eta = 0.1
theta =0.0
plot_gradient(gradient_descent(eta,theta))
eta = 0.01 # eta越小,迭代次數(shù)越多,耗時越久
theta =0.0
theta_history = gradient_descent(eta,theta)
plot_gradient(theta_history)
len(theta_history)
eta = 0.8 # 說明eta的取值不是特別準(zhǔn)確,也可以得到正確的結(jié)果
theta =0.0
plot_gradient(gradient_descent(eta,theta))
eta = 1.1 # 說明eta取值太大
theta =0.0
plot_gradient(gradient_descent(eta,theta))
六、sklearn中使用梯度下降法
文章來源地址http://www.zghlxwxcb.cn/news/detail-801550.html
到了這里,關(guān)于機(jī)器學(xué)習(xí)~從入門到精通(三)梯度下降法的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!