python实现线性回归
参考:《机器学习实战》- Machine Learning in Action
一、 必备的包
一般而言,这几个包是比较常见的:
• matplotlib,用于绘图
• numpy,数组处理库
• pandas,强大的数据分析库
• sklearn,用于线性回归的库
• scipy, 提供很多有用的科学函数
我一般是用pip安装,若不熟悉这些库,可以搜索一下它们的简单教程。
二、 线性回归
为了尽量简单,所以用以下一元方程式为例子:

典型的例子是房价预测,假设我们有以下数据集:

我们需要通过训练这些数据得到一个线性模型,以便来预测大小为700平方英尺的房价是多少。
详细代码如下:
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from sklearn import datasets, linear_model def get_data(file_name):
data = pd.read_csv(file_name)
X_parameter = []
Y_parameter = []
for single_square_feet ,single_price_value in zip(data['square_feet'],data['price']):
X_parameter.append([float(single_square_feet)])
Y_parameter.append(float(single_price_value))
return X_parameter,Y_parameter def linear_model_main(X_parameters,Y_parameters,predict_value):
regr = linear_model.LinearRegression()
regr.fit(X_parameters, Y_parameters)
predict_outcome = regr.predict(predict_value)
predictions = {}
predictions['intercept'] = regr.intercept_
predictions['coefficient'] = regr.coef_
predictions['predicted_value'] = predict_outcome return predictions def show_linear_line(X_parameters,Y_parameters):
regr = linear_model.LinearRegression()
regr.fit(X_parameters, Y_parameters)
plt.scatter(X_parameters,Y_parameters,color='blue')
plt.plot(X_parameters,regr.predict(X_parameters),color='red',linewidth=4)
#plt.xticks(())
#plt.yticks(())
plt.show() if __name__ == "__main__": X,Y = get_data('E:/machine_learning/LR/input_data.csv')
#show_linear_line(X,Y)
predictvalue = 700
result = linear_model_main(X,Y,predictvalue)
print "Intercept value " , result['intercept']
print "coefficient" , result['coefficient']
print "Predicted value: ",result['predicted_value']
结果如图:


前两个为公式里的参数。
三、 多项式回归
简单的线性模型误差难免高,于是引入多项式回归模型,方程式如下:

这次我们用scipy.stats中的norm来生成满足高斯分布的数据,直接贴代码:
# encoding:utf-8
import matplotlib.pyplot as plt
import numpy as np
from scipy.stats import norm
from sklearn.pipeline import Pipeline
from sklearn.linear_model import LinearRegression, SGDClassifier
from sklearn.preprocessing import PolynomialFeatures, StandardScaler x = np.arange(0, 1, 0.002)
y = norm.rvs(0, size=500, scale=0.1) #高斯分布数据
y = y + x**2 plt.scatter(x, y, s=5)
y_test = []
y_test = np.array(y_test) #clf = LinearRegression(fit_intercept=False)
clf = Pipeline([('poly', PolynomialFeatures(degree=100)),
('linear', LinearRegression(fit_intercept=False))])
clf.fit(x[:, np.newaxis], y)
y_test = clf.predict(x[:, np.newaxis]) plt.plot(x, y_test, linewidth=2)
plt.grid() #显示网格
plt.show()
结果如下:

