用Python和scikit-learn来介绍机器学习

用Python和scikit-learn来介绍机器学习

数据加载

当我们学习机器学习的时候,首先必须得有数据,我们得把数据加载到内存中才能对它进行处理。这一节我们先介绍如何加载数据的问题。我们以从著名的UCI Machine Learning Repository.加载.csv格式的文件来说明。

import numpy as np
# the python version is 3.5
import urllib.request
# url with dataset
url="http://archive.ics.uci.edu/ml/machine-learning-databases/pima-indians-diabetes/pima-indians-diabetes.data"
# download the file
raw_data = urllib..request.urlopen(url)
# load the CSV file as a numpy matrix
dataset = np.loadtxt(raw_data,delimiter=",")
# separate the data from the target attributes
X = dataset[:,0:8]
Y = dataset[:,8]

说明:下面的讨论我们将使用这里加载的数据集,这里 X 为特征矩阵,Y 为类别标签向量。

数据正则化

几乎所有的机器学习算法基于梯度方法,而大部分梯度方法对数据的尺度高度敏感,因此在我们运行机器学习算法之前,我们应该进行正则化(normalization),或者所谓的标准化(standardization)

  • 正则化:每一个特征的范围变为从01
  • 标准化:每一个特征有一个平均值0和方差1
from sklearn import preprocessing
# normalize the data attributes
normalized_X = preprocessing.normalize(X)
# standardize the data attributes
standardized_X = preprocessing.scale(X)

特征选择

我们在处理机器学习任务时最重要的能力是恰当的选择或者甚至创造特征,这被称为特征选择或者特征工程。尽管特征工程是一个非常的创造性过程,并且更多的依赖直觉和领域知识,但是有许多已有的特征选择方法。树方法(Tree algorithms)允许计算特征的信息量。

from sklearn import metrics
from sklearn.ensemble import ExtraTreesClassifier
model = ExtraTreesClassifier()
model.fit(X, y)
# display the relative importance of each attribute
print(model.feature_importances_)

所有其他的方法都是基于有效的搜索特征子集去找到最好的特征子集以使开发的模型提供最好的效果。其中的一种搜索算法是递归特征消减算法(Recursive Feature Elimination)

from sklearn.feature_selection import RFE
from sklearn.linear_model import LogisticRegression
model = LogisticRegression()
# create the RFE model and select 3 attributes
rfe = RFE(model, 3)
rfe = rfe.fit(X, y)
# summarize the selection of the attributes
print(rfe.support_)
print(rfe.ranking_)

算法开发

LR

这个算法的好处是输出是每一个对象属于一个类的概率

from sklearn import metrics
from sklearn.linear_model import LogisticRegression
model = LogisticRegression()
model.fit(X, y)
print(model)
# make predictions
expected = y
predicted = model.predict(X)
# summarize the fit of the model
print(metrics.classification_report(expected, predicted))
print(metrics.confusion_matrix(expected, predicted))

朴素贝叶斯

这个算法的主要任务是恢复训练样本的数据分布密度,这个方法在多类分类问题中经常提供好的效果

from sklearn import metrics
from sklearn.naive_bayes import GaussianNB
model = GaussianNB()
model.fit(X, y)
print(model)
# make predictions
expected = y
predicted = model.predict(X)
# summarize the fit of the model
print(metrics.classification_report(expected, predicted))
print(metrics.confusion_matrix(expected, predicted))

K最近邻

当参数(大部数为度量)被很好的设置时,这个算法对回归问题
能提供好的效果。

from sklearn import metrics
from sklearn.neighbors import KNeighborsClassifier
# fit a k-nearest neighbor model to the data
model = KNeighborsClassifier()
model.fit(X, y)
print(model)
# make predictions
expected = y
predicted = model.predict(X)
# summarize the fit of the model
print(metrics.classification_report(expected, predicted))
print(metrics.confusion_matrix(expected, predicted))

决策树

Classification and Regression Trees (CART) 经常被用在对象拥有分类特征和回归、分类问题,非常适合多分类问题。

from sklearn import metrics
from sklearn.tree import DecisionTreeClassifier
# fit a CART model to the data
model = DecisionTreeClassifier()
model.fit(X, y)
print(model)
# make predictions
expected = y
predicted = model.predict(X)
# summarize the fit of the model
print(metrics.classification_report(expected, predicted))
print(metrics.confusion_matrix(expected, predicted))

支持向量机

是最流行的分类问题机器学习算法之一,通过“一对多”的方法可以和LR一样用来多分类。

from sklearn import metrics
from sklearn.svm import SVC
# fit a SVM model to the data
model = SVC()
model.fit(X, y)
print(model)
# make predictions
expected = y
predicted = model.predict(X)
# summarize the fit of the model
print(metrics.classification_report(expected, predicted))
print(metrics.confusion_matrix(expected, predicted))

怎样优化算法参数

在创造实际有效的算法中最困难的一个阶段是选择正确的参数,对于有足够的经验来说,这是很容易的。但是不管怎样,我们不得不做搜索。幸运的是,Scikit-learn提供了许多有效的函数来做这件事。
作为一个例子,我们来看一看正则化参数的选取。

import numpy as np
from sklearn.linear_model import Ridge
from sklearn.grid_search import GridSearchCV
# prepare a range of alpha values to test
alphas = np.array([1,0.1,0.01,0.001,0.0001,0])
# create and fit a ridge regression model, testing each alpha
model = Ridge()
grid = GridSearchCV(estimator=model, param_grid=dict(alpha=alphas))
grid.fit(X, y)
print(grid)
# summarize the results of the grid search
print(grid.best_score_)
print(grid.best_estimator_.alpha)

Sometimes it is more efficient to randomly select a parameter from the given range, estimate the algorithm quality for this parameter and choose the best one.
有时随机地从一个给定的范围选取一个参数是更有效的,对于这个参数评估这个算法并选择最好的一个。

import numpy as np
from scipy.stats import uniform as sp_rand
from sklearn.linear_model import Ridge
from sklearn.grid_search import RandomizedSearchCV
# prepare a uniform distribution to sample for the alpha parameter
param_grid = {'alpha': sp_rand()}
# create and fit a ridge regression model, testing random alpha values
model = Ridge()
rsearch = RandomizedSearchCV(estimator=model, param_distributions=param_grid, n_iter=100)
rsearch.fit(X, y)
print(rsearch)
# summarize the results of the random parameter search
print(rsearch.best_score_)
print(rsearch.best_estimator_.alpha)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值