参考:《机器学习实战》- 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实现线性回归的更多相关文章

  1. 机器学习经典算法具体解释及Python实现--线性回归(Linear Regression)算法

    (一)认识回归 回归是统计学中最有力的工具之中的一个. 机器学习监督学习算法分为分类算法和回归算法两种,事实上就是依据类别标签分布类型为离散型.连续性而定义的. 顾名思义.分类算法用于离散型分布预測, ...

  2. python求线性回归斜率

    一. 先说我对这个题目的理解 直线的x,y方程是这样的:y = kx+b, k就是斜率. 求线性回归斜率, 就是说 有这么一组(x, y)的对应值——样本.如果有四组,就说样本量是4.根据这些样本,做 ...

  3. 吴裕雄 python 机器学习——线性回归模型

    import numpy as np from sklearn import datasets,linear_model from sklearn.model_selection import tra ...

  4. python模拟线性回归的点

    构造符合线性回归的数据点 import numpy as np import tensorflow as tf import matplotlib.pyplot as plt # 随机生成1000个点 ...

  5. python机器学习---线性回归案例和KNN机器学习案例

    散点图和KNN预测 一丶案例引入 # 城市气候与海洋的关系研究 # 导包 import numpy as np import pandas as pd from pandas import Serie ...

  6. python实现线性回归之简单回归

    代码来源:https://github.com/eriklindernoren/ML-From-Scratch 首先定义一个基本的回归类,作为各种回归方法的基类: class Regression(o ...

  7. Python机器学习/LinearRegression(线性回归模型)(附源码)

    LinearRegression(线性回归) 2019-02-20  20:25:47 1.线性回归简介 线性回归定义: 百科中解释 我个人的理解就是:线性回归算法就是一个使用线性函数作为模型框架($ ...

  8. 机器学习之线性回归(纯python实现)][转]

    本文转载自:https://juejin.im/post/5a924df16fb9a0634514d6e1 机器学习之线性回归(纯python实现) 线性回归是机器学习中最基本的一个算法,大部分算法都 ...

  9. 【机器学习】线性回归python实现

    线性回归原理介绍 线性回归python实现 线性回归sklearn实现 这里使用python实现线性回归,没有使用sklearn等机器学习框架,目的是帮助理解算法的原理. 写了三个例子,分别是单变量的 ...

随机推荐

  1. xml的xPath解析规则

    一,为什么要用xpath技术 问题:当使用dom4j查询比较深的层次结构的节点(标签,属性,文本),比较麻烦!!! 二,xpath的规则 2.1,/根元素的案例 /AAA 选择根元素AAA       ...

  2. Redis入门必读,The Little Redis Book中文版

    csdn的博客都要搬到这里了 The Little Redis Book中文版 入门 The Little Redis Book中文版 第一章 - 基础知识 The Little Redis Book ...

  3. python基础—装饰器

    python基础-装饰器 定义:一个函数,可以接受一个函数作为参数,对该函数进行一些包装,不改变函数的本身. def foo(): return 123 a=foo(); b=foo; print(a ...

  4. js去重

    <!DOCTYPE html><html><head lang="en"> <meta charset="UTF-8" ...

  5. 【BZOJ1007】水平可见直线(单调栈)

    [BZOJ1007]水平可见直线(单调栈) 题解 Description 在xoy直角坐标平面上有n条直线L1,L2,...Ln,若在y值为正无穷大处往下看,能见到Li的某个子线段,则称Li为 可见的 ...

  6. 【CJOJ P1957】【NOIP2010冲刺十模拟赛】数字积木

    [NOIP2010冲刺十模拟赛]数字积木 Description 小明有一款新式积木,每个积木上都有一个数,一天小明突发奇想,要是把所有的积木排成一排,所形成的数目最大是多少呢? 你的任务就是读入n个 ...

  7. js文本框字符数输入限制

    我们常常在前台页面做一些文本输入长度的验证,为什么呢?因为数据库字段设置了大小,如果不限制输入长度,那么写入库时就会引发字符串截断异常.今天就给大家分享一个jquery插件来解决这一问题. (func ...

  8. Openflow简介和安装

    搞网络研究的,跟踪斯坦福stanford大学的研究就很重要. 因为思科CISCO与斯坦福的渊源太深了.被誉神雕侠侣的思科创始人Sandy Lerner夫妇,一个在计算机学院,一个在商学院. 最近去看了 ...

  9. 关于new,delete,malloc,free的一些总结

    首先,new,delete都是c++的关键字并不是函数,通过特定的语法组成表达式,new可以在编译的时候确定其返回值.可以直接使用string *p=new string("asdfgh&q ...

  10. WP Super Cache+七牛云配置CDN加速,让你的网站秒开

    CDN加速网站是几乎所有的站长都在考虑的问题,CDN,全称是Content Delivery Network,即内容分发网络.所谓CDN加速,通俗的来说就是把原服务器上数据复制到其他服务器上,用户访问 ...