How to do PCA and SVM for classification in python -
i doing classification, , have list 2 sizes this;
data=[list1,list2]
list1 1000*784 size. means 1000 images have been reshaped 28*28 size 784.
list2 1000*1 size. shows label each images belonged to. below code, applied pca:
from matplotlib.mlab import pca results = pca(data[0])
the output this:
out[40]: <matplotlib.mlab.pca instance @ 0x7f301d58c638>
now, want use svm classifier. should add labels. have new data svm:
newdata=[results,data[1]]
i not know how use svm here.
from sklearn.decomposition import pca sklearn.svm import svc sklearn import cross_validation data=[list1,list2] x = data[0] y = data[1] x_train, x_test, y_train, y_test = cross_validation.train_test_split(x, y, test_size=0.4, random_state=0) pca = pca(n_components=2)# adjust pca.fit(x_train) x_t_train = pca.transform(x_train) x_t_test = pca.transform(x_test) clf = svc() clf.fit(x_t_train, y_train) print 'score', clf.score(x_t_test, y_test) print 'pred label', clf.predict(x_t_test)
here tested code on dataset.
import numpy np sklearn import datasets sklearn.decomposition import pca sklearn.svm import svc sklearn import cross_validation iris = datasets.load_iris() x = iris.data y = iris.target x_train, x_test, y_train, y_test = cross_validation.train_test_split(x, y, test_size=0.4, random_state=0) pca = pca(n_components=2)# adjust pca.fit(x_train) x_t_train = pca.transform(x_train) x_t_test = pca.transform(x_test) clf = svc() clf.fit(x_t_train, y_train) print 'score', clf.score(x_t_test, y_test) print 'pred label', clf.predict(x_t_test)
based on these references:
Comments
Post a Comment