sklearn学习笔记

希望能做成思维导图的形式。

 

机器学习包括监督学习和无监督学习,监督学习一般为分类与回归,无监督学习一般分为聚类与降维。

 

1.sklearn数据集

1.1数据集介绍

数据集是一个类似字典的对象,它保存有关数据的所有数据和一些元数据。 该数据存储在 .data 成员中,它是 n_samples, n_features 数组。 在监督问题的情况下,一个或多个响应变量存储在 .target 成员中

1.2数据集获取

1.2.1导入sklearn数据集

from sklearn import datasets
iris = datasets.load_iris()

1.2.2创建数据集

from sklearn.datasets.samples_generator import make_classification

2.特征提取

官方文档介绍:

The sklearn.feature_extraction module can be used to extract features in a format supported by machine learning algorithms from datasets consisting of formats such as text and image.

2.1从字典里提取特征

2.2特征哈希

2.3提取文本特征(Text feature extraction

1.词袋模型的实现,将语料进行分词后完成词袋模型的构建。

vect = CountVectorizer(max_df = 0.8,min_df = 3, token_pattern=u'(?u)\\b[^\\d\\W]\\w+\\b', stop_words=stopwords)
X_train = vect.fit_transform(X_train)

 

2.tfidf的实现

2.4提取图片特征

 

3.数据预处理

官方文档介绍:

The sklearn.preprocessing package provides several common utility functions and transformer classes to change raw feature vectors into a representation that is more suitable for the downstream estimators.
In general, learning algorithms benefit from standardization of the data set. If some outliers are present in the set, robust scalers or transformers are more appropriate. The behaviors of the different scalers, transformers, and normalizers on a dataset containing marginal outliers is highlighted in Compare the effect of different scalers on data with outliers.

3.1标准化,均质去除或方差标度(Standardization, or mean removal and variance scaling

3.1.1标准化,均值去除或按方差比例缩放

1. scale 零均值单位方差

from sklearn import preprocessing 
import numpy as np  
X = np.array([[1., -1., 2.], [2., 0., 0.], [0., 1., -1.]])  
X_scaled = preprocessing.scale(X) 
#output :X_scaled = [[ 0.         -1.22474487  1.33630621]
 				 [ 1.22474487  0.         -0.26726124]
 				 [-1.22474487  1.22474487 -1.06904497]]
#scaled之后的数据零均值,单位方差
X_scaled.mean(axis=0)  # column mean: array([ 0.,  0.,  0.])  
X_scaled.std(axis=0)  #column standard deviation: array([ 1.,  1.,  1.])

2.StandardScaler 计算训练集的平均值和标准差,以便测试数据集使用相同的变换

scaler = preprocessing.StandardScaler().fit(X) #out: StandardScaler(copy=True, with_mean=True, with_std=True)
scaler.mean_  #out: array([ 1.,  0. ,  0.33333333])  
scaler.std_ #out: array([ 0.81649658,  0.81649658,  1.24721913]) 
#测试将该scaler用于输入数据,变换之后得到的结果同上
scaler.transform(X) #out: array([[ 0., -1.22474487,  1.33630621],        [ 1.22474487, 0. , -0.26726124],  [-1.22474487,1.22474487, -1.06904497]])  
scaler.transform([[-1., 1., 0.]])  #scale the new data, out: array([[-2.44948974,  1.22474487, -0.26726124]])

3.1.2将数据特征缩放至某一范围

scaler = preprocessing.MinMaxScaler(feature_range=(0, 1)).fit(train_data)
scaler.transform(train_data)
scaler.transform(test_data)
#feature_range: 定义归一化范围,注用()括起来

3.2数据正则化

3.4生成多项式特征(Generating polynomial features

在多项式回归中可能需要把[X1,X2]生成[1,X1,X2,X1X2,X1**2,X2**2]再进行回归,此时就需要调用from sklearn.preprocessing import PolynomialFeatures模块。例如下面进行多项式回归时用到的例子:

import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures
import matplotlib.pyplot as plt

dataset_X=[]
dataset_y=[]

f = open(*****\LinearRegression\prices.txt','r')
dataset = f.readlines()

for line in dataset:
    item = line.split(',')
    dataset_X.append(int(item[0]))
    dataset_y.append(int(item[1]))
    
dataset_X = np.array(dataset_X).reshape([len(dataset_X),1])
dataset_y = np.array(dataset_y).reshape([len(dataset_X),1])
poly_reg = PolynomialFeatures(degree = 2)
X_poly = poly_reg.fit_transform(dataset_X)

LR = LinearRegression()
LR.fit(X_poly,dataset_y)

X_max=int(max(dataset_X))
X_min=int(min(dataset_y))
X = np.arange(X_min,X_max).reshape([-1,1])

ax1 = plt.subplot(212)
ax1.scatter(dataset_X,dataset_y,c='r')
ax1.plot(X,LR.predict(poly_reg.fit_transform(X)),c='b')
ax1.set_xlabel('sqare')
ax1.set_ylabel('price')
ax1.set_title('the relationshaip between sqare and price')
plt.show()

4.数据集拆分

将数据集拆分成测试集和训练集

from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)

5.定义模型

在这一步我们首先要分析自己数据的类型,搞清出你要用什么模型来做,然后我们就可以在sklearn中定义模型了。sklearn为所有模型提供了非常相似的接口,这样使得我们可以更加快速的熟悉所有模型的用法。在这之前我们先来看看模型的常用属性和功能:

# 拟合模型
model.fit(X_train, y_train)
# 模型预测
model.predict(X_test)

# 获得这个模型的参数
model.get_params()
# 为模型进行打分
model.score(data_X, data_y) # 线性回归:R square; 分类问题: acc

6.模型评估与选择

6.1交叉验证

6.2检验曲线

7.保存模型

7.1 保存为pickle文件

7.2 sklearn自带方法joblib

 

参考文章:

机器学习中的数据预处理(sklearn preprocessing)https://blog.csdn.net/csmqq/article/details/51461696

sklearn快速入门教程https://blog.csdn.net/yuanshuaipeng/article/details/80399863

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值