使用 TSNE 进行降维。为什么 3D 图形不起作用?

Using TSNE to dimensionality reduction. Why 3 D graph is not working?

我使用了 Sklearn 的数字数据集,并尝试使用 TSNE(t-分布式随机邻域嵌入)将维度从 64 减少到 3:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
#%matplotib inline
from sklearn.manifold import TSNE
from sklearn.datasets import load_digits
from mpl_toolkits.mplot3d import Axes3D


digits = load_digits()
digits_df = pd.DataFrame(digits.data,)
digits_df["target"] = pd.Series(digits.target)

tsne = TSNE(n_components=3)
digits_tsne = tsne.fit_transform(digits_df.iloc[:,:64])
digits_df_tsne = pd.DataFrame(digits_tsne,
                            columns =["Component1","Component2","Component3"])

finalDf = pd.concat([digits_df_tsne, digits_df["target"]], axis = 1)

#Visualizing 3D
figure = plt.figure(figsize=(9,9))
axes = figure.add_subplot(111,projection = "3d")
dots = axes.scatter(xs = finalDf[:,0],ys = finalDf[:,1],zs = finalDf[:,2],
                   c = digits.target, cmap = plt.cm.get_cmap("nipy_spectral_r",10))

最后的Df:

错误:

TypeError: '(slice(None, None, None), 0)' is an invalid key

怎么了?有人可以帮助我吗?

您正在尝试对无效的 pandas 数据帧进行 numpy 切片,因此首先将数据帧转换为 numpy 数组。

这是更新后的代码:-

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
#%matplotib inline
from sklearn.manifold import TSNE
from sklearn.datasets import load_digits
from mpl_toolkits.mplot3d import Axes3D


digits = load_digits()
digits_df = pd.DataFrame(digits.data,)
digits_df["target"] = pd.Series(digits.target)

tsne = TSNE(n_components=3)
digits_tsne = tsne.fit_transform(digits_df.iloc[:,:64])
digits_df_tsne = pd.DataFrame(digits_tsne,
                            columns =["Component1","Component2","Component3"])

finalDf = pd.concat([digits_df_tsne, digits_df["target"]], axis = 1)

#Visualizing 3D
figure = plt.figure(figsize=(9,9))
axes = figure.add_subplot(111,projection = "3d")
dots = axes.scatter(xs = finalDf.to_numpy()[:,0],ys = finalDf.to_numpy()[:,1],zs = finalDf.to_numpy()[:,2],
                   c = digits.target, cmap = plt.cm.get_cmap("nipy_spectral_r",10))