根据原理的代码!lkx半桶水看不懂那种xixi
在jupyter跑的!
目录
线性回归
梯度下降
1 批量梯度下降
编辑2 随机梯度下降
线性回归
import numpy as np
import os
import matplotlib.pyplot as plt
#字体设置
plt.rcParams['axes.labelsize']=14
plt.rcParams['xtick.labelsize']=12
plt.rcParams['ytick.labelsize']=12
import warnings
warnings.filterwarnings('ignore')
import numpy as np
X=2*np.random.rand(100,1)
y=4+3*X+np.random.randn(100,1)
X_b=np.c_[np.ones((100,1)),X]
#最小二乘法的结果
theta_best=np.linalg.inv(X_b.T.dot(X_b)).dot(X_b.T).dot(y)
X_new=np.array([[0],[2]])#(0,2)连接画一条线
X_new_b=np.c_[np.ones((2,1)),X_new]
y_predict=X_new_b.dot(theta_best)
plt.plot(X_new,y_predict,'r--')
plt.plot(X,y,'b.')
plt.show()
直接调api
from sklearn.linear_model import LinearRegression lr=LinearRegression() lr.fit(X,y) lr.coef_
梯度下降
1 批量梯度下降
在前面代码(数据)的基础上啊啊啊啊
eta=0.1#学习率
n_iterations=1000#迭代次数
m=100#样本个数
theta=np.random.randn(2,1)#随机初始化
for iteration in range(n_iterations):
gradients=2/m*X_b.T.dot(X_b.dot(theta)-y)
theta=theta-eta*gradients
X_new_b.dot(theta)
theta_path_bgd=[]
def plot_gradient_descent(theta,eta,theta_path=None):
m=len(X_b)
plt.plot(X,y,'b.')
n_iterations=1000
sum=0
for iteration in range(n_iterations):
y_predict=X_new_b.dot(theta)
plt.plot(X_new,y_predict,'b-')
gradients=2/m*X_b.T.dot(X_b.dot(theta)-y)
theta=theta-eta*gradients
sum+=1
if theta_path is not None:
theta_path.append(theta)
print(sum)
plt.xlabel('X_1')
plt.axis([0,2,0,15])
plt.title('eta={}'.format(eta))
theta=np.random.randn(2,1)
plt.figure(figsize=(10,4))
#不同学习率得到的结果,对比实验画图
plt.subplot(131)
plot_gradient_descent(theta,eta=0.02)
plt.subplot(132)
plot_gradient_descent(theta,eta=0.1)
plt.subplot(133)
plot_gradient_descent(theta,eta=0.5)
plt.show()
2 随机梯度下降
也是在前面数据基础嗷
theta_path_sgd=[]
m=len(X_b)
n_epochs=50
t0=5
t1=50
def learning_schedule(t):
return t0/(t1+t)
for epoch in range(n_epochs):
for i in range(m):
if epoch==0 and i <20:
y_predict=X_new_b.dot(theta)
plt.plot(X_new,y_predict,'r-')
random_index=np.random.randint(m)
xi=X_b[random_index:random_index+1]
yi=y[random_index:random_index+1]
gradients=xi.T.dot(xi.dot(theta)-yi)
theta=theta-eta*gradients
eta=learning_schedule(n_epochs*m+i)
theta=theta-eta*gradients
theta_path_sgd.append(theta)
plt.plot(X,y,'b.')
plt.xlabel('X_1')
plt.axis([0,2,0,15])
plt.show()
没了。



