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实现同时兼容老版和新版Socket协议的一个简单WebSocket服务器
Jun 04 Python
Python爬虫代理IP池实现方法
Jan 05 Python
python中pandas.DataFrame对行与列求和及添加新行与列示例
Mar 12 Python
浅谈Python由__dict__和dir()引发的一些思考
Oct 30 Python
python线程中同步锁详解
Apr 27 Python
python实现输入数字的连续加减方法
Jun 22 Python
给我一面国旗 python帮你实现
Sep 30 Python
python实现图片上添加图片
Nov 26 Python
numpy np.newaxis 的实用分享
Nov 30 Python
Django对接elasticsearch实现全文检索的示例代码
Aug 02 Python
python全面解析接口返回数据
Feb 12 Python
Python编程中内置的NotImplemented类型的用法
Mar 23 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
Thinkphp搜索时首页分页和搜索页保持条件分页的方法
2014/12/05 PHP
laravel框架使用极光推送消息操作示例
2020/02/15 PHP
禁止刷新,回退的JS
2006/11/25 Javascript
js文字滚动停顿效果代码
2008/06/28 Javascript
JQuery EasyUI 加载两次url的原因分析及解决方案
2014/08/18 Javascript
javascript使用avalon绑定实现checkbox全选
2015/05/06 Javascript
基于jquery实现日历签到功能
2020/09/11 Javascript
AngularJs expression详解及简单示例
2016/09/01 Javascript
JS实现拖动滚动条评分的效果代码分享
2016/09/29 Javascript
javascript获取图片的top N主色值方法详解
2018/01/26 Javascript
Vue实现导出excel表格功能
2018/03/30 Javascript
vue-cli项目中使用echarts图表实例
2018/10/22 Javascript
微信小程序中的canvas 文字断行和省略号显示功能的处理方法
2018/11/14 Javascript
基于jquery ajax的多文件上传进度条过程解析
2019/09/11 jQuery
vue移动端模态框(可传参)的实现
2019/11/20 Javascript
微信公众号服务器验证Token步骤图解
2019/12/30 Javascript
小程序中使用css var变量(使js可以动态设置css样式属性)
2020/03/31 Javascript
jQuery实现的解析本地 XML 文档操作示例
2020/04/30 jQuery
Element PageHeader页头的使用方法
2020/07/26 Javascript
vue实现点击按钮“查看详情”弹窗展示详情列表操作
2020/09/09 Javascript
[03:59]5分钟带你了解什么是DOTA2(第二期)
2017/02/07 DOTA
Python原始字符串(raw strings)用法实例
2014/10/13 Python
Python 实现一个颜色色值转换的小工具
2016/12/06 Python
python3实现TCP协议的简单服务器和客户端案例(分享)
2017/06/14 Python
详解python 3.6 安装json 模块(simplejson)
2019/04/02 Python
Pycharm 2020.1 版配置优化的详细教程
2020/08/07 Python
英国巧克力贸易公司:Chocolate Trading Company
2017/03/21 全球购物
信息服务专业毕业生求职信
2014/03/02 职场文书
大课间体育活动方案
2014/03/12 职场文书
初中国旗下的演讲稿
2014/08/28 职场文书
成本会计岗位职责
2015/02/03 职场文书
党风廉正建设个人工作总结
2015/03/06 职场文书
民事调解书范文
2015/05/20 职场文书
Pytorch 实现变量类型转换
2021/05/17 Python
Python字符串的转义字符
2022/04/07 Python
JAVA 线程池(池化技术)的实现原理
2022/04/28 Java/Android