脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - python实现简单的单变量线性回归方法

python实现简单的单变量线性回归方法

2021-04-17 00:27xckkcxxck Python

今天小编就为大家分享一篇python实现简单的单变量线性回归方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

线性回归是机器学习中的基础算法之一,属于监督学习中的回归问题,算法的关键在于如何最小化代价函数,通常使用梯度下降或者正规方程(最小二乘法),在这里对算法原理不过多赘述,建议看吴恩达发布在斯坦福大学上的课程进行入门学习。

这里主要使用python的sklearn实现一个简单的单变量线性回归。

sklearn对机器学习方法封装的十分好,基本使用fit,predict,score,来训练,预测,评价模型,

一个简单的事例如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
from pandas import dataframe
from pandas import dataframe
import pandas as pd
import matplotlib.pyplot as plt
from sklearn import datasets,linear_model
 
x=[]
y=[]
with open("c:\\users\\www\\ex1data1.txt","r") as f:  #读取txt文件。
 for line in f:
  p_tmp, e_tmp = [float(i) for i in line.split(',')]
  x.append(p_tmp)
  y.append(e_tmp)
 #'data=np.loadtxt('ex1data1.txt',delimiter=',')
?
1
# x=data[0]
?
1
# y=data[1]
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
data=dataframe(x,columns={'a'})
data['b']=b
x=dataframe(x)
 
fig = plt.figure()        
ax1 = fig.add_subplot(1,1,1)
plt.scatter(data['a'],data['b'])   #显示x,y的散点图
 
def linear_model_main(x,y,predict_value): #定义一个使用线性回归的函数
 regr=linear_model.linearregression()
 regr.fit(x,y)  #训练模型
 predict_output=regr.predict(predict_value) #预测
 predictions={}        #用一个集合装以下元素
 predictions['intercept']=regr.intercept_  #截距
 predictions['codfficient']=regr.coef_   #斜率(参数)
 predictions['predict_value']=predict_output  #预测值
 return predictions
 
result = linear_model_main(x,y,1500)    #调用函数
print(result['predict_value'])
 
 
def show_predict(x,y):
 regr=linear_model.linearregression()
 regr.fit(x,y)
 plt.scatter(x,y,color='blue')
 plt.plot(x,regr.predict(x),color='red')
 
show_predict(x,y)

最后拟合结果如图:

python实现简单的单变量线性回归方法

以上这篇python实现简单的单变量线性回归方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/xckkcxxck/article/details/70158004

延伸 · 阅读

精彩推荐