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代码来解图片迷宫的方法整理
Apr 02 Python
python实现的简单猜数字游戏
Apr 04 Python
python中字典(Dictionary)用法实例详解
May 30 Python
numpy中索引和切片详解
Dec 15 Python
python将文本中的空格替换为换行的方法
Mar 19 Python
python实现对指定字符串补足固定长度倍数截断输出的方法
Nov 15 Python
Python自动化之数据驱动让你的脚本简洁10倍【推荐】
Jun 04 Python
pyqt5实现按钮添加背景图片以及背景图片的切换方法
Jun 13 Python
python Django 创建应用过程图示详解
Jul 29 Python
python中struct模块之字节型数据的处理方法
Aug 27 Python
将pytorch转成longtensor的简单方法
Feb 18 Python
python装饰器代码解析
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
解决CodeIgniter伪静态失效
2014/06/09 PHP
一个php生成16位随机数的代码(两种方法)
2014/09/16 PHP
php获取百度收录、百度热词及百度快照的方法
2015/04/02 PHP
[原创]php实现 data url的图片生成与保存
2016/12/04 PHP
phpstudy默认不支持64位php的解决方法
2017/02/20 PHP
PHP 文件上传限制问题
2019/09/01 PHP
PHP的new static和new self的区别与使用
2019/11/27 PHP
设定php简写功能的方法
2019/11/28 PHP
实例讲解PHP表单
2020/06/10 PHP
JS 类型转换常见方法小结
2010/05/31 Javascript
说说JSON和JSONP 也许你会豁然开朗
2012/09/02 Javascript
jquery触发a标签跳转事件示例代码
2013/07/21 Javascript
JS中的异常处理方法分享
2013/12/22 Javascript
javascript操作符&quot;!~&quot;详解
2015/02/10 Javascript
学习使用grunt来打包JavaScript和CSS程序的教程
2016/01/04 Javascript
vue.js入门教程之绑定class和style样式
2016/09/02 Javascript
jQuery Validate验证表单时多个name相同的元素只验证第一个的解决方法
2016/12/24 Javascript
利用Javascript实现简单的转盘抽奖
2017/02/13 Javascript
JS库之wow.js使用方法
2017/09/14 Javascript
nodejs中request库使用HTTPS代理的方法
2019/04/30 NodeJs
小程序实现搜索界面 小程序实现推荐搜索列表效果
2019/05/18 Javascript
Python httplib模块使用实例
2015/04/11 Python
Python按钮的响应事件详解
2019/03/04 Python
Python 绘制酷炫的三维图步骤详解
2019/07/12 Python
pytorch构建多模型实例
2020/01/15 Python
python GUI库图形界面开发之PyQt5表单布局控件QFormLayout详细使用方法与实例
2020/03/06 Python
使用keras时input_shape的维度表示问题说明
2020/06/29 Python
使用html5制作loading图的示例
2014/04/14 HTML / CSS
HTML5 文件上传下载的实例代码
2017/07/03 HTML / CSS
canvas之自定义头像功能实现代码示例
2017/09/29 HTML / CSS
线程的基本概念、线程的基本状态以及状态之间的关系
2012/10/26 面试题
拾金不昧表扬信
2015/01/16 职场文书
2015年中秋节主持词
2015/07/30 职场文书
2015年教师国培感言
2015/08/01 职场文书
Java Socket实现Redis客户端的详细说明
2021/05/26 Redis
mysql的单列多值存储实例详解
2022/04/05 MySQL