这里取的最高次为100
参考博客:http://python.jobbole.com/81215/
python实现线性回归的更多相关文章
- 机器学习经典算法具体解释及Python实现--线性回归(Linear Regression)算法
(一)认识回归 回归是统计学中最有力的工具之中的一个. 机器学习监督学习算法分为分类算法和回归算法两种,事实上就是依据类别标签分布类型为离散型.连续性而定义的. 顾名思义.分类算法用于离散型分布预測, ...
- python求线性回归斜率
一. 先说我对这个题目的理解 直线的x,y方程是这样的:y = kx+b, k就是斜率. 求线性回归斜率, 就是说 有这么一组(x, y)的对应值——样本.如果有四组,就说样本量是4.根据这些样本,做 ...
- 吴裕雄 python 机器学习——线性回归模型
import numpy as np from sklearn import datasets,linear_model from sklearn.model_selection import tra ...
- python模拟线性回归的点
构造符合线性回归的数据点 import numpy as np import tensorflow as tf import matplotlib.pyplot as plt # 随机生成1000个点 ...
- python机器学习---线性回归案例和KNN机器学习案例
散点图和KNN预测 一丶案例引入 # 城市气候与海洋的关系研究 # 导包 import numpy as np import pandas as pd from pandas import Serie ...
- python实现线性回归之简单回归
代码来源:https://github.com/eriklindernoren/ML-From-Scratch 首先定义一个基本的回归类,作为各种回归方法的基类: class Regression(o ...
- Python机器学习/LinearRegression(线性回归模型)(附源码)
LinearRegression(线性回归) 2019-02-20 20:25:47 1.线性回归简介 线性回归定义: 百科中解释 我个人的理解就是:线性回归算法就是一个使用线性函数作为模型框架($ ...
- 机器学习之线性回归(纯python实现)][转]
本文转载自:https://juejin.im/post/5a924df16fb9a0634514d6e1 机器学习之线性回归(纯python实现) 线性回归是机器学习中最基本的一个算法,大部分算法都 ...
- 【机器学习】线性回归python实现
线性回归原理介绍 线性回归python实现 线性回归sklearn实现 这里使用python实现线性回归,没有使用sklearn等机器学习框架,目的是帮助理解算法的原理. 写了三个例子,分别是单变量的 ...
随机推荐
- freemarker中的substring取子串(十四)
freemarker中的substring取子串 1.substring取子串介绍 (1)表达式?substring(from,to) (2)当to为空时,默认的是字符串的长度 (3)from是第一个 ...
- UltraEdit 脚本 实现查找替换
UltraEdit中,要实现,脚本查找替换功能,按照下文中的做法稍作修改, 现象很奇怪,有时可以进行查找替换有时不能. http://blog.csdn.net/neareast/article/de ...
- CentOS 7.0 启动多个MySQL实例(mysql-5.7.21)
Linux系统:CentOS-7.0 MySQL版本:5.7.21 Linux系统下启动多个MySQL实例,目前知道有两种方法,一种是通过官方提供的mysqld_multi.server来实现,但是我 ...
- python官方推荐的各阶段学习书籍
Python学习交流群:463024091,群内每天分享干货,包括最新的python企业案例学习资料和零基础入门教程,欢迎各位小伙伴入群学习交流! 你是否曾经学期初立下一大堆学习计划,到期末却依旧过着 ...
- Bzoj2946:[POI2000] 最长公共子串
题面 求多个串的最长公共子串 Sol 套路,拼在一起,二分答案+后缀数组判定 把大于答案的\(height\)分组,然后计算出一个组内是否有所有串的后缀 由于串只有\(5\)个开个桶就好了 # inc ...
- Mock Server文章链接
Mock Server文章链接 2017-06-14 1 Dreamhead (Zheng Ye) Moco可以提供以下服务: HTTP APIs Socket APIs REST API GitHu ...
- Handsontable的前端分页与数据库分页
Handsontable虽然处理速度很快,但当数据量达到10W+的时候很容易导致浏览器内存泄漏,这时候可以用分页来解决.官网提供了前端分页demo,测试后发现也只能处理低于10W的数据,而且调试的时候 ...
- DataX通过纯Java代码启动
DataX是阿里巴巴团队开发的一个很好开源项目,但是他们对如何使用只提供了python命令启动方式,这种方式对于只是想简单的用下DataX的人来说很是友好,仅仅需要几行代码就可以运行,但是如果你需要在 ...
- JavaScript中的execCommand
execCommand方法是执行一个对当前文档,当前选择或者给出范围的命令.处理Html数据时常用 如下格式:document.execCommand(sCommand[,交互方式, 动态参数]) , ...
- linux的shell学习笔记
shell脚本第一行写明解释器的路径: #!/bin/bash运行脚本两种方式:使用bash命令运行shell文件,或授予脚本文件执行权限,可直接执行文件shell启动时,一开始执行一组命令来定义提问 ...