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等机器学习框架,目的是帮助理解算法的原理. 写了三个例子,分别是单变量的 ...
随机推荐
- Theano环境搭建/安装
关键词:theano安装,搭建theano环境, python, 深度学习 因为需要安装theano,结果发现这又是一个难以安装的python包-虽然网上教程不少,然而鱼龙混杂,试验了各种方法流程,最 ...
- TCP/IP协议三次握手与四次握手流程解析(转)
一.TCP报文格式 下面是TCP报文格式图: 上图中有几个字段需要重点介绍下: (1)序号:Seq序号,占32位,用来标识从TCP源端向目的端发送的字节流,发起方发送数据时对此进行标 ...
- [HAOI2012]高速公路
题面在这里 题意 维护区间加操作+询问区间任选两不同点途中线段权值之和的期望 sol 一道假的期望题... 因为所有事件的发生概率都相同,所以答案就是所有方案的权值总和/总方案数 因为区间加法自然想到 ...
- [BZOJ3224] [Tyvj 1728] 普通平衡树 (treap)
Description 您需要写一种数据结构(可参考题目标题),来维护一些数,其中需要提供以下操作: 1. 插入x数 2. 删除x数(若有多个相同的数,因只删除一个) 3. 查询x数的排名(若有多个相 ...
- 1.4 如何在main()方法之前执行输出“hello world”
public class Test{ static{ System.out.println("hello world"); } public static void main(St ...
- IDEA jsp模板
> File > Settings- > File and Code Templates > Other >Jsp files >Jsp File.jsp < ...
- MongoDB 搭建文件存储的方案
用云的话,节省你开发成本,快速上线,数据比较安全.缺点是一旦用了他们的,形成习惯以后,数据想迁移就会比较麻烦,你会越来越依赖,而且规模上去以后价格并不低.早年自己做的话,你需要实现分布式文件系统,这个 ...
- Android RecyclerView 滚动到中间位置
最近看到QQ音乐的歌词每次滑动后都可以滚回到中间位置.觉得甚是神奇,打开开发者模式显示布局,发现歌词部分不是采用 android 控件的写的,应该是前端写的.于是,我想,能不能用 recyclerVi ...
- Lintcode212 Space Replacement solution 题解
[题目描述] Write a method to replace all spaces in a string with%20. The string is given in a characters ...
- 解决python本地离线安装requests问题
使用python36进行本地requests安装的时候,由于安装requests需要联网,导致安装失败,现象如下: 一开始以为,需要安装什么证书,其实只是需要一个python的证书库,(⊙﹏⊙)b 执 ...