SVM Classification python example using sklearn 分类例子

这篇博客展示了如何在Python中使用sklearn库进行支持向量机(SVM)分类。通过SVC构建线性核函数的SVM分类器,并使用交叉验证计算精度和F1分数。
摘要由CSDN通过智能技术生成

1. No cross validation

ref: 

http://stackoverflow.com/questions/16927964/how-to-calculate-precision-recall-and-f-score-with-libsvm-in-python

from sklearn import svm
from sklearn import metrics
from sklearn.cross_validation import train_test_split
from sklearn.datasets import load_iris

# prepare dataset
iris = load_iris()
X = iris.data[:, :2]
y = iris.target
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)

# svm classification
clf = svm.SVC(kernel='rbf', gamma=0.7, C = 1.0).fit(X_train, y_train)
y_predicted = clf.predict(X_test)

# performance
print "Classification report for %s" % clf
print
print metrics.classification_report(y_test, y_predicted)
print
print "Confusion matrix"
print metrics.confusion_matrix(y_test, y_predicted)
This example would output f1. if you need accuracy, using the code below
metrics.accuracy_score(y_test, y_predicted)

2. Cross Validation


head is the same with the example above, after we have X and y, 

 clf2 = svm.SVC(kernel='linear', gamma=0.7, C = 1.0) # build a svm classifier
 scores = cross_validation.cross_val_score(clf2, X, y, cv = 5) # calculate the accuracy
 scores2 = cross_validation.cross_val_score(clf2, X, y, cv = 5, scoring = 'f1') # calculate the f1
  
 print 'clf2 res:\n'
 print scores.mean()
 print 'clf2 f1:\n'
 print scores2.mean()






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值