栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

线性回归和梯度下降代码

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

线性回归和梯度下降代码

根据原理的代码!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()

没了。 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1019199.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号