对数据降维后使用KNN算法进行分类的案例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 from scipy.io import loadmatimport numpy as npfrom sklearn.neighbors import KNeighborsClassifierimport picklefrom sklearn.decomposition import PCAmnist=loadmat('mnist-original.mat' ) x,y=mnist["data" ],mnist["label" ] x=x.T y=y[0 ] pca=PCA() pca.fit(x) cumsum=np.cumsum(pca.explained_variance_ratio_) d=np.argmax(cumsum>=0.95 )+1 pca=PCA(n_components=d) x1=pca.fit_transform(x) x_train=x1[:60000 ] y_train=y[:60000 ] shuffle_index=np.random.permutation(60000 ) x_train=x_train[shuffle_index] y_train=y_train[shuffle_index] sgd_clf=KNeighborsClassifier() sgd_clf.fit(x_train,y_train) print (d)with open ('clf.pickle' , 'wb' ) as f: pickle.dump(sgd_clf, f)
154
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 from scipy.io import loadmatimport numpy as npimport picklefrom sklearn.decomposition import PCAfrom sklearn.metrics import accuracy_scoremnist=loadmat('mnist-original.mat' ) x,y=mnist["data" ],mnist["label" ] x=x.T y=y[0 ] pca=PCA(n_components=154 ) x1=pca.fit_transform(x) some_digit=x1[66000 ] x_test=x[60000 :] y_test=y[60000 :] with open ('clf.pickle' , 'rb' ) as f: clf2 = pickle.load(f) y_pred = clf2.predict(x1[60000 :]) print (accuracy_score(y[60000 :], y_pred))
0.9719
LLE
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 import numpy as npimport matplotlib.pyplot as pltfrom mpl_toolkits.mplot3d import Axes3Dfrom sklearn.manifold import LocallyLinearEmbeddingN=2000 angle=np.pi*(1.5 *np.random.random(int (N/2 ))-1 ) height=5 *np.random.random(N) x=np.array([np.append(np.cos(angle),-1 *np.cos(angle)),height,np.append(np.sin(angle),2 -np.sin(angle))]) x=x.T fig=plt.figure() ax=Axes3D(fig) ax.scatter(x[:,0 ],x[:,1 ],x[:,2 ]) lle=LocallyLinearEmbedding(n_components=2 ,n_neighbors=12 ) x2d=lle.fit_transform(x) plt.figure() plt.plot(x2d[:,0 ],x2d[:,1 ],'k.' ) plt.show()
c:\users\administrator\appdata\local\programs\python\python37\lib\site-packages\ipykernel_launcher.py:12: MatplotlibDeprecationWarning: Axes3D(fig) adding itself to the figure is deprecated since 3.4. Pass the keyword argument auto_add_to_figure=False and use fig.add_axes(ax) to suppress this warning. The default value of auto_add_to_figure will change to False in mpl3.5 and True values will no longer work in 3.6. This is consistent with other Axes classes.
if sys.path[0] == '':