python使用梯度下降算法实现一个多线性回归


Posted in Python onMarch 24, 2020

python使用梯度下降算法实现一个多线性回归,供大家参考,具体内容如下

图示:

python使用梯度下降算法实现一个多线性回归

python使用梯度下降算法实现一个多线性回归

import pandas as pd
import matplotlib.pylab as plt
import numpy as np
# Read data from csv
pga = pd.read_csv("D:\python3\data\Test.csv")
# Normalize the data 归一化值 (x - mean) / (std)
pga.AT = (pga.AT - pga.AT.mean()) / pga.AT.std()
pga.V = (pga.V - pga.V.mean()) / pga.V.std()
pga.AP = (pga.AP - pga.AP.mean()) / pga.AP.std()
pga.RH = (pga.RH - pga.RH.mean()) / pga.RH.std()
pga.PE = (pga.PE - pga.PE.mean()) / pga.PE.std()


def cost(theta0, theta1, theta2, theta3, theta4, x1, x2, x3, x4, y):
 # Initialize cost
 J = 0
 # The number of observations
 m = len(x1)
 # Loop through each observation
 # 通过每次观察进行循环
 for i in range(m):
 # Compute the hypothesis
 # 计算假设
 h=theta0+x1[i]*theta1+x2[i]*theta2+x3[i]*theta3+x4[i]*theta4
 # Add to cost
 J += (h - y[i])**2
 # Average and normalize cost
 J /= (2*m)
 return J
# The cost for theta0=0 and theta1=1


def partial_cost_theta4(theta0,theta1,theta2,theta3,theta4,x1,x2,x3,x4,y):
 h = theta0 + x1 * theta1 + x2 * theta2 + x3 * theta3 + x4 * theta4
 diff = (h - y) * x4
 partial = diff.sum() / (x2.shape[0])
 return partial


def partial_cost_theta3(theta0,theta1,theta2,theta3,theta4,x1,x2,x3,x4,y):
 h = theta0 + x1 * theta1 + x2 * theta2 + x3 * theta3 + x4 * theta4
 diff = (h - y) * x3
 partial = diff.sum() / (x2.shape[0])
 return partial


def partial_cost_theta2(theta0,theta1,theta2,theta3,theta4,x1,x2,x3,x4,y):
 h = theta0 + x1 * theta1 + x2 * theta2 + x3 * theta3 + x4 * theta4
 diff = (h - y) * x2
 partial = diff.sum() / (x2.shape[0])
 return partial


def partial_cost_theta1(theta0,theta1,theta2,theta3,theta4,x1,x2,x3,x4,y):
 h = theta0 + x1 * theta1 + x2 * theta2 + x3 * theta3 + x4 * theta4
 diff = (h - y) * x1
 partial = diff.sum() / (x2.shape[0])
 return partial

# 对theta0 进行求导
# Partial derivative of cost in terms of theta0


def partial_cost_theta0(theta0, theta1, theta2, theta3, theta4, x1, x2, x3, x4, y):
 h = theta0 + x1 * theta1 + x2 * theta2 + x3 * theta3 + x4 * theta4
 diff = (h - y)
 partial = diff.sum() / (x2.shape[0])
 return partial


def gradient_descent(x1,x2,x3,x4,y, alpha=0.1, theta0=0, theta1=0,theta2=0,theta3=0,theta4=0):
 max_epochs = 1000 # Maximum number of iterations 最大迭代次数
 counter = 0 # Intialize a counter 当前第几次
 c = cost(theta0, theta1, theta2, theta3, theta4, x1, x2, x3, x4, y) ## Initial cost 当前代价函数
 costs = [c] # Lets store each update 每次损失值都记录下来
 # Set a convergence threshold to find where the cost function in minimized
 # When the difference between the previous cost and current cost
 # is less than this value we will say the parameters converged
 # 设置一个收敛的阈值 (两次迭代目标函数值相差没有相差多少,就可以停止了)
 convergence_thres = 0.000001
 cprev = c + 10
 theta0s = [theta0]
 theta1s = [theta1]
 theta2s = [theta2]
 theta3s = [theta3]
 theta4s = [theta4]
 # When the costs converge or we hit a large number of iterations will we stop updating
 # 两次间隔迭代目标函数值相差没有相差多少(说明可以停止了)
 while (np.abs(cprev - c) > convergence_thres) and (counter < max_epochs):
 cprev = c
 # Alpha times the partial deriviative is our updated
 # 先求导, 导数相当于步长
 update0 = alpha * partial_cost_theta0(theta0, theta1, theta2, theta3, theta4, x1, x2, x3, x4, y)
 update1 = alpha * partial_cost_theta1(theta0, theta1, theta2, theta3, theta4, x1, x2, x3, x4, y)
 update2 = alpha * partial_cost_theta2(theta0, theta1, theta2, theta3, theta4, x1, x2, x3, x4, y)
 update3 = alpha * partial_cost_theta3(theta0, theta1, theta2, theta3, theta4, x1, x2, x3, x4, y)
 update4 = alpha * partial_cost_theta4(theta0, theta1, theta2, theta3, theta4, x1, x2, x3, x4, y)
 # Update theta0 and theta1 at the same time
 # We want to compute the slopes at the same set of hypothesised parameters
 #  so we update after finding the partial derivatives
 # -= 梯度下降,+=梯度上升
 theta0 -= update0
 theta1 -= update1
 theta2 -= update2
 theta3 -= update3
 theta4 -= update4

 # Store thetas
 theta0s.append(theta0)
 theta1s.append(theta1)
 theta2s.append(theta2)
 theta3s.append(theta3)
 theta4s.append(theta4)

 # Compute the new cost
 # 当前迭代之后,参数发生更新
 c = cost(theta0, theta1, theta2, theta3, theta4, x1, x2, x3, x4, y)

 # Store updates,可以进行保存当前代价值
 costs.append(c)
 counter += 1 # Count
 # 将当前的theta0, theta1, costs值都返回去
 #return {'theta0': theta0, 'theta1': theta1, 'theta2': theta2, 'theta3': theta3, 'theta4': theta4, "costs": costs}
 return {'costs':costs}

