|
| 1 | +# encoding: utf-8 |
| 2 | +__author__ = 'zhanghe' |
| 3 | + |
| 4 | +import numpy as np |
| 5 | +import scipy as sp |
| 6 | +from sklearn import svm |
| 7 | +from sklearn.cross_validation import train_test_split |
| 8 | +import matplotlib.pyplot as plt |
| 9 | + |
| 10 | +data = [] |
| 11 | +labels = [] |
| 12 | +with open("test_svc.txt") as ifile: |
| 13 | + for line in ifile: |
| 14 | + tokens = line.strip().split(' ') |
| 15 | + data.append([float(tk) for tk in tokens[:-1]]) |
| 16 | + labels.append(tokens[-1]) |
| 17 | + |
| 18 | +x = np.array(data) |
| 19 | +labels = np.array(labels) |
| 20 | +y = np.zeros(labels.shape) |
| 21 | +y[labels == 'fat'] = 1 |
| 22 | +x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.0) |
| 23 | + |
| 24 | +h = .02 |
| 25 | +# create a mesh to plot in |
| 26 | +x_min, x_max = x_train[:, 0].min() - 0.1, x_train[:, 0].max() + 0.1 |
| 27 | +y_min, y_max = x_train[:, 1].min() - 1, x_train[:, 1].max() + 1 |
| 28 | +xx, yy = np.meshgrid(np.arange(x_min, x_max, h), |
| 29 | + np.arange(y_min, y_max, h)) |
| 30 | + |
| 31 | +""" |
| 32 | +SVM |
| 33 | +""" |
| 34 | +# title for the plots |
| 35 | +titles = ['LinearSVC (linear kernel)', |
| 36 | + 'SVC with polynomial (degree 3) kernel', |
| 37 | + 'SVC with RBF kernel', |
| 38 | + 'SVC with Sigmoid kernel'] |
| 39 | +clf_linear = svm.SVC(kernel='linear').fit(x, y) |
| 40 | +# clf_linear = svm.LinearSVC().fit(x, y) |
| 41 | +clf_poly = svm.SVC(kernel='poly', degree=3).fit(x, y) |
| 42 | +clf_rbf = svm.SVC().fit(x, y) |
| 43 | +clf_sigmoid = svm.SVC(kernel='sigmoid').fit(x, y) |
| 44 | + |
| 45 | +for i, clf in enumerate((clf_linear, clf_poly, clf_rbf, clf_sigmoid)): |
| 46 | + answer = clf.predict(np.c_[xx.ravel(), yy.ravel()]) |
| 47 | + print(clf) |
| 48 | + print(np.mean(answer == y_train)) |
| 49 | + print(answer) |
| 50 | + print(y_train) |
| 51 | + |
| 52 | + plt.subplot(2, 2, i + 1) |
| 53 | + plt.subplots_adjust(wspace=0.4, hspace=0.4) |
| 54 | + |
| 55 | + # Put the result into a color plot |
| 56 | + z = answer.reshape(xx.shape) |
| 57 | + plt.contourf(xx, yy, z, cmap=plt.cm.Paired, alpha=0.8) |
| 58 | + |
| 59 | + # Plot also the training points |
| 60 | + plt.scatter(x_train[:, 0], x_train[:, 1], c=y_train, cmap=plt.cm.Paired) |
| 61 | + plt.xlabel(u'身高') |
| 62 | + plt.ylabel(u'体重') |
| 63 | + plt.xlim(xx.min(), xx.max()) |
| 64 | + plt.ylim(yy.min(), yy.max()) |
| 65 | + plt.xticks(()) |
| 66 | + plt.yticks(()) |
| 67 | + plt.title(titles[i]) |
| 68 | + |
| 69 | +plt.show() |
0 commit comments