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

yipeiwu_com7年前Python基础

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

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

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

一个简单的事例如下:

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=',')
# X=data[0]
# Y=data[1] 
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实现简单的单变量线性回归方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python中三元表达式的几种写法介绍

要介绍Python的三元表达式,可以先看看其他编程语言比如C,JAVA中应用: public class java { public static void main(String...

virtualenv 指定 python 解释器的版本方法

使用如下命令为 ubuntu 系统安装 virtualenv sudo apt-get install python-virtualenv 当我们使用 virtualenv 命令创...

Python中创建字典的几种方法总结(推荐)

1、传统的文字表达式: >>> d={'name':'Allen','age':21,'gender':'male'} >>> d {'age':...

Python 实现数据库更新脚本的生成方法

我在工作的时候,在测试环境下使用的数据库跟生产环境的数据库不一致,当我们的测试环境下的数据库完成测试准备更新到生产环境上的数据库时候,需要准备更新脚本,真是一不小心没记下来就会忘了改了哪...

Python实现Windows和Linux之间互相传输文件(文件夹)的方法

Python实现Windows和Linux之间互相传输文件(文件夹)的方法

项目中需要从Windows系统传输ISO文件到Linux测试系统,然后再Linux测试系统里安装这个ISO文件。所以就需要实现如何把文件从Windows系统传输到Linux系统中。 在项...