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目录操作之python遍历文件夹后将结果存储为xml
Jan 27 Python
Python实现栈的方法
May 26 Python
Python开发之快速搭建自动回复微信公众号功能
Apr 22 Python
Python自定义进程池实例分析【生产者、消费者模型问题】
Sep 19 Python
python 爬虫 批量获取代理ip的实例代码
May 22 Python
Python多进程fork()函数详解
Feb 22 Python
Python实现图片批量加入水印代码实例
Nov 30 Python
numpy np.newaxis 的实用分享
Nov 30 Python
Python for循环与getitem的关系详解
Jan 02 Python
matlab中imadjust函数的作用及应用举例
Feb 27 Python
opencv python 图片读取与显示图片窗口未响应问题的解决
Apr 24 Python
Python+Appium新手教程
Apr 17 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
收音机怀古---春雷3P7图片欣赏
2021/03/02 无线电
php中可能用来加密字符串的函数[base64_encode、urlencode、sha1]
2012/01/16 PHP
ThinkPHP CURD方法之table方法详解
2014/06/18 PHP
Yii2中使用asset压缩js,css文件的方法
2016/11/24 PHP
PHP搭建大文件切割分块上传功能示例
2017/01/04 PHP
php图片裁剪函数
2018/10/31 PHP
JavaScript入门之事件、cookie、定时等
2011/10/21 Javascript
ASP.NET jQuery 实例7 通过jQuery来获取DropDownList的Text/Value属性值
2012/02/03 Javascript
js模拟点击以提交表单为例兼容主流浏览器
2013/11/29 Javascript
js和jquery分别验证单选框、复选框、下拉框
2015/12/17 Javascript
BootStrap 智能表单实战系列(二)BootStrap支持的类型简介
2016/06/13 Javascript
AngularJS中实现动画效果的方法
2016/07/28 Javascript
真正好用的js验证上传文件大小的简单方法
2016/10/27 Javascript
详解vue.js组件化开发实践
2016/12/14 Javascript
单行 JS 实现移动端金钱格式的输入规则
2017/05/22 Javascript
jQuery实现可编辑表格并生成json结果(实例代码)
2017/07/19 jQuery
用react-redux实现react组件之间数据共享的方法
2018/06/08 Javascript
vue上传图片到oss的方法示例(图片带有删除功能)
2018/09/27 Javascript
vue引入axios同源跨域问题
2018/09/27 Javascript
深入解析vue 源码目录及构建过程分析
2019/04/24 Javascript
微信小程序基础教程之worker线程的使用方法
2019/07/15 Javascript
Vue的编码技巧与规范使用详解
2019/08/28 Javascript
python修改操作系统时间的方法
2015/05/18 Python
python去除文件中空格、Tab及回车的方法
2016/04/12 Python
简述Python2与Python3的不同点
2018/01/21 Python
Python生成任意范围任意精度的随机数方法
2018/04/09 Python
Python使用pylab库实现绘制直方图功能示例
2018/06/01 Python
python 递归深度优先搜索与广度优先搜索算法模拟实现
2018/10/22 Python
Python爬虫实现获取动态gif格式搞笑图片的方法示例
2018/12/24 Python
Python图像处理实现两幅图像合成一幅图像的方法【测试可用】
2019/01/04 Python
Django 缓存配置Redis使用详解
2019/07/23 Python
Ranorex通过Python将报告发送到邮箱的方法
2020/01/12 Python
Opencv常见图像格式Data Type及代码实例
2020/11/02 Python
法学专业本科生自荐信范文
2013/12/17 职场文书
个人违纪检讨书
2014/09/15 职场文书
我们认为中短波广播场强仪的最佳组合
2022/04/05 无线电