[关闭]
@zsh-o 2019-12-27T22:34:25.000000Z 字数 912 阅读 922

PCA 只有代码

机器学习


  1. %matplotlib inline
  2. import numpy as np
  3. import scipy
  4. from matplotlib import pyplot as plt
  1. points = np.random.randn(50, 2)
  1. plt.scatter(points[:, 0], points[:, 1])
<matplotlib.collections.PathCollection at 0x7f378f2f7f50>

![png](output_3_1.png)

  1. cov = np.cov(points.T)
  2. cov.shape
(2, 2)
  1. w, v = np.linalg.eig(cov)
  2. w, v
(array([0.95331384, 0.82559234]), array([[ 0.99782635, -0.06589818],
        [ 0.06589818,  0.99782635]]))
  1. y_axis = v[np.argmax(w)]
  2. x_axis = v[np.argmin(w)]
  3. y_axis, x_axis
(array([ 0.99782635, -0.06589818]), array([0.06589818, 0.99782635]))
  1. x = np.dot(points, x_axis)
  2. y = np.dot(points, y_axis)
  1. x1 = np.dot(x.reshape(-1, 1), x_axis.reshape(1, -1))
  2. y1 = np.dot(y.reshape(-1, 1), y_axis.reshape(1, -1))
  1. l = np.linspace(-1, 1)
  1. lx = np.dot(l.reshape(-1, 1), x_axis.reshape(1, -1))
  2. ly = np.dot(l.reshape(-1, 1), y_axis.reshape(1, -1))
  1. plt.scatter(points[:, 0], points[:, 1])
  2. plt.scatter(x1[:, 0], x1[:, 1])
  3. plt.scatter(y1[:, 0], y1[:, 1])
  4. plt.plot(lx[:, 0], lx[:, 1])
  5. plt.plot(ly[:, 0], ly[:, 1])
[<matplotlib.lines.Line2D at 0x7f378f2a79d0>]

output_11_1.png-9.6kB

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注