دوستان عزیز سلام.
در این قسمت، مطابق درخواست یکی از شما، یک مثال از نحوه ی استخراج ویژگی های pca آورده ام. ویژگی های این مثال، داده های ارقام دست نویس فارسی هدی بوده اند. شما میتونین این کد رو با هر نوع داده ی خاکستری یا باینری دیگه هم ران بزنین.
from PIL import Image
import os
from numpy import *
from pylab import *
import pca
path = “D:\\_my teaches\\nn_sstp\\Classification\\HODA_images\\”
imlist = [os.path.join(path, f) for f in os.listdir(path) if f.endswith(‘.bmp’)]
#resized_img = img.resize((40, 40))
im = array(Image.open(imlist[0]).resize((40,40))) # open one image to get size
m,n = im.shape[0:2] # get the size of the images
imnbr = len(imlist) # get the number of images
# create matrix to store all flattened images
immatrix = np.zeros([len(imlist), m*n*1])###64–>8*8*8=512
for i,f in enumerate(imlist):
im = np.array(Image.open(f).resize((m, n)))
#multi-dimensional histogram
immatrix[i] = im.flatten()
#immatrix = array([array(Image.open(im)).resize((40,40)).flatten() for im in imlist], float)
# perform PCA
V,S,immean = pca.pca(immatrix)
# show some images (mean and 7 first modes)
figure()
gray()
subplot(2,4,1)
imshow(immean.reshape(m,n))
for i in range(7):
subplot(2,4,i+2)
imshow(V[i].reshape(m,n))
show()
کد الگوریتم pca هم در فایل زیر آمده است. آنرا کپی کنید و در یک فایل بنام pca.py در کنار فایل برنامه ی بالا قرار دهید
from PIL import Image
import numpy as np
def pca(X):
# “”” Principal Component Analysis
# input: X, matrix with training data stored as flattened arrays in rows
# return: projection matrix (with important dimensions first), variance and mean.
# “””
# get dimensions
num_data,dim = X.shape
# center data
mean_X = X.mean(axis=0)
X = X – mean_X
if dim>num_data:
# PCA – compact trick used
M = np.dot(X,X.T) # covariance matrix
e,EV = np.linalg.eigh(M) # eigenvalues and eigenvectors
tmp = np.dot(X.T,EV).T # this is the compact trick
V = tmp[::-1] # reverse since last eigenvectors are the ones we want
S = np.sqrt(e)[::-1] # reverse since eigenvalues are in increasing order
for i in range(V.shape[1]):
V[:,i] /= S
else:
# PCA – SVD used
U,S,V = np.linalg.svd(X)
V = V[:num_data] # only makes sense to return the first num_data
# return the projection matrix, the variance and the mean
return V,S,mean_X