把别人的代码套到自己的 Jupyter 环境跑自己的数据,遇到了两个小问题:
- 1 绘图时数据的一点小细节;
- 2 plotly 画图时,结果一直显示不出来。
第一个问题是在 x[y_clusters == 0, 0] 这里报错,根据报错提示 修改为 x.loc[y_clusters == 0, 0] 就解决了。第二个问题,做了一点尝试,在这里汇总一下解决办法,希望未来可以帮助到其他小伙伴。
x 是聚类用的数据, y_clusters 是训练好的 KMeans 模型 fit_predict 的结果。
直接 用 matplotlib 下的 plot 来做 scatter:
/Python
x = df3
fig = plt.figure(figsize = (15,15))
ax = fig.add_subplot(111, projection='3d')
ax.scatter(x.loc[y_clusters == 0,0],x.loc[y_clusters == 0,1],x.loc[y_clusters == 0,2], s = 40 , color = 'windows blue', label = "cluster 0")
ax.scatter(x.loc[y_clusters == 1,0],x.loc[y_clusters == 1,1],x.loc[y_clusters == 1,2], s = 40 , color = 'orange', label = "cluster 1")
ax.scatter(x.loc[y_clusters == 2,0],x.loc[y_clusters == 2,1],x.loc[y_clusters == 2,2], s = 40 , color = 'faded green', label = "cluster 2")
ax.scatter(x.loc[y_clusters == 3,0],x.loc[y_clusters == 3,1],x.loc[y_clusters == 3,2], s = 40 , color = 'red', label = "cluster 3")
ax.scatter(x.loc[y_clusters == 4,0],x.loc[y_clusters == 4,1],x.loc[y_clusters == 4,2], s = 40 , color = 'purple', label = "cluster 4")
ax.scatter(x.loc[y_clusters == 5,0],x.loc[y_clusters == 5,1],x.loc[y_clusters == 5,2], s = 40 , color = 'pink', label = "cluster 5")
ax.scatter(x.loc[y_clusters == 6,0],x.loc[y_clusters == 6,1],x.loc[y_clusters == 6,2], s = 40 , color = 'steel blue', label = "cluster 6")
ax.set_xlabel('Repair')
ax.set_ylabel('age')
ax.set_zlabel('power_on')
ax.legend()
plt.show()
运行结果:

用 plotly 画图:
导的包:
from mpl_toolkits.mplot3d import Axes3D
import plotly.graph_objs as go
from plotly import tools
from plotly.subplots import make_subplots
import plotly.offline as py
画图代码:
Scene = dict(xaxis = dict(title = 'repair'),yaxis = dict(title = 'age'),zaxis = dict(title = 'power_on'))
labels = km.labels_
trace = go.Scatter3d(x=x.iloc[:, 0], y=x.iloc[:, 1], z=x.iloc[:, 2], mode='markers',marker=dict(color = labels, size= 10, line=dict(color= 'black',width = 10)))
layout = go.Layout(margin=dict(l=0,r=0),scene = Scene,height = 800,width = 800)
data = [trace]
fig = go.Figure(data = data, layout = layout)
fig.show()
第二个问题的解决办法:
(1) 对我有用的:
添加代码:
import plotly.io as pio
pio.renderers.default = 'iframe' # or 'notebook' or 'colab' or 'jupyterlab'
其他方法:
(2) 生成本地的 HTML 文件:
import plotly.offline as py
py.plot(fig, filename = 'xxx.html')
(3) 同样,也是在 HTML 上做文章,我有看到有人用这样的方式成功了,附在下面:
from IPython.display import HTML
HTML(fig.show())
(4)安装拓展 jupyterlab-plotly:

在这之前,还检查了一下有关的一个拓展有没有被安装。一般来说,装好后重启 Kernel 就可以了。但是对我而言还不行。又搜了一下,发现了其他的解决办法。有的还说要去安装一下 nodejs,我也尝试了。但是在安装前用第一个解决办法显示成功,说明 nodejs 不是必须要有的。
(5) 换个浏览器。
来看下结果吧:

个人更喜欢 plotly 画出来的这种具有交互效果的图,还可以用鼠标转各个角度、拉近放大,悬停还可以显示图片坐标。
更改颜色属性,换了一个自己更喜欢的紫色系:

代码参考🔗:
https://www.kaggle.com/code/scratchpad/notebook58b759fc58/edit
解决方案参考🔗:

