数据分析与挖掘(一):数据预处理环节的数据降维方法以及应用
一、 实验目的:
数据预处理环节的数据降维方法以及应用
二、实验设备(环境)及要求
Jupyter notebook、百度 AI studio
三、实验内容
1.降维处理-PCA算法应用
(1) 算法实施基本步骤
- 基于sklearn和numpy随机生成2个类别共40个3维空间的样本点。
mu_vec1 =np.array([0,0,0])
cov_mat1= np.array([[1,0,0],[0,1,0],[0,0,1]])
class1_sample= np.random.multivariate_normal(mu_vec1, cov_mat1, 20).T
mu_vec2= np.array([1,1,1])
cov_mat2= np.array([[1,0,0],[0,1,0],[0,0,1]])
class2_sample= np.random.multivariate_normal(mu_vec2, cov_mat2, 20).T
- 生成的两个类别class1_sample和class2_sample的样本数据维度为3维,即样本数据的特征数量为3个,将其置于3维空间中展示。
ax = plt.subplot(projection='3d')
ax.scatter(class1_sample[0], class1_sample[1], class1_sample[2])
ax.scatter(class2_sample[0], class2_sample[1], class2_sample[2])
- 计算40个点在3个维度上的平均向量。
all_samples = np.concatenate((class1_sample, class2_sample), axis=1)
mean_x = np.mean(all_samples[0,:])
mean_y = np.mean(all_samples[1,:])
mean_z = np.mean(all_samples[2,:])
mean_vector = np.array([[mean_x],[mean_y],[mean_z]])
- 所有向量经过平均向量,计算散步矩阵值。
scatter_matrix = np.zeros((3,3))
for i in range(all_samples.shape[1]):
scatter_matrix += (all_samples[:,i].reshape(3,1) - mean_vector).dot((all_samples[:,i].reshape(3,1) - mean_vector).T)
print('Scatter Matrix:\n', scatter_matrix)
sample_x =all_samples[0,:]
sample_y =all_samples[1,:]
sample_z =all_samples[2,:]
- 用python里内置的numpy.cov()函数直接计算协方差矩阵。
cov_mat = np.cov([all_samples[0,:],all_samples[1,:],all_samples[2,:]])
print('Covariance Matrix:\n', cov_mat)
- 使用np.linalg.eig(scatter_matrix)计算特征向量和特征值。
eig_val_sc, eig_vec_sc = np.linalg.eig(scatter_matrix)
eig_val_cov, eig_vec_cov = np.linalg.eig(cov_mat)
- 按照特征向量和特征值进行配对,按照特征值从大到小排序,选择前两个特征值、特征向量作为坐标构建矩阵。
for i in range(len(eig_val_sc)):
eigvec_sc = eig_vec_sc[:,i].reshape(1,3).T
eigvec_cov = eig_vec_cov[:,i].reshape(1,3).T
assert eigvec_sc.all() == eigvec_cov.all(), 'Eigenvectors are not identical'
- 可视化特征向量
ax.plot(all_samples[0,:],all_samples[1,:], all_samples[2,:], 'o', markersize=8, color='green', alpha=0.2)
ax.plot([mean_x], [mean_y], [mean_z], 'o', markersize=10, color='red', alpha=0.5)
for v in eig_vec_sc.T:
a=Arrow3D([mean_x,v[0]],[mean_y,v[1]],[mean_z,v[2]],mutation_scale=20,lw=3,arrowstyle="-|>", color="r")
ax.add_artist(a)
- 根据特征值对特征向量降序排列。
eig_pairs = [(np.abs(eig_val_sc[i]), eig_vec_sc[:,i]) for i in range(len(eig_val_sc))]
eig_pairs.sort(key=lambda x: x[0], reverse=True)
- 选出前k个特征值最大的特征向量。
matrix_w = np.hstack((eig_pairs[0][1].reshape(3,1), eig_pairs[1][1].reshape(3,1)))
print('Matrix W:\n', matrix_w)
- 将样本转化为新的特征空间。
plt.plot(transformed[0,0:20], transformed[1,0:20], 'o', markersize=7, color='blue', alpha=0.5, label='class1')
plt.plot(transformed[0,20:40], transformed[1,20:40], '^', markersize=7, color='red', alpha=0.5, label='class2')
plt.xlim([-4,4])
plt.ylim([-4,4])
plt.xlabel('x_values')
plt.ylabel('y_values')
plt.legend()
plt.title('Transformed samples with class labels')
(2) 运行
(3) 结果查看与分析
建立一个有四十个点的随机三维数据,然后计算他们的三维向量和向量均量,之后计算散布矩阵和协方差矩阵,通过散布矩阵和协方差矩阵计算相应的特征向量和特征值,最后进行特征向量的可视化并且将样本转化为新的特征空间。
2.降维处理-LDA算法应用
(1) 算法实施基本步骤
- 计算数据集中每个类别下所有样本的均值向量
def comp_mean_vectors(X, y):
class_labels = np.unique(y)
n_classes = class_labels.shape[0]
mean_vectors = []
for cl in class_labels:
mean_vectors.append(np.mean(X[y==cl], axis=0))
return mean_vectors
- 通过均值向量,计算类间散布矩阵和类内散布矩阵
def scatter_within(X, y):
class_labels = np.unique(y)
n_classes = class_labels.shape[0]
n_features = X.shape[1]
mean_vectors = comp_mean_vectors(X, y)
S_W = np.zeros((n_features, n_features))
for cl, mv in zip(class_labels, mean_vectors):
class_sc_mat = np.zeros((n_features, n_features))
for row in X[y == cl]:
row, mv = row.reshape(n_features, 1), mv.reshape(n_features, 1)
class_sc_mat += (row-mv).dot((row-mv).T)
S_W += class_sc_mat
return S_W
- 依据公式进行特征值求解,计算的特征向量和特征值
eig_vals, eig_vecs = np.linalg.eig(np.linalg.inv(S_W).dot(S_B))
- 按照特征值排序, 选择前k个特征向量构成投影矩阵U
def get_components(eig_vals, eig_vecs, n_comp=1):
n_features = X.shape[1]
eig_pairs = [(np.abs(eig_vals[i]), eig_vecs[:,i]) for i in range(len(eig_vals))]
eig_pairs = sorted(eig_pairs, key=lambda k: k[0], reverse=True)
print("eig_pairs:",eig_pairs)
W = np.hstack([eig_pairs[i][1].reshape(4, 1) for i in range(0, n_comp)])
return W
- 通过的特征值矩阵将所有样本转换到新的子空间中
plt.xlabel('LD1')
plt.ylabel('LD2')
X_lda = X.dot(W)
for label,marker,color in zip(np.unique(y),('o', '^', 's'),('red', 'green', 'blue')):
plt.scatter(X_lda[y==label,0],X_lda[y==label,1],c=color,edgecolors='black',marker=marker,s=640)
plt.show()
(2) 运行
(3) 结果查看与分析
先计算没类样本的均值,之后计算散布矩阵和类散布矩阵,然后计算特征值和特征向量,并且检查是否满足公式Av=λv,之后按照特征值排序,选择一定量的特征向量构建矩阵,最后通过矩阵将样本转换到新的空间中并可视化。