print("costs =", gradient_descent(pga.AT, pga.V,pga.AP,pga.RH,pga.PE)['costs'])
descend = gradient_descent(pga.AT, pga.V,pga.AP,pga.RH,pga.PE, alpha=.01)
plt.scatter(range(len(descend["costs"])), descend["costs"])
plt.show()

损失函数随迭代次数变换图:

python使用梯度下降算法实现一个多线性回归

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Python2.5/2.6实用教程 入门基础篇
Nov 29 Python
python读写ini文件示例(python读写文件)
Mar 25 Python
Python松散正则表达式用法分析
Apr 29 Python
Python IDLE入门简介
Dec 08 Python
Flask框架信号用法实例分析
Jul 24 Python
python随机数分布random测试
Aug 27 Python
python实现顺序表的简单代码
Sep 28 Python
Django 设置多环境配置文件载入问题
Feb 25 Python
浅谈keras使用预训练模型vgg16分类,损失和准确度不变
Jul 02 Python
python调试工具Birdseye的使用教程
May 25 Python
pytorch 预训练模型读取修改相关参数的填坑问题
Jun 05 Python
PyTorch 如何检查模型梯度是否可导
Jun 05 Python
PyQt5+python3+pycharm开发环境配置教程
Mar 24 #Python
python实现最速下降法
Mar 24 #Python
python实现梯度法 python最速下降法
Mar 24 #Python
PyQt5+Pycharm安装和配置图文教程详解
Mar 24 #Python
python实现梯度下降法
Mar 24 #Python
pycharm下配置pyqt5的教程(anaconda虚拟环境下+tensorflow)
Mar 25 #Python
pycharm通过anaconda安装pyqt5的教程
Mar 24 #Python
You might like
WordPress中用于检索模版的相关PHP函数使用解析
2015/12/15 PHP
php 使用html5 XHR2实现上传文件与进度显示功能示例
2020/03/03 PHP
禁止直接访问php文件代码分享
2020/05/05 PHP
List Installed Software Features
2007/06/11 Javascript
可实现多表单提交的javascript函数
2007/08/01 Javascript
对字符串进行HTML编码和解码的JavaScript函数
2010/02/01 Javascript
javascript中的107个基础知识收集整理 推荐
2010/03/29 Javascript
关于图片的预加载过程中隐藏未知的
2012/12/19 Javascript
利用JS实现浏览器的title闪烁
2013/07/08 Javascript
javascript算法题:求任意一个1-9位不重复的N位数在该组合中的大小排列序号
2015/04/01 Javascript
JavaScript实现对下拉列表值进行排序的方法
2015/07/15 Javascript
JS针对浏览器窗口关闭事件的监听方法集锦
2016/06/24 Javascript
微信小程序 toast 详解及实例代码
2016/11/09 Javascript
详解Angular2组件之间如何通信
2017/06/22 Javascript
Vue2.0点击切换类名改变样式的方法
2018/08/22 Javascript
小程序实现自定义导航栏适配完美版
2019/04/02 Javascript
Vue插件之滑动验证码用法详解
2020/04/05 Javascript
基于JavaScript实现十五拼图代码实例
2020/04/26 Javascript
微信小程序实现加入购物车滑动轨迹
2020/11/18 Javascript
Python+PIL实现支付宝AR红包
2018/02/09 Python
Django中间件实现拦截器的方法
2018/06/01 Python
python图形用户接口实例详解
2019/12/16 Python
TensorFlow梯度求解tf.gradients实例
2020/02/04 Python
keras tensorflow 实现在python下多进程运行
2020/02/06 Python
python如何利用paramiko执行服务器命令
2020/11/07 Python
python3 googletrans超时报错问题及翻译工具优化方案 附源码
2020/12/23 Python
HTML5移动开发图片压缩上传功能
2016/11/09 HTML / CSS
美国最流行的男士时尚网站:Touch of Modern
2018/02/05 全球购物
全球采购的街头服饰和帽子:Urban Excess
2020/10/28 全球购物
Tuckernuck官网:经典的美国品质服装、鞋子和配饰
2021/01/11 全球购物
Linux中如何用命令创建目录
2015/01/12 面试题
运动会100米解说词
2014/01/23 职场文书
小学校园之星事迹材料
2014/05/16 职场文书
党员领导干部民主生活会批评与自我批评发言
2014/09/28 职场文书
写给纪委的违纪检讨书
2015/05/05 职场文书
Oracle配置dblink访问PostgreSQL的操作方法
2022/03/21 PostgreSQL