# 主成分分析（二）

``````import numpy as np
import cv2
import matplotlib.pyplot as plt

def points(start, end, step, noise, f):
n = (end - start) // step
x = np.arange(start, end, step) + np.random.rand(n) * noise
y = np.arange(start, end, step) + np.random.rand(n) * noise
z = f(x, y) + np.random.rand(n) * noise
return np.dstack((x, y, z))[0]

# 用來產生資料的平面函式
def f(x, y):
return 2 * x + y + 10

# 資料來源
data = points(0, 100, 1, 200, f)

ax = plt.axes(projection='3d')
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')
ax.set_box_aspect((1, 1, 1))
ax.scatter(data[:,0], data[:,1], data[:,2])

plt.show()
``````

``````import numpy as np
import cv2
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA

def points(start, end, step, noise, f):
n = (end - start) // step
x = np.arange(start, end, step) + np.random.rand(n) * noise
y = np.arange(start, end, step) + np.random.rand(n) * noise
z = f(x, y) + np.random.rand(n) * noise
return np.dstack((x, y, z))[0]

# 用來產生資料的平面函式
def f(x, y):
return 2 * x + y + 10

# 資料來源
data = points(0, 100, 1, 200, f)

# 降為二維
pca = PCA(n_components = 2)
transformed = pca.fit_transform(data)

plt.scatter(transformed[:,0], transformed[:,1])

plt.show()
``````

``````import numpy as np
import cv2
import matplotlib.pyplot as plt
from matplotlib.pyplot import cm

from sklearn.decomposition import PCA

pca = PCA(3)  # 將 64 維投影至 3 維
projected = pca.fit_transform(digits.data)

ax = plt.axes(projection='3d')
ax.set_xlabel('component 1')
ax.set_ylabel('component 2')
ax.set_zlabel('component 3')
ax.set_box_aspect((1, 1, 1))

p = ax.scatter(
projected[:,0], projected[:,1], projected[:,2],
c = digits.target,  # 指定標記
edgecolor = 'none',   # 無邊框
alpha = 0.5,          # 不透明度
cmap = plt.cm.get_cmap('nipy_spectral', 10) # 依標記著色
)

plt.gcf().colorbar(p) # 著色圖例

plt.show()
``````

``````import numpy as np
import cv2
import matplotlib.pyplot as plt
from matplotlib.pyplot import cm

from sklearn.decomposition import PCA

pca = PCA(2)  # 將 64 維投影至 2 維
projected = pca.fit_transform(digits.data)

plt.xlabel('component 1')
plt.ylabel('component 2')

plt.scatter(
projected[:,0], projected[:,1],
c = digits.target,    # 指定標記
edgecolor = 'none',   # 無邊框
alpha = 0.5,          # 不透明度
cmap = plt.cm.get_cmap('nipy_spectral', 10) # 依標記著色
)

plt.colorbar()

plt.show()
``````

``````from sklearn.datasets import load_digits
import numpy as np
import matplotlib.pyplot as plt

noisy = np.random.normal(digits.data, 3) # 加入高斯雜訊

plt.gray()

for i in range(10):
plt.subplot(2, 5, i + 1)
plt.imshow(noisy[i].reshape((8, 8)))

plt.show()
``````

``````from sklearn.datasets import load_digits
from sklearn.decomposition import PCA
import numpy as np
import matplotlib.pyplot as plt

noisy = np.random.normal(digits.data, 3)

pca = PCA(0.5) # 0.5 是試誤出來的 XD
transformed = pca.fit_transform(noisy)
inversed = pca.inverse_transform(transformed)

plt.gray()
for i in range(10):
plt.subplot(2, 5, i + 1)
plt.imshow(inversed[i].reshape((8, 8)))

plt.show()
``````