svm.py-20171018

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 18 17:20:19 2017

@author: vicky
"""

'''
SVC参数解释 
(1)C: 目标函数的惩罚系数C,用来平衡分类间隔margin和错分样本的,default C = 1.0; 
(2)kernel:参数选择有RBF, Linear, Poly, Sigmoid, 默认的是"RBF"; 
(3)degree:if you choose 'Poly' in param 2, this is effective, degree决定了多项式的最高次幂; 
(4)gamma:核函数的系数('Poly', 'RBF' and 'Sigmoid'), 默认是gamma = 1 / n_features; 
(5)coef0:核函数中的独立项,'RBF' and 'Poly'有效; 
(6)probablity: 可能性估计是否使用(true or false); 
(7)shrinking:是否进行启发式; 
(8)tol(default = 1e - 3): svm结束标准的精度; 
(9)cache_size: 制定训练所需要的内存(以MB为单位); 
(10)class_weight: 每个类所占据的权重,不同的类设置不同的惩罚参数C, 缺省的话自适应; 
(11)verbose: 跟多线程有关,不大明白啥意思具体; 
(12)max_iter: 最大迭代次数,default = 1, if max_iter = -1, no limited; 
(13)decision_function_shape : ‘ovo’ 一对一, ‘ovr’ 多对多  or None 无, default=None 
(14)random_state :用于概率估计的数据重排时的伪随机数生成器的种子。 
 ps:7,8,9一般不考虑。 
'''  
from sklearn.svm import SVC  
import numpy as np  

X= np.array([[-1,-1],[-2,-1],[1,1],[2,1]])  
y = np.array([1,1,2,2])  
  
clf = SVC()  
clf.fit(X,y)  
clf.predict([[-0.8,-1]])

'''
NuSVC参数 
nu:训练误差的一个上界和支持向量的分数的下界。应在间隔(0,1 ]。 
其余同SVC 
'''  
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)    
clf.predict([[-0.8,-1]])

'''  
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:跟多线程有关,不大明白啥意思具体<pre name="code" class="python">  
'''
  
from sklearn.svm import SVC  
  
X=[[0],[1],[2],[3]]  
Y = [0,1,2,3]  
  
clf = SVC(decision_function_shape='ovo') #ovo为一对一  
clf.fit(X,Y)  
  
dec = clf.decision_function([[1]])    #返回的是样本距离超平面的距离  
print(dec)  
  
clf.decision_function_shape = "ovr"  
dec =clf.decision_function([1]) #返回的是样本距离超平面的距离  
print(dec)  
  
#预测  
print(clf.predict([1]))

'''
Multi-class classification(多类别分类)
'''
from sklearn.svm import SVC,LinearSVC  
  
X=[[0],[1],[2],[3]]  
Y = [0,1,2,3]  
  
''''' 
SVC and NuSVC 
'''  
clf = SVC(decision_function_shape='ovo') #ovo为一对一  
clf.fit(X,Y)  
print("SVC:",clf.fit(X,Y))  
  
dec = clf.decision_function([[1]])    #返回的是样本距离超平面的距离  
print("SVC:",dec) 
  
clf.decision_function_shape = "ovr"  
dec =clf.decision_function([1]) #返回的是样本距离超平面的距离  
print("SVC:",dec)  
  
#预测  
print("预测:",clf.predict([1])) 
  

'''
Unbalanced problems(数据不平衡问题)
 '''
 
import numpy as np  
import matplotlib.pyplot as plt  
from sklearn import svm  
#from sklearn.linear_model import SGDClassifier  
  
# we create 40 separable points  
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)  
#print(y)  
  
# fit the model and get the separating hyperplane  
clf = svm.SVC(kernel='linear', C=1.0)  
clf.fit(X, y)  
  
w = clf.coef_[0]  
a = -w[0] / w[1]      #a可以理解为斜率  
xx = np.linspace(-5, 5)  
yy = a * xx - clf.intercept_[0] / w[1]    #二维坐标下的直线方程  
  
# get the separating hyperplane using weighted classes  
wclf = svm.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]   #带权重的直线  
  
# plot separating hyperplanes and samples  
h0 = plt.plot(xx, yy, 'k-', label='no weights')  
h1 = plt.plot(xx, wyy, 'k--', label='with weights')  
plt.scatter(X[:, 0], X[:, 1], c=y)  
plt.legend()

#不显示线  
plt.axis('tight')  
plt.show()

'''
regress
'''
from sklearn import svm  
X = [[0, 0], [2, 2]]  
y = [0.5, 2.5]  
clf = svm.SVR()  
clf.fit(X, y)   
clf.predict([[1, 1]]) 

'''
线性回归
'''

import numpy as np  
from sklearn.svm import SVR  
import matplotlib.pyplot as plt  
  
###############################################################################  
# Generate sample data  
X = np.sort(5 * np.random.rand(40, 1), axis=0)  #产生40组数据,每组一个数据,axis=0决定按列排列,=1表示行排列  
y = np.sin(X).ravel()   #np.sin()输出的是列,和X对应,ravel表示转换成行  
  
###############################################################################  
# Add noise to targets  
y[::5] += 3 * (0.5 - np.random.rand(8))  
  
###############################################################################  
# Fit regression model  
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)  
  
###############################################################################  
# look at the results  
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()

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值