%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as img
from sklearn.decomposition import TruncatedSVD
import warnings
warnings.filterwarnings("ignore")
class Truncated_SVD:
def __init__(self, data, n_components):
self.data = data
self.n_components = n_components
self.shape = data.shape
def SvdResult(self):
height, width, channels = self.shape[0], self.shape[1], self.shape[2]
planes = []
for idx in range(channels):
plane = self.data[:, :, idx]
# 转成二维矩阵
plane = np.reshape(plane, (height, width))
svd = TruncatedSVD(n_components=self.n_components)
# 拟合数据,进行矩阵分解,生成特征空间,剔去无关紧要的成分
svd.fit(plane)
# 将输入数据转换到特征空间
new_plane = svd.transform(plane)
# 再将特征空间的数据转换会数据空间
plane = svd.inverse_transform(new_plane)
plane = np.clip(plane, 0, 1)
# 存起来
planes.append(plane)
img_ = np.dstack(planes)
plt.imshow(img_)
plt.show()