降维示例:图像数据
示例图片
该示例图片的数据维度为 360*460
。我们将尝试通过 PCA 和自动编码器将数据规模降低为原有的 10%。
PCA 方法
pct_reduction = 0.10 reduced_pixel = int( pct_reduction* original_dimensions[1]) #Applying PCA pca = PCA(n_components=reduced_pixel) pca.fit(image_matrix) #Transforming the input matrix X_transformed = pca.transform(image_matrix) print("Original Input dimesnions {}".format(original_dimensions)) print("New Reduced dimensions {}".format(X_transformed.shape))
输出如下:
Original Input dimesnions (360, 460) New Reduced dimensions (360, 46)
检查各维度的相关性:
df_pca = pd.DataFrame(data = X_transformed,columns=list(range(X_transformed.shape[1]))) figure = plt.figure(figsize=(10,6)) corrMatrix = df_pca.corr() sns.heatmap(corrMatrix, annot=False) plt.show()
PCA降维后各维度相关性
从上图可以看出,PCA 降维后各个维度都是不相关的,也就是完全正交。
接下来,我们通过降维后的数据来重构原始数据:
reconstructed_matrix = pca.inverse_transform(X_transformed) reconstructed_image_pca = Image.fromarray(np.uint8(reconstructed_matrix)) plt.figure(figsize=(8,12)) plt.imshow(reconstructed_image_pca,cmap = plt.cm.gray)
PCA 图像重构
计算重构后图像的均方根误差:
def my_rmse(np_arr1,np_arr2): dim = np_arr1.shape tot_loss = 0 for i in range(dim[0]): for j in range(dim[1]): tot_loss += math.pow((np_arr1[i,j] - np_arr2[i,j]),2) return round(math.sqrt(tot_loss/(dim[0]* dim[1]*1.0)),2) error_pca = my_rmse(image_matrix,reconstructed_matrix)
计算可知,均方根误差为11.84。