Numpy Hstack尺寸未对齐

2024-05-14 13:10:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图运行一个PCA分析数据集代表一个图像的3个波段。数据集的大小(300000,3)是像素和3个波段,我找到了特征值和对,然后将它们放入一个名为eig_pairs的元组中。然后,我计算方差,以确定有多少波段用于主成分分析。你知道吗

我决定使用2个波段。你知道吗

我的eig_pairs形状是大小为3的元组列表。你知道吗

this tutorial之后,我说我需要重塑一切,从原来的维度空间(3)减少到每个维度的数量等于我希望使用的维度数量(2)。他们的例子是7到4,如下所示:

matrix_w = np.hstack((eig_pairs[0][1].reshape(7,1),
                      eig_pairs[1][1].reshape(7,1),
                      eig_pairs[2][1].reshape(7,1),
                      eig_pairs[3][1].reshape(7,1)))

按照这个逻辑,我把自己的想法改为:

matrix_w = np.hstack((eig_pairs0.reshape(3,1), eig_pairs1.reshape(3,1)))

但是我得到了错误ValueError: shapes (3131892,3) and (2,3) not aligned: 3 (dim 1) != 2 (dim 0)

#read in image
img = cv2.imread('/Volumes/EXTERNAL/Stitched-Photos-for-Chris/p7_0015_20161005-949am-75m-pass-1.jpg.png',1)
row,col = img.shape[:2]
b,g,r = cv2.split(img)

# Pandas dataset
# samples = 3000000, featuress = 3
dataSet = pd.DataFrame({'bBnad':b.flat[:],'gBnad':g.flat[:],'rBnad':r.flat[:]})

print(dataSet.head())
# Standardize the data
X = dataSet.values
X_std = StandardScaler().fit_transform(X) #converts data from unit8 to float64

#Calculating Eigenvectors and eigenvalues of Covariance matrix
meanVec = np.mean(X_std, axis=0)
covarianceMatx = np.cov(X_std.T)
eigVals, eigVecs = np.linalg.eig(covarianceMatx)

# Create a list of (eigenvalue, eigenvector) tuples
eig_pairs = [ (np.abs(eigVals[i]),eigVecs[:,i]) for i in range(len(eigVals))]
# Sort from high to low
eig_pairs.sort(key = lambda x: x[0], reverse= True)

# Determine how many PC going to choose for new feature subspace via
# the explained variance measure which is calculated from eigen vals
# The explained variance tells us how much information (variance) can 
# be attributed to each of the principal components
tot = sum(eigVals)
var_exp = [(i / tot)*100 for i in sorted(eigVals, reverse=True)]
cum_var_exp = np.cumsum(var_exp)

#convert 3 dimension space to 2 dimensional space therefore getting a 2x3 matrix W
matrix_w = np.hstack((eig_pairs[0][1].reshape(3,1),
                      eig_pairs[1][1].reshape(3,1)))

谢谢你的帮助。你知道吗


Tags: thetoinimgfor波段npmatrix

热门问题