【发布时间】:2020-07-14 18:11:38
【问题描述】:
我正在尝试使用 searborn facetgrid 可视化 MIST 数据集的 t-SNE,但是在绘图时出现错误。下面是代码和错误
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
from sklearn import datasets
from sklearn import manifold
%matplotlib inline
data = datasets.fetch_openml('mnist_784',
version=1,
return_X_y=True
)
pixel_values, targets = data
targets = targets.astype(int)
single_image = pixel_values[1, :].reshape(28,28)
plt.imshow(single_image, cmap='gray')
tsne = manifold.TSNE(n_components=2, random_state=42)
transformed_data = tsne.fit_transform(pixel_values[:3000, :])
tsne_df = pd.DataFrame(np.column_stack((transformed_data, targets[:3000])), columns=["x", "y", "targets"])
tsne_df.loc[:,"targets"] = tsne_df.targets.astype(int)
grid = sns.FacetGrid(tsne_df, hue="targets", height=8)
grid.map(plt.scatter, "x", "y").add_legend()
但是,我在运行 grid.map(plt.scatter, "x", "y").add_legend() 时遇到以下错误
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-18-84d161de948f> in <module>
----> 1 grid.map(plt.scatter, "x", "y").add_legend()
~/opt/miniconda3/envs/ml/lib/python3.7/site-packages/seaborn/axisgrid.py in map(self, func, *args, **kwargs)
736
737 # Get the current axis
--> 738 ax = self.facet_axis(row_i, col_j)
739
740 # Decide what color to plot with
~/opt/miniconda3/envs/ml/lib/python3.7/site-packages/seaborn/axisgrid.py in facet_axis(self, row_i, col_j)
866
867 # Get a reference to the axes object we want, and make it active
--> 868 plt.sca(ax)
869 return ax
870
~/opt/miniconda3/envs/ml/lib/python3.7/site-packages/matplotlib/pyplot.py in sca(ax)
856 m.canvas.figure.sca(ax)
857 return
--> 858 raise ValueError("Axes instance argument was not found in a figure")
859
860
ValueError: Axes instance argument was not found in a figure
【问题讨论】:
-
grid = sns.FacetGrid(tsne_df, hue="targets", height=8)不正确。您最需要提供行和列参数。 seaborn.FacetGrid -
@TrentonMcKinney 谢谢,我刚刚将行更新为 grid = sns.FacetGrid(tsne_df,row="x", col="y", hue="targets", size=8) 它做到了没有给出错误,但现在代码运行了 4 个小时,并且仍在运行。
-
如果您有很多列/行组合,使用 FacetGrid 可能不起作用。看起来下面 Diziet 的回答就是一个很好的例子。
标签: python-3.x pandas matplotlib seaborn