• 高维数据降维(机器学习)


    目录

    一、实验内容

    二、实验过程

    1、算法思想

    2、算法原理

    3、算法分析

    三、源程序代码

    四、运行结果及分析

    五、实验总结


    一、实验内容


    1. 熟知高维数据降维的概念和基本算法思想;
    2. 掌握高维数据降维算法的算法原理;
    3. 掌握高维数据降维算法的设计及Python实现。

    二、实验过程


    1、算法思想


    高维数据降维是指采用某种映射方法,降低随机变量的数量。例如将数据点从高维空间映射到低维空间中,从而实现维度减少

    降维分为:特征选择 和 特征提取

    特征选择:是从含有冗余信息以及噪声信息的数据中找出主要变量

    特征提取:是去掉原来的数据,生成新的变量可以寻找数据内部的本质结构特征。

    2、算法原理


    降维的过程是通过对输入的原始数据特征进行学习,得到一个映射函数,实现将输入样本映射后到低维空间中之后,原始数据特征并没有明显的损失。

    通常情况下新空间的维度要小于原空间的维度。目前大部分降维算法是处理向量形式的数据。

    3、算法分析


    1.将原始数据进行标准化(一般是去均值化,如果特征在不同的数量级上,则还要将其除以标准差)

    2.计算标准化数据集的协方差矩阵

    3.计算协方差矩阵的特征值和特征向量

    4.保留最重要(特征值最大)的前k个特征(k就表示降维后的维度)

    5.找到这k个特征值对应的特征向量

    6.将标准化数据集乘以该k个特征向量,得到降维后的结果

    三、源程序代码


    1. import numpy as np
    2. from matplotlib import pyplot as plt
    3. from mpl_toolkits.mplot3d import Axes3D
    4. from mpl_toolkits.mplot3d import proj3d
    5. from matplotlib.patches import FancyArrowPatch
    6. plt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签
    7. plt.rcParams['axes.unicode_minus']=False #用来正常显示负号
    8. np.random.seed(1) # random seed for consistency
    9. mu_vec1 = np.array([0,0,0])
    10. cov_mat1 = np.array([[1,0,0],[0,1,0],[0,0,1]])
    11. class1_sample = np.random.multivariate_normal(mu_vec1, cov_mat1, 20).T
    12. mu_vec2 = np.array([1,1,1])
    13. cov_mat2 = np.array([[1,0,0],[0,1,0],[0,0,1]])
    14. class2_sample = np.random.multivariate_normal(mu_vec2, cov_mat2, 20).T
    15. fig = plt.figure(figsize=(8,8))
    16. ax = fig.add_subplot(111, projection='3d')
    17. plt.rcParams['legend.fontsize'] = 10
    18. ax.plot(class1_sample[0,:], class1_sample[1,:], class1_sample[2,:], 'o', markersize=8, color='blue', alpha=0.5, label='class1')
    19. ax.plot(class2_sample[0,:], class2_sample[1,:], class2_sample[2,:], '^', markersize=8, alpha=0.5, color='red', label='class2')
    20. plt.title('class1 and class2 ')
    21. ax.legend(loc='upper right')
    22. plt.show()
    23. all_samples = np.concatenate((class1_sample, class2_sample), axis=1)
    24. mean_x = np.mean(all_samples[0,:])
    25. mean_y = np.mean(all_samples[1,:])
    26. mean_z = np.mean(all_samples[2,:])
    27. mean_vector = np.array([[mean_x],[mean_y],[mean_z]])
    28. print('Mean Vector:\n', mean_vector)
    29. scatter_matrix = np.zeros((3,3))
    30. for i in range(all_samples.shape[1]):
    31. scatter_matrix += (all_samples[:,i].reshape(3,1) - mean_vector).dot((all_samples[:,i].reshape(3,1) - mean_vector).T)
    32. print('Scatter Matrix:\n', scatter_matrix)
    33. sample_x =all_samples[0,:]
    34. sample_y =all_samples[1,:]
    35. sample_z =all_samples[2,:]
    36. cov_mat = np.cov([sample_x,sample_y,sample_z])
    37. print('Covariance Matrix:\n', cov_mat)
    38. # eigenvectors and eigenvalues for the from the scatter matrix
    39. eig_val_sc, eig_vec_sc = np.linalg.eig(scatter_matrix)
    40. # eigenvectors and eigenvalues for the from the covariance matrix
    41. eig_val_cov, eig_vec_cov = np.linalg.eig(cov_mat)
    42. #print("eig_val_cov:",eig_val_cov)
    43. print("eig_vec_sc:",eig_vec_sc)
    44. print("eig_val_sc",eig_val_sc)
    45. for i in range(len(eig_val_sc)):
    46. eigvec_sc = eig_vec_sc[:,i].reshape(1,3).T
    47. eigvec_cov = eig_vec_cov[:,i].reshape(1,3).T
    48. assert eigvec_sc.all() == eigvec_cov.all(), 'Eigenvectors are not identical'
    49. print('Eigenvector {}: \n{}'.format(i+1, eigvec_sc))
    50. print('Eigenvalue {} from scatter matrix: {}'.format(i+1, eig_val_sc[i]))
    51. print('Eigenvalue {} from covariance matrix: {}'.format(i+1, eig_val_cov[i]))
    52. print('Scaling factor: ', eig_val_sc[i]/eig_val_cov[i])
    53. print(40 * '-')
    54. for i in range(len(eig_val_sc)):
    55. eigv = eig_vec_sc[:,i].reshape(1,3).T
    56. np.testing.assert_array_almost_equal(scatter_matrix.dot(eigv), eig_val_sc[i] * eigv,
    57. decimal=6, err_msg='', verbose=True)
    58. class Arrow3D(FancyArrowPatch):
    59. def __init__(self, xs, ys, zs, *args, **kwargs):
    60. FancyArrowPatch.__init__(self, (0,0), (0,0), *args, **kwargs)
    61. self._verts3d = xs, ys, zs
    62. def draw(self, renderer):
    63. xs3d, ys3d, zs3d = self._verts3d
    64. xs, ys, zs = proj3d.proj_transform(xs3d, ys3d, zs3d, renderer.M)
    65. self.set_positions((xs[0],ys[0]),(xs[1],ys[1]))
    66. FancyArrowPatch.draw(self, renderer)
    67. fig = plt.figure(figsize=(7,7))
    68. ax = fig.add_subplot(111, projection='3d')
    69. ax.plot(class1_sample[0,:], class1_sample[1,:], class1_sample[2,:], 'o', markersize=8, color='blue', alpha=0.5, label='class1')
    70. ax.plot(class2_sample[0,:], class2_sample[1,:], class2_sample[2,:], '^', markersize=8, alpha=0.5, color='red', label='class2')
    71. print(mean_x)
    72. ax.plot([mean_x], [mean_y], [mean_z], 'o', markersize=10, color='red', alpha=0.9)
    73. # for v in eig_vec_sc.T:
    74. # a = Arrow3D([mean_x, v[0]], [mean_y, v[1]], [mean_z, v[2]], mutation_scale=20, lw=3, arrowstyle="-|>", color="r")
    75. # ax.add_artist(a)
    76. ax.set_xlabel('x_values')
    77. ax.set_ylabel('y_values')
    78. ax.set_zlabel('z_values')
    79. #plt.title("特征向量可视化")
    80. plt.show()
    81. eig_pairs = [(np.abs(eig_val_sc[i]), eig_vec_sc[:,i]) for i in range(len(eig_val_sc))]
    82. print("eig_pairs:",eig_pairs)
    83. # Sort the (eigenvalue, eigenvector) tuples from high to low
    84. eig_pairs.sort(key=lambda x: x[0], reverse=True)
    85. # Visually confirm that the list is correctly sorted by decreasing eigenvalues
    86. for i in eig_pairs:
    87. print(i[0])
    88. matrix_w = np.hstack((eig_pairs[0][1].reshape(3,1), eig_pairs[1][1].reshape(3,1)))
    89. print('Matrix W:\n', matrix_w)
    90. transformed = matrix_w.T.dot(all_samples)
    91. plt.plot(transformed[0,0:20], transformed[1,0:20], 'o', markersize=7, color='blue', alpha=0.5, label='class1')
    92. plt.plot(transformed[0,20:40], transformed[1,20:40], '^', markersize=7, color='red', alpha=0.5, label='class2')
    93. plt.xlim([-4,4])
    94. plt.ylim([-4,4])
    95. plt.xlabel('x_values')
    96. plt.ylabel('y_values')
    97. plt.legend()
    98. plt.show()

    四、运行结果及分析


     

    五、实验总结


            数据降维可以降低模型的计算量并减少模型运行时间、降低噪音对于模型结果的影响、便于通过可视化方式展示归约后的维度信息并减少数据存储空间。

            因此,大多数情况下,当我们面临高维数据时,都需要对数据做降维处理。

  • 相关阅读:
    初识Java 13-2 异常
    java String.format使用 %d
    三种方式循环获取水仙花数
    【PAT甲级】1016 Phone Bills
    微服务系列之单体架构
    【报表实战篇】格间计算性能提升方案
    RPC框架核心技术
    Oracle中instr,rtrim,XMLPARSE,XMLAGG,GETCLOBVAL函数的使用
    AI创作系统ChatGPT网站源码+支持最新GPT-Turbo模型+支持DALL-E3文生图/AI绘画源码
    红队隧道应用篇之Netsh端口转发
  • 原文地址:https://blog.csdn.net/qq_50942093/article/details/127113465