python scikit-learn库
实现SVM
1.SVC(Support Vector Classification)支持向量分类
基于libsvm实现的(libsvm详情参考 或者百科),数据拟合的时间复杂度是数据样本的二次方,这使得他很难扩展到10000个数据集。
当输入是多类别时(SVM最初是处理二分类问题的),通过一对一的方案解决,当然也有别的解决办法,比如说(以下为引用):其他多类分类方法。除了以上几种方法外,还有有向无环图SVM(Directed Acyclic Graph SVMs,简称DAG-SVMs)和对类别进行二进制编码的纠错编码SVMs。
SVC参数解释:
sklearn中调用机器学习的方法都是一个道理,算法就是一个类,其中包含fit(),predict()等等许多方法,我们只要输入训练样本和标记,以及模型的一些可能的参数,自然就直接出分类的结果。
示例:
X = np.array([[-
1,-
1],[-
2,-
1],[
1,
1],[
2,
1]])
y = np.array([
1,
1,
2,
2])
from sklearn.svm
import SVC
neg = y[:] ==
1
pos = y[:] ==
2
axes = plt.gca()
axes.scatter(X[pos][
0],X[pos][
1],marker=
'+',c=
'k',s=
60,linewidth=
2,label=
'Pass')
axes.scatter(X[neg][
0],X[neg][
1],c=
'y',s=
60,linewidth=
2,label=
'Fail')
axes.scatter(-
0.8,-
1,c=
'r',s=
60,linewidth=
2,label=
'Predict')
axes.legend(frameon=
True, fancybox=
True)
clf = SVC()
clf.fit(X,y)
print clf.fit(X,y)
print clf.predict([-
0.8,-
1])
输出:
SVC(C=
1.0, cache_size=
200, class_weight=
None, coef0=
0.0,
decision_function_shape=
None, degree=
3, gamma=
'auto', kernel=
'rbf',
max_iter=-
1, probability=
False, random_state=
None, shrinking=
True,
tol=
0.001, verbose=
False)
[
1]
2.NuSVC(Nu-Support Vector Classification)核支持向量分类
和SVC类似,也是基于libsvm实现的,但不同的是通过一个参数空值支持向量的个数
import numpy
as np
X = np.array([[-
1, -
1], [-
2, -
1], [
1,
1], [
2,
1]])
y = np.array([
1,
1,
2,
2])
from sklearn.svm
import NuSVC
clf = NuSVC()
clf.fit(X, y)
print clf.fit(X,y)
print(clf.predict([[-
0.8, -
1]]))
3.LinearSVC(Linear Support Vector Classification)
线性支持向量分类
类似于SVC,但是其使用的核函数是”linear“上边介绍的两种是按照RBF(径向基函数)计算的,其实现也不是基于LIBSVM,所以它具有更大的灵活性在选择处罚和损失函数时,而且可以适应更大的数据集,他支持密集和稀疏的输入是通过一对一的方式解决的。
LinearSVC 参数解释
C:目标函数的惩罚系数C,用来平衡分类间隔margin和错分样本的,default C =
1.0;
loss :指定损失函数
penalty :
dual :选择算法来解决对偶或原始优化问题。当n_samples > n_features 时dual=false。
tol :(default =
1e -
3): svm结束标准的精度;
multi_class:如果y输出类别包含多类,用来确定多类策略, ovr表示一对多,“crammer_singer”优化所有类别的一个共同的目标
如果选择“crammer_singer”,损失、惩罚和优化将会被被忽略。
fit_intercept :
intercept_scaling :
class_weight :对于每一个类别i设置惩罚系数C = class_weight[i]*C,如果不给出,权重自动调整为 n_samples / (n_classes * np.bincount(y))
verbose:跟多线程有关
示例:
import numpy
as np
X = np.array([[-
1, -
1], [-
2, -
1], [
1,
1], [
2,
1]])
y = np.array([
1,
1,
2,
2])
from sklearn.svm
import LinearSVC
clf = LinearSVC()
clf.fit(X, y)
print clf.fit(X,y)
print(clf.predict([[-
0.8, -
1]]
4.数据不平衡问题(Unbalanced problems)
对于非平衡级分类超平面,使用不平衡SVC找出最优分类超平面,基本的思想是,我们先找到一个普通的分类超平面,自动进行校正,求出最优的分类超平面
这里可以使用 SVC(kernel=”linear”)
针对下面的svc可以使用 clf=SGDClassifie(n_iter=100,alpha=0.01)代替
rng = np.random.RandomState(
0)
n_samples_1 =
1000
n_samples_2 =
100
X = np.r_[
1.5*rng.randn(n_samples_1,
2),
0.5*rng.randn(n_samples_2,
2)+[
2,
2]]
y = [
0]*(n_samples_1)+[
1]*(n_samples_2)
print X.shape
print X
print y
输出结果:
(
1100,
2)
[[
2.64607852 0.60023581]
[
1.46810698 3.3613398 ]
[
2.80133699 -
1.46591682]
...,
[
1.68550965 2.53503626]
[
1.68945865 2.86728609]
[
1.45085528 2.28630668]]
[
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0, ...,
1,
1,
1]
clf = SVC(kernel=
'linear', C=
1.0)
clf.fit(X, y)
w = clf.coef_[
0]
a = -w[
0] / w[
1]
xx = np.linspace(-
5,
5)
yy = a * xx - clf.intercept_[
0] / w[
1]
h0 = plt.plot(xx, yy,
'k-', label=
'no weights')
wclf = SVC(kernel=
'linear', class_weight={
1:
10})
wclf.fit(X, y)
ww = wclf.coef_[
0]
wa = -ww[
0] / ww[
1]
wyy = wa * xx - wclf.intercept_[
0] / ww[
1]
h1 = plt.plot(xx, wyy,
'k--', label=
'with weights')
plt.scatter(X[:,
0], X[:,
1], c=y,s=
5,linewidth=
0.5)
plt.legend()
plt.axis(
'tight')
plt.show()
随机数种子RandomState
RandomState exposes a number of methods for generating random numbersdrawn from a variety of probability distributions.
使用示例:
prng = np.random.RandomState(
123456789)
prng.rand(
2,
4)
prng.chisquare(
1, size=(
2,
2))
prng.standard_t(
1, size=(
2,
3))
prng.poisson(
5, size=
10)
clf.coef_,clf.intercept_用法
clf.coef_表示回归直线的参数
clf.intercept_表示回归直线截距
二维坐标下的直线方程由Ax+By=C,clf.coef_表示[A,B],C即为clf.intercept_
5.SVR(Support Vector Regression)支持向量回归
支持分类的支持向量机可以推广到解决回归问题,这种方法称为支持向量回归
支持向量分类所产生的模型仅仅依赖于训练数据的一个子集,因为构建模型的成本函数不关心在超出边界范围的点,类似的,通过支持向量回归产生的模型依赖于训练数据的一个子集,因为构建模型的函数忽略了靠近预测模型的数据集。
有三种不同的实现方式:支持向量回归SVR,nusvr和linearsvr。linearsvr提供了比SVR更快实施但只考虑线性核函数,而nusvr实现比SVR和linearsvr略有不同
from sklearn.svm
import SVR
X = np.sort(
5 * np.random.rand(
40,
1), axis=
0)
y = np.sin(X).ravel()
y[::
5] +=
3 * (
0.5 - np.random.rand(
8))
svr_rbf = SVR(kernel=
'rbf', C=
1e3, gamma=
0.1)
svr_lin = SVR(kernel=
'linear', C=
1e3)
svr_poly = SVR(kernel=
'poly', C=
1e3, degree=
2)
y_rbf = svr_rbf.fit(X, y).predict(X)
y_lin = svr_lin.fit(X, y).predict(X)
y_poly = svr_poly.fit(X, y).predict(X)
lw =
2
plt.scatter(X, y, color=
'darkorange', label=
'data')
plt.hold(
'on')
plt.plot(X, y_rbf, color=
'navy', lw=lw, label=
'RBF model')
plt.plot(X, y_lin, color=
'c', lw=lw, label=
'Linear model')
plt.plot(X, y_poly, color=
'cornflowerblue', lw=lw, label=
'Polynomial model')
plt.xlabel(
'data')
plt.ylabel(
'target')
plt.title(
'Support Vector Regression')
plt.legend()
plt.show()
输出: