今天介绍一个机器学习包,sklearn。其功能模块有regression\classification\clustering\Dimensionality reduction\data preprocessing\model selection

对我来说,常用的主要有regression(SVR)和classification(SVC)两个部分。

首先介绍一下用sklearn.svm.SVR来做回归,如下:

1)多元线性回归

import numpy as np
from sklearn.linear_model import LinearRegression rng = np.random.RandomState(10) # 设置随机局部种子
x = 100 * rng.rand(50, 3) # 设置一个50行3列 所有值乘100的随机矩阵 x1 = x[:, 0]
x1.shape = 50, 1
x2 = x[:, 1]
x2.shape = 50, 1
x3 = x[:, 2]
x3.shape = 50, 1
y = 1.25 * x1 + 2.5 * x2 + 3 * x3 + 10 + rng.randn(50, 1) # randn是标准正态分布,用于核验结果 model = LinearRegression(fit_intercept=True)
model.fit(x, y) a = np.linspace(0, 50, 1000) # 从0到50创建1000个等差数列,验证模型
x1_fit = a[:, np.newaxis] # 将a转置成列
x2_fit = a[:, np.newaxis]
x3_fit = a[:, np.newaxis]
x_fit = np.hstack((x1_fit, x2_fit, x3_fit)) # 将x1,x2,x3合并一起
y_fit = model.predict(x_fit) # 对y预测
print("Model slope: ", model.coef_[0])
print("Model intercept:", model.intercept_)
print('方程的判定系数(R^2): %.2f' % model.score(x, y)) #计算得分,R^2

2)多项式回归

import random
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures x_data, y_data = [], []
# 随机生成30个点
for x in range(-10, 20):
y = - x ** 2 + 5 * x - 10 + random.random() * 20
x_data.append([x])
y_data.append([y]) # 特征构造
poly_reg = PolynomialFeatures(degree=2) #多项式构造
x_poly = poly_reg.fit_transform(x_data) # 创建线性模型
linear_reg = LinearRegression()
linear_reg.fit(x_poly, y_data)
plt.plot(x_data, y_data, 'b.')
# 用特征构造数据进行预测
plt.plot(x_data, linear_reg.predict(poly_reg.fit_transform(x_data)), 'r')
plt.show()

3)非线性回归(一元为例)

from sklearn.svm import SVR
from sklearn.model_selection import GridSearchCV #自动选择最佳模型 from sklearn.tree import DecisionTreeRegressor #决策树 from sklearn.ensemble import RandomForestRegressor #随机森林
import numpy as np
import matplotlib.pyplot as plt x = np.array([68.67,54.351,92.991,80.39,64.46]).reshape(-1, 1) #reshape为(-1,1),里面是[[1],[2]...]
y = np.array([68.67,54.351,92.991,80.39,64.46]).reshape(-1, 1) # 选择模型
#model = SVR(kernel='rbf')
# model = DecisionTreeRegressor()
# model = RandomForestRegressor()
model = GridSearchCV(SVR(), param_grid={"kernel": ("linear", 'rbf', 'sigmoid'), "C": np.logspace(-3, 3, 7), "gamma": np.logspace(-3, 3, 7)})
model.fit(x, y) xneed = np.arrray([[1.2],[3.6]])
y_pre = model.predict(xneed)# 进行预测 plt.scatter(x, y, c='k', label='data', zorder=1)
plt.plot(xneed, y_pre, c='r', label='SVR_fit')
plt.show()
print(model.best_params_)

补充:

1.如果要划分训练样本和测试样本数据集。

from sklearn.model_selection import  train_test_split

x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=.3) #选取0.3的测试集

2.为了增强数据之间相关性,通常对数据进行预处理,如标准化。

from sklearn.preprocessing import StandardScaler

scaler = StandardScaler()
x_std = scaler.fit_transform(x)  # 标准化

3.可以用GridSearchCV自动选择最佳模型

from sklearn.model_selection import GridSearchCV

grid = GridSearchCV(svc, param_grid, cv=3, n_jobs=-1)

4.模型保存

from sklearn.externals import joblib   #用于保存和读取模型pkl

joblib.dump(model, 'svr.pkl')     # 保存模型

svr = joblib.load('svr.pkl')        # 读取模型

过两天补充一下sklearn.svm.SVC...

