RBF核PCA训练报错:arrays to stack must be passed as a sequence
RBF核PCA实现报错:"arrays to stack must be passed as a sequence"
错误原因
报错出现在np.column_stack()调用处:
X_pc = np.column_stack((eigvecs[:, i] for i in range(n_components)))
np.column_stack()要求传入**序列类型(如列表、元组)**的数组集合,但此处使用的是生成器表达式(eigvecs[:, i] for i in range(n_components)),生成器不属于numpy可直接识别的序列参数类型,导致无法正确解析要堆叠的数组。
修复方案
将生成器表达式转换为列表(把圆括号改为方括号),让column_stack能正确识别要堆叠的数组序列:
X_pc = np.column_stack([eigvecs[:, i] for i in range(n_components)])
修复后完整代码
import numpy as np from scipy.spatial.distance import pdist, squareform from scipy.linalg import eigh from sklearn.datasets import make_moons import matplotlib.pyplot as plt def rbf_kernel_pca(X, gamma, n_components): """ RBF kernel PCA implementation. Parameters ------------ X: {NumPy ndarray}, shape = [n_samples, n_features] gamma: float Tuning parameter of the RBF kernel n_components: int Number of principal components to return Returns ------------ X_pc: {NumPy ndarray}, shape = [n_samples, k_features] Projected dataset """ # Calculate pairwise squared Euclidean distances sq_dists = pdist(X, 'sqeuclidean') # Convert pairwise distances into a square matrix. mat_sq_dists = squareform(sq_dists) # Compute the symmetric kernel matrix. K = np.exp(-gamma * mat_sq_dists) # Center the kernel matrix. N = K.shape[0] one_n = np.ones((N, N)) / N K = K - one_n.dot(K) - K.dot(one_n) + one_n.dot(K).dot(one_n) # Obtaining eigenpairs from the centered kernel matrix eigvals, eigvecs = eigh(K) eigvals, eigvecs = eigvals[::-1], eigvecs[:, ::-1] # Collect the top k eigenvectors (projected samples) # 修复:将生成器表达式改为列表 X_pc = np.column_stack([eigvecs[:, i] for i in range(n_components)]) return X_pc X, y = make_moons(n_samples=100, random_state=123) X_kpca = rbf_kernel_pca(X, gamma=15, n_components=2) fig, ax = plt.subplots(nrows=1,ncols=2, figsize=(7,3)) ax[0].scatter(X_kpca[y==0, 0], X_kpca[y==0, 1], color='red', marker='^', alpha=0.5) ax[0].scatter(X_kpca[y==1, 0], X_kpca[y==1, 1], color='blue', marker='o', alpha=0.5) ax[1].scatter(X_kpca[y==0, 0], np.zeros((50,1))+0.02, color='red', marker='^', alpha=0.5) ax[1].scatter(X_kpca[y==1, 0], np.zeros((50,1))-0.02, color='blue', marker='o', alpha=0.5) ax[0].set_xlabel('PC1') ax[0].set_ylabel('PC2') ax[1].set_ylim([-1, 1]) ax[1].set_yticks([]) ax[1].set_xlabel('PC1') plt.tight_layout() plt.show()
验证结果
修复后运行代码,将正常生成核PCA投影后的可视化图像,两个类别在主成分空间中实现有效分离。
内容的提问来源于stack exchange,提问作者tan hongkiat
相关产品推荐
相关产品推荐

