1.classification分类
2.Regression回归
3.Clustering聚类
4.Dimensionality reduction降维
5.Model selection模型选择
6.Preprocessing预处理
1.sklearn.base: Base classes and utility function基础实用函数
2.sklearn.cluster: Clustering聚类
3.sklearn.cluster.bicluster: Biclustering 双向聚类
4.sklearn.covariance: Covariance Estimators 协方差估计
5.sklearn.model_selection: Model Selection 模型选择
6.sklearn.datasets: Datasets 数据集
7.sklearn.decomposition: Matrix Decomposition 矩阵分解
8.sklearn.dummy: Dummy estimators 虚拟估计
9.sklearn.ensemble: Ensemble Methods 集成方法
10.sklearn.exceptions: Exceptions and warnings 异常和警告
11.sklearn.feature_extraction: Feature Extraction 特征抽取
12.sklearn.feature_selection: Feature Selection 特征选择
13。sklearn.gaussian_process: Gaussian Processes 高斯过程
14.sklearn.isotonic: Isotonic regression 保序回归
15.sklearn.kernel_approximation: Kernel Approximation 核 逼近
16.sklearn.kernel_ridge: Kernel Ridge Regression 岭回归ridge
17.sklearn.discriminant_analysis: Discriminant Analysis 判别分析
18.sklearn.linear_model: Generalized Linear Models 广义线性模型
19.sklearn.manifold: Manifold Learning 流形学习
20.sklearn.metrics: Metrics 度量 权值
21.sklearn.mixture: Gaussian Mixture Models 高斯混合模型
22.sklearn.multiclass: Multiclass and multilabel classification 多等级标签分类
23.sklearn.multioutput: Multioutput regression and classification 多元回归和分类
24.sklearn.naive_bayes: Naive Bayes 朴素贝叶斯
25.sklearn.neighbors: Nearest Neighbors 最近邻
26.sklearn.neural_network: Neural network models 神经网络
27.sklearn.calibration: Probability Calibration 概率校准
28.sklearn.cross_decomposition: Cross decomposition 交叉求解
29.sklearn.pipeline: Pipeline 管道
30.sklearn.preprocessing: Preprocessing and Normalization 预处理和标准化
31.sklearn.random_projection: Random projection 随机映射
32.sklearn.semi_supervised: Semi-Supervised Learning 半监督学习
33.sklearn.svm: Support Vector Machines 支持向量机
34.sklearn.tree: Decision Tree 决策树
35.sklearn.utils: Utilities 实用工具
from sklearn import preprocessing
标准化处理函数
preprocessing.scale(X,axis=0, with_mean=True, with_std=True, copy=True)
preprocessing.minmax_scale(X,feature_range=(0, 1), axis=0, copy=True)
preprocessing.maxabs_scale(X,axis=0, copy=True)
preprocessing.robust_scale(X,axis=0, with_centering=True, with_scaling=True,copy=True)
标准化正态分布类
classpreprocessing.StandardScaler(copy=True, with_mean=True,with_std=True)
# 属性:
# scale_:ndarray,缩放比例
# mean_:ndarray,均值
# var_:ndarray,方差
# n_samples_seen_:int,已处理的样本个数,调用partial_fit()时会累加,调用fit()会重设
# 这里可以根据训练集进行标准化,测试集沿用训练集的标准化方法!
scaler = preprocessing.StandardScaler().fit(train_data)
scaler.transform(train_data)
scaler.transform(test_data)
# 将每个特征值归一化到一个固定范围
scaler = preprocessing.MinMaxScaler(feature_range=(0, 1)).fit(train_data)
scaler.transform(train_data)
scaler.transform(test_data)
classpreprocessing.MinMaxScaler(feature_range=(0, 1),copy=True):
# 属性:
# min_:ndarray,缩放后的最小值偏移量
# scale_:ndarray,缩放比例
# data_min_:ndarray,数据最小值
# data_max_:ndarray,数据最大值
# data_range_:ndarray,数据最大最小范围的长度
classpreprocessing.MaxAbsScaler(copy=True):
# 属性:
# scale_:ndarray,缩放比例
# max_abs_:ndarray,绝对值最大值
# n_samples_seen_:int,已处理的样本个数
classpreprocessing.RobustScaler(with_centering=True,with_scaling=True, copy=True):
# 属性:
# center_:ndarray,中心点
# scale_:ndarray,缩放比例
classpreprocessing.KernelCenterer:
以上几个标准化类的方法:
正则化
# 计算两个样本的相似度时必不可少的一个操作,就是正则化。其思想是:首先求出样本的p-范数,然后该样本的所有元素都要除以该范数,这样最终使得每个样本的范数都为1。
# L1 norm 是指对每个样本的每一个元素都除以该样本的L1范数. 使行和为1
# eg. 0.47619048 = 10 /(10+4+5+2)
X = np.array([[10,4,5,2], [1,4,5,7]])
X_normalized = preprocessing.normalize(X, norm='l1')
X_normalized
array([[ 0.47619048, 0.19047619, 0.23809524, 0.0952381 ],
[ 0.05882353, 0.23529412, 0.29411765, 0.41176471]])
#L2 norm 是指对每个样本的每一个元素都除以该样本的L2范数.
# eg. 0.4 = 1/sqrt(1+1+4)
X = [[ 1., -1., 2.],
[ 2., 0., 0.],
[ 0., 1., -1.]]
X_normalized = preprocessing.normalize(X, norm='l2')
X_normalized
array([[ 0.40, -0.40, 0.81],
[ 1. , 0. , 0. ],
[ 0. , 0.70, -0.70]])
将数据集分为训练集和测试集
from sklearn.mode_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)
# arrays:样本数组,包含特征向量和标签
# test_size:
# float-获得多大比重的测试样本 (默认:0.25)
# int - 获得多少个测试样本
# train_size: 同test_size
# random_state: int - 随机种子(种子固定,实验可复现)
# shuffle - 是否在分割之前对数据进行洗牌(默认True)
# 拟合模型
model.fit(X_train, y_train)
# 模型预测
model.predict(X_test)
# 获得这个模型的参数
model.get_params()
# 为模型进行打分
model.score(data_X, data_y)
from sklearn.linear_model import LinearRegression
# 定义线性回归模型
model = LinearRegression(fit_intercept=True, normalize=False, copy_X=True, n_jobs=1)
"""
fit_intercept:是否计算截距。False-模型没有截距
normalize: 当fit_intercept设置为False时,该参数将被忽略。 如果为真,则回归前的回归系数X将通过减去平均值并除以l2-范数而归一化。
n_jobs:指定线程数
"""
from sklearn.linear_model import LogisticRegression
# 定义逻辑回归模型
model = LogisticRegression(penalty=’l2’, dual=False, tol=0.0001, C=1.0,
fit_intercept=True, intercept_scaling=1, class_weight=None,
random_state=None, solver=’liblinear’, max_iter=100, multi_class=’ovr’,
verbose=0, warm_start=False, n_jobs=1)
"""
penalty:使用指定正则化项(默认:l2)
dual: n_samples > n_features取False(默认)
C:正则化强度的反,值越小正则化强度越大
n_jobs: 指定线程数
random_state:随机数生成器
fit_intercept: 是否需要常量
"""
from sklearn import naive_bayes
model = naive_bayes.GaussianNB()
model = naive_bayes.MultinomialNB(alpha=1.0, fit_prior=True, class_prior=None)
model = naive_bayes.BernoulliNB(alpha=1.0, binarize=0.0, fit_prior=True, class_prior=None)
"""
alpha:平滑参数
fit_prior:是否要学习类的先验概率;false-使用统一的先验概率
class_prior: 是否指定类的先验概率;若指定则不能根据参数调整
binarize: 二值化的阈值,若为None,则假设输入由二进制向量组成
"""
from sklearn import tree
model = tree.DecisionTreeClassifier(criterion=’gini’, max_depth=None,
min_samples_split=2, min_samples_leaf=1, min_weight_fraction_leaf=0.0,
max_features=None, random_state=None, max_leaf_nodes=None,
min_impurity_decrease=0.0, min_impurity_split=None,
class_weight=None, presort=False)
"""
criterion :特征选择准则gini/entropy
max_depth:树的最大深度,None-尽量下分
min_samples_split:分裂内部节点,所需要的最小样本树
min_samples_leaf:叶子节点所需要的最小样本数
max_features: 寻找最优分割点时的最大特征数
max_leaf_nodes:优先增长到最大叶子节点数
min_impurity_decrease:如果这种分离导致杂质的减少大于或等于这个值,则节点将被拆分。
"""
from sklearn.svm import SVC
model = SVC(C=1.0, kernel=’rbf’, gamma=’auto’)
"""
C:误差项的惩罚参数C
gamma: 核相关系数。浮点数,If gamma is ‘auto’ then 1/n_features will be used instead.
"""
from sklearn import neighbors
#定义kNN分类模型
model = neighbors.KNeighborsClassifier(n_neighbors=5, n_jobs=1) # 分类
model = neighbors.KNeighborsRegressor(n_neighbors=5, n_jobs=1) # 回归
"""
n_neighbors: 使用邻居的数目
n_jobs:并行任务数
"""
from sklearn.neural_network import MLPClassifier
# 定义多层感知机分类算法
model = MLPClassifier(activation='relu', solver='adam', alpha=0.0001)
"""
hidden_layer_sizes: 元祖
activation:激活函数
solver :优化算法{‘lbfgs’, ‘sgd’, ‘adam’}
alpha:L2惩罚(正则化项)参数。
"""
from sklearn.model_selection import cross_val_score
cross_val_score(model, X, y=None, scoring=None, cv=None, n_jobs=1)
"""
model:拟合数据的模型
cv : k-fold
scoring: 打分参数-‘accuracy’、‘f1’、‘precision’、‘recall’ 、‘roc_auc’、'neg_log_loss'等等
"""
from sklearn.model_selection import validation_curve
train_score, test_score = validation_curve(model, X, y, param_name, param_range, cv=None, scoring=None, n_jobs=1)
"""
model:用于fit和predict的对象
X, y: 训练集的特征和标签
param_name:将被改变的参数的名字
param_range: 参数的改变范围
cv:k-fold
"""
# 保存为pickle文件
import pickle
# 保存模型
with open('model.pickle', 'wb') as f:
pickle.dump(model, f)
# 读取模型
with open('model.pickle', 'rb') as f:
model = pickle.load(f)
model.predict(X_test)
# sklearn自带方法joblib
from sklearn.externals import joblib
# 保存模型
joblib.dump(model, 'model.pickle')
#载入模型
model = joblib.load('model.pickle')