资源简介
用Python自己写的线性回归。其方法包括用最小二乘法直接求解和梯度下降法求解。理解代码能让你更好东其原理

代码片段和文件信息
“““直接法和梯度法求解线性回归“““
import numpy as np
import matplotlib.pyplot as plt
import time
from numpy.linalg import linalg as la
data = np.array([[ 0.35291809 0.16468428 0.35774628]
[-0.55106013 -0.10981663 0.25468008]
[-0.65439632 -0.71406955 0.1061582 ]
[-0.19790689 0.61536205 0.43122894]
[-0.00171825 0.66827656 0.44198075]
[-0.2739687 -1.16342739 0.01195186]
[ 0.11592071 -0.18320789 0.29397728]
[-0.02707248 -0.53269863 0.21784183]
[ 0.7321352 0.27868019 0.42643361]
[-0.76680149 -0.89838545 0.06411818]])
X = data[::2]
y = data[:-1]
“““直接求解“““
b = np.array([1])#偏移量 b shape=(101)
b=b.repeat(10)
“““将偏移量与2个特征值组合 shape = (103)“““
X = np.column_stack((bX))
xtx = X.transpose().dot(X)
xtx = la.inv(xtx)
theta = xtx.dot(X.transpose()).dot(y)
“““梯度求解“““
#model
def model(thetaX):
theta = np.array(theta)
return X.dot(theta)
#cost
def cost(mthetaXy):
#print(theta)
ele = y - model(thetaX)
item = ele**2
item_sum = np.sum(item)
return item_sum/2/m
#gradient
def gradient(mthetaXycols):
grad_theta = []
for j in range(cols):
grad = (y-model(thetaX)).dot(X[:j])
grad_sum = np.sum(grad)
grad_theta.append(-grad_sum/m)
return np.array(grad_theta)
#theta update
def theta_update(grad_thetathetasigma):
return theta - sigma * grad_theta
‘stop stratege‘
def stop_stratege(costcost_updatethreshold):
return cost-cost_update < threshold
# OLS algorithm
def OLS(Xythreshold):
start = time.clock()
# 样本个数
m=10
# 设置权重参数的初始值
theta = [000]
# 迭代步数
iters = 0
# 记录代价函数的值
cost_record=[]
# 学习率
sigma = 0.0001
cost_val = cost(mthetaXy)#代价函数
cost_record.append(cost_val)
while True:
grad = gradient(mthetaXy3)#求梯度
# 参数更新
theta = theta_update(gradthetasigma)
cost_update = cost(mthetaXy)
if stop_stratege(cost_valcost_updatethreshold):
break
iters=iters+1
cost_val = cost_update
cost_record.append(cost_val)
end = time.clock()
print(“OLS convergence duration: %f s“ % (end - start))
return cost_record iterstheta
if __name__==“__main__“:
cost_record iterstheta=OLS(Xy1e-10)
## x = range(iters)
x = np.arange(0iters+11)
plt.figure()
plt.plot(xcost_record)
plt.show()
属性 大小 日期 时间 名称
----------- --------- ---------- ----- ----
文件 2710 2020-03-14 22:09 线性回归的最小二乘法与梯度下降法代码.py
相关资源
- Instant Pygame for Python Game Development How
- Biopython Tutorial
- Think Python 2nd
- 一个小小的表白程序(python)
- Python课堂笔记(高淇400集第一季)
- 二级考试python试题12套(包括选择题和
- pywin32_python3.6_64位
- python+ selenium教程
- PycURL(Windows7/Win32)Python2.7安装包 P
- 英文原版-Scientific Computing with Python
- 7.图像风格迁移 基于深度学习 pyt
- 基于Python的学生管理系统
- A Byte of Python(简明Python教程)(第
- Python实例174946
- Python 人脸识别
- Python 人事管理系统
- 基于python-flask的个人博客系统
- 计算机视觉应用开发流程
- python 调用sftp断点续传文件
- python socket游戏
- 基于Python爬虫爬取天气预报信息
- python函数编程和讲解
- Python开发的个人博客
- 基于python的三层神经网络模型搭建
- python实现自动操作windows应用
- python人脸识别(opencv)
- python 绘图(方形、线条、圆形)
- python疫情卡UN管控
- python 连连看小游戏源码
- 基于PyQt5的视频播放器设计
评论
共有 条评论