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 相关文章推荐
Python的另外几种语言实现
Jan 29 Python
Python中的异常处理简明介绍
Apr 13 Python
python简单实现基于SSL的IRC bot实例
Jun 15 Python
Django实现快速分页的方法实例
Oct 22 Python
python计算日期之间的放假日期
Jun 05 Python
Python中常用的内置方法
Jan 28 Python
对python 自定义协议的方法详解
Feb 13 Python
基于Python函数和变量名解析
Jul 19 Python
使用OpCode绕过Python沙箱的方法详解
Sep 03 Python
基于Pyinstaller打包Python程序并压缩文件大小
May 28 Python
如何解决安装python3.6.1失败
Jul 01 Python
Python os和os.path模块详情
Apr 02 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
解析php中curl_multi的应用
2013/07/17 PHP
关于php微信订阅号开发之token验证后自动发送消息给订阅号但是没有消息返回的问题
2015/12/21 PHP
PHP基于imagick扩展实现合成图片的两种方法【附imagick扩展下载】
2017/11/14 PHP
PHP中单例模式的使用场景与使用方法讲解
2019/03/18 PHP
yii 框架实现按天,月,年,自定义时间段统计数据的方法分析
2020/04/04 PHP
PHP 面向对象程序设计之类属性与类常量实现方法分析
2020/04/13 PHP
ie focus bug 解决方法
2009/09/03 Javascript
模仿JQuery.extend函数扩展自己对象的js代码
2009/12/09 Javascript
jQuery EasyUI API 中文文档 - ComboBox组合框
2011/10/07 Javascript
利用NodeJS和PhantomJS抓取网站页面信息以及网站截图
2013/11/18 NodeJs
使用变量动态设置js的属性名
2014/10/19 Javascript
js实现每日自动换一张图片的方法
2015/05/04 Javascript
ion content 滚动到底部会遮住一部分视图的快速解决方法
2016/09/06 Javascript
KnockoutJS 3.X API 第四章之表单textInput、hasFocus、checked绑定
2016/10/11 Javascript
JS验证不重复验证码
2017/02/10 Javascript
JavaScript中filter的用法实例分析
2019/02/27 Javascript
浅谈layui数据表格判断问题(加入表单元素),设置单元格样式
2019/10/26 Javascript
Python中的Classes和Metaclasses详解
2015/04/02 Python
Django rest framework实现分页的示例
2018/05/24 Python
使用urllib库的urlretrieve()方法下载网络文件到本地的方法
2018/12/19 Python
Python生成MD5值的两种方法实例分析
2019/04/26 Python
如何真正的了解python装饰器
2020/08/14 Python
CSS3 选择器 基本选择器介绍
2012/01/21 HTML / CSS
CSS3的颜色渐变效果的示例代码
2017/09/29 HTML / CSS
HTML5 图片悬停放大的实现代码示例
2019/12/04 HTML / CSS
英国PC组件和在线电脑商店:SCAN
2019/04/18 全球购物
.NET现在共支持多少种语言
2014/02/26 面试题
教师节促销活动方案
2014/02/14 职场文书
《识字五》教学反思
2014/03/01 职场文书
英语课前三分钟演讲稿(6篇)
2014/09/13 职场文书
咖啡厅商业计划书
2014/09/15 职场文书
甜品店创业计划书
2014/09/21 职场文书
培训通知书模板
2015/04/17 职场文书
2016年母亲节广告语
2016/01/28 职场文书
Java各种比较对象的方式的对比总结
2021/06/20 Java/Android
浅谈Redis变慢的原因及排查方法
2022/06/21 Redis