在python上运行鸢尾花分类实验首先要先下载numpy、matplotlib再下载scikit-learn
pip install --index https://pypi.mirrors.ustc.edu.cn/simple/ numpy pip install --index https://pypi.mirrors.ustc.edu.cn/simple/ matplotlib pip install --index https://pypi.mirrors.ustc.edu.cn/simple/ scikit-learn
但是在下载完之后点击运行又会报attributeerror: 'axes3d' object has no attribute 'w_xaxis'. did you mean: 'xaxis'?
这是因为matplotlib版本升级的原因,按照报错信息将w_xaxis改为xaxis就可以,但是之后又会出现可视化的界面是一片空白,这时在ax = Axes3D(fig, rect=[0, 0, .95, 1], elev=48, azim=134)后面加上
fig.add_axes(ax)就可以
鸢尾花分类的完整代码为
import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from sklearn.cluster import KMeans from sklearn import datasets np.random.seed(5) centers = [[1, 1], [-1, -1], [1, -1]] iris = datasets.load_iris() X = iris.data y = iris.target estimators = {'k_means_iris_3': KMeans(n_clusters=3), 'k_means_iris_8': KMeans(n_clusters=8), 'k_means_iris_bad_init': KMeans(n_clusters=3, n_init=1, init='random')} fignum = 1 for name, est in estimators.items(): fig = plt.figure(fignum, figsize=(4, 3)) plt.clf() ax = Axes3D(fig, rect=[0, 0, .95, 1], elev=48, azim=134) fig.add_axes(ax) plt.cla() est.fit(X) labels = est.labels_ ax.scatter(X[:, 3], X[:, 0], X[:, 2], c=labels.astype(float)) ax.xaxis.set_ticklabels([]) ax.yaxis.set_ticklabels([]) ax.zaxis.set_ticklabels([]) ax.set_xlabel('Petal width') ax.set_ylabel('Sepal length') ax.set_zlabel('Petal length') fignum = fignum + 1 # Plot the ground truth fig = plt.figure(fignum, figsize=(4, 3)) plt.clf() ax = Axes3D(fig, rect=[0, 0, .95, 1], elev=48, azim=134) fig.add_axes(ax) plt.cla() for name, label in [('Setosa', 0), ('Versicolour', 1), ('Virginica', 2)]: ax.text3D(X[y == label, 3].mean(), X[y == label, 0].mean() + 1.5, X[y == label, 2].mean(), name, horizontalalignment='center', bbox=dict(alpha=.5, edgecolor='w', facecolor='w')) # Reorder the labels to have colors matching the cluster results y = np.choose(y, [1, 2, 0]).astype(float) ax.scatter(X[:, 3], X[:, 0], X[:, 2], c=y) ax.xaxis.set_ticklabels([]) ax.yaxis.set_ticklabels([]) ax.zaxis.set_ticklabels([]) ax.set_xlabel('Petal width') ax.set_ylabel('Sepal length') ax.set_zlabel('Petal length') plt.show()
标签:iris,set,分类,ticklabels,问题,plt,fig,ax,鸢尾花 From: https://www.cnblogs.com/cinan/p/18111733