Sklearn--(SVR)Regression学习笔记的更多相关文章

  1. Logistic Regression学习笔记

    1.李航<统计学习方法>: 2.https://blog.csdn.net/laobai1015/article/details/78113214 3.http://www.cnblogs ...

  2. Stepwise regression 学习笔记

    之前在 SPSS 中的回归分析算法中发现,在它里面实现的算法有 Enter 和 Stepwise 两种.Enter 很容易理解,就是将所有选定的自变量一起放入模型中,直接去计算包含所有自变量的整个模型 ...

  3. Hands on Machine Learning with Sklearn and TensorFlow学习笔记——机器学习概览

    一.什么是机器学习? 计算机程序利用经验E(训练数据)学习任务T(要做什么,即目标),性能是P(性能指标),如果针对任务T的性能P随着经验E不断增长,成为机器学习.[这是汤姆米切尔在1997年定义] ...

  4. 学习Logistic Regression的笔记与理解(转)

    学习Logistic Regression的笔记与理解 1.首先从结果往前来看下how logistic regression make predictions. 设我们某个测试数据为X(x0,x1, ...

  5. ufldl学习笔记和编程作业:Softmax Regression(softmax回报)

    ufldl学习笔记与编程作业:Softmax Regression(softmax回归) ufldl出了新教程.感觉比之前的好,从基础讲起.系统清晰,又有编程实践. 在deep learning高质量 ...

  6. [Machine Learning]学习笔记-Logistic Regression

    [Machine Learning]学习笔记-Logistic Regression 模型-二分类任务 Logistic regression,亦称logtic regression,翻译为" ...

  7. [ML学习笔记] 回归分析(Regression Analysis)

    [ML学习笔记] 回归分析(Regression Analysis) 回归分析:在一系列已知自变量与因变量之间相关关系的基础上,建立变量之间的回归方程,把回归方程作为算法模型,实现对新自变量得出因变量 ...

  8. ufldl学习笔记与编程作业:Softmax Regression(vectorization加速)

    ufldl学习笔记与编程作业:Softmax Regression(vectorization加速) ufldl出了新教程,感觉比之前的好.从基础讲起.系统清晰,又有编程实践. 在deep learn ...

  9. ufldl学习笔记与编程作业:Logistic Regression(逻辑回归)

    ufldl学习笔记与编程作业:Logistic Regression(逻辑回归) ufldl出了新教程,感觉比之前的好,从基础讲起.系统清晰,又有编程实践. 在deep learning高质量群里面听 ...

随机推荐

  1. Pandas的介绍与基本使用

    1.什么是Pandas 当大家谈论到数据分析时,提及最多的语言就是Python和SQL,而Python之所以适合做数据分析,就是因为他有很多强大的第三方库来协助,pandas就是其中之一,它是基于Nu ...

  2. dp - 求符合题意的序列的个数

    The sequence of integers a1,a2,…,ak is called a good array if a1=k−1 and a1>0. For example, the s ...

  3. @RequestParam,@PathVariable,@RequestBody

    @RequestParam 和 @PathVariable 注解是用于从request中接收请求的,两个都可以接收参数,关键点不同的是@RequestParam 是从request里面拿取值,而 @P ...

  4. python+opencv中最近出现的一些变化( OpenCV 官方的 Python tutorial目前好像还没有改过来?) 记一次全景图像的拼接

    最近在学习过程中发现opencv有了很多变动, OpenCV 官方的 Python tutorial目前好像还没有改过来,导致大家在学习上面都出现了一些问题,现在做一个小小的罗列,希望对大家有用 做的 ...

  5. python简易计算器

    import re """ 过程:(最内部的括号->先乘除,替换->整理表达式->加减)->替换 """ def m ...

  6. redis 支持事务

    pipe = conn.pipeline(transaction=True) pipe.multi() pipe.set(') pipe.hset('k3','n1',666) pipe.lpush( ...

  7. Treap基本用法总结

    Treap=Tree+Heap  起名的人非常有才 Treap是啥? 一棵二叉搜索树可能退化成链,那样各种操作的效率都比较低 于是可爱的Treap在每个节点原先值v的基础上加了一个随机数rnd,树的形 ...

  8. 【洛谷4424】[HNOI_AHOI2018]寻宝游戏(我也不知道括号里该写啥)

    题目 洛谷 4424 分析 感觉思路比较神仙. 对于按位与和按位或两种运算,显然每一位是独立的,可以分开考虑. 对于某一位,「与 \(0\)」会将这一位变成 \(0\),「或 \(1\)」会将这一位变 ...

  9. xpath写法汇总(适用于appium、robotframework)

    1.移动端应用,content-des包含“订单号” xpath=//android.view.View[contains(@content-desc,"订单号:")] 2.移动端 ...

  10. nmap详解之选项说明

    功能选项 功能选项可以组合使用.一些功能选项只能够在某种扫描模式下使用.nmap会自动识别无效或者不支持的功能选项组合,并向用户发出警告信息. 如果你是有经验的用户,可以略过结尾的示例一节.可以使用n ...