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的subprocess模块总结
Nov 07 Python
python使用MySQLdb访问mysql数据库的方法
Aug 03 Python
python 字典中取值的两种方法小结
Aug 02 Python
解决python opencv无法显示图片的问题
Oct 28 Python
解决python3中cv2读取中文路径的问题
Dec 05 Python
celery4+django2定时任务的实现代码
Dec 23 Python
python+opencv实现高斯平滑滤波
Jul 21 Python
Python3.5实现的三级菜单功能示例
Mar 25 Python
Flask框架模板继承实现方法分析
Jul 31 Python
Python 使用matplotlib模块模拟掷骰子
Aug 08 Python
使用Python画出小人发射爱心的代码
Nov 23 Python
解决python调用自己文件函数/执行函数找不到包问题
Jun 01 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
使用 MySQL 开始 PHP 会话
2006/12/21 PHP
php实现用户在线时间统计详解
2011/10/08 PHP
ThinkPHP进程计数类Process用法实例详解
2015/09/25 PHP
JS获取农历日期具体实例
2013/11/14 Javascript
js文件包含的几种方式介绍
2014/09/28 Javascript
jQuery获取对象简单实现方法小结
2014/10/30 Javascript
Angular.js回顾ng-app和ng-model使用技巧
2016/04/26 Javascript
JQuery控制DIV的选取实现方法
2016/09/18 Javascript
基于Node的React图片上传组件实现实例代码
2017/05/10 Javascript
elementUI Vue 单个按钮显示和隐藏的变换功能(两种方法)
2018/09/04 Javascript
小程序云开发实战小结
2018/10/25 Javascript
npx create-react-app xxx创建项目报错的解决办法
2020/02/17 Javascript
JS实现购物车基本功能
2020/11/08 Javascript
[00:36]我的中国心——Serenity vs Fnatic
2018/08/21 DOTA
Python Requests安装与简单运用
2016/04/07 Python
python下读取公私钥做加解密实例详解
2017/03/29 Python
Flask Web开发入门之文件上传(八)
2018/08/17 Python
Python实现的微信支付方式总结【三种方式】
2019/04/13 Python
如何更优雅地写python代码
2019/07/02 Python
Python SELENIUM上传文件或图片实现过程
2019/10/28 Python
python爬虫爬取监控教务系统的思路详解
2020/01/08 Python
Python实现寻找回文数字过程解析
2020/06/09 Python
python如何实现读取并显示图片(不需要图形界面)
2020/07/08 Python
html5 canvas移动浏览器上实现图片压缩上传
2016/03/11 HTML / CSS
Linux如何修改文件和文件夹的权限
2013/09/05 面试题
linux面试题参考答案(9)
2016/01/29 面试题
管理站站长岗位职责
2013/11/27 职场文书
预备党员思想汇报范文
2014/01/11 职场文书
十八届三中全会个人学习材料
2014/02/13 职场文书
房屋租赁委托书范本
2014/10/04 职场文书
阿凡达观后感
2015/06/10 职场文书
母亲去世追悼词
2015/06/23 职场文书
2015迎新晚会活动总结
2015/07/16 职场文书
电台广播稿范文
2015/08/19 职场文书
vue中data改变后让视图同步更新的方法
2021/03/29 Vue.js
如何利用Matlab制作一款真正的拼图小游戏
2021/05/11 Python