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中黄金分割法实现方法
May 06 Python
python字典快速保存于读取的方法
Mar 23 Python
使用python的pandas库读取csv文件保存至mysql数据库
Aug 20 Python
python获取url的返回信息方法
Dec 17 Python
python虚拟环境迁移方法
Jan 03 Python
PyQt5实现从主窗口打开子窗口的方法
Jun 19 Python
django 框架实现的用户注册、登录、退出功能示例
Nov 28 Python
python求一个字符串的所有排列的实现方法
Feb 04 Python
python 实现仿微信聊天时间格式化显示的代码
Apr 17 Python
DjangoWeb使用Datatable进行后端分页的实现
May 18 Python
给Django Admin添加验证码和多次登录尝试限制的实现
Jul 26 Python
详解tensorflow之过拟合问题实战
Nov 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
一个用php3编写的简单计数器
2006/10/09 PHP
php xml文件操作实现代码(二)
2009/03/20 PHP
php 记录进行累加并显示总时长为秒的结果
2011/11/04 PHP
php生成随机字符串可指定纯数字、纯字母或者混合的
2014/04/18 PHP
Yii2实现跨mysql数据库关联查询排序功能代码
2017/02/10 PHP
Jquery知识点一 Jquery的ready和Dom的onload的区别
2011/01/15 Javascript
JavaScript改变HTML元素的样式改变CSS及元素属性
2013/11/12 Javascript
一个奇葩的最短的 IE 版本判断JS脚本
2014/05/28 Javascript
浅谈jQuery中replace()方法
2015/05/13 Javascript
JS实现仿QQ效果的三级竖向菜单
2015/09/25 Javascript
利用Angular.js限制textarea输入的字数
2016/10/20 Javascript
javascript将url解析为json格式的两种方法
2017/08/18 Javascript
vue动态绑定组件子父组件多表单验证功能的实现代码
2018/05/14 Javascript
vue-cli构建项目下使用微信分享功能
2018/05/28 Javascript
JavaScript类的继承方法小结【组合继承分析】
2018/07/11 Javascript
vue.js input框之间赋值方法
2018/08/24 Javascript
Vue中 key keep-alive的实现原理
2018/09/18 Javascript
nodejs require js文件入口,在package.json中指定默认入口main方法
2018/10/10 NodeJs
JS实现获取数组中最大值或最小值功能示例
2019/03/02 Javascript
vue实现页面内容禁止选中功能,仅输入框和文本域可选
2019/11/09 Javascript
JavaScript动画实例之粒子文本的实现方法详解
2020/07/28 Javascript
原生js实现自定义滚动条
2021/01/20 Javascript
原生JavaScript实现换肤
2021/02/19 Javascript
python利用正则表达式排除集合中字符的功能示例
2017/10/10 Python
Python将DataFrame的某一列作为index的方法
2018/04/08 Python
python3+PyQt5实现拖放功能
2018/04/24 Python
Python3.7中安装openCV库的方法
2018/07/11 Python
在Pandas中DataFrame数据合并,连接(concat,merge,join)的实例
2019/01/29 Python
django为Form生成的label标签添加class方式
2020/05/20 Python
python如何操作mysql
2020/08/17 Python
HTML5 客户端数据库简易使用:IndexedDB
2019/12/19 HTML / CSS
HTML5逐步分析实现拖放功能的方法
2020/09/30 HTML / CSS
心碎乌托邦的创业计划书范文
2013/12/26 职场文书
2014离婚协议书范文
2014/09/10 职场文书
《比尾巴》教学反思
2016/02/24 职场文书
解决golang post文件时Content-Type出现的问题
2021/05/02 Golang