[英]Error - Calculating Euclidean distance for PCA in python
我正在尝试使用主要组件分析(PCA)使用python实现面部识别。 我按照本教程中的步骤操作: http : //onionesquereality.wordpress.com/2009/02/11/face-recognition-using-eigenfaces-and-distance-classifiers-a-tutorial/
这是我的代码:
import os
from PIL import Image
import numpy as np
import glob
import numpy.linalg as linalg
#Step1: put database images into a 2D array
filenames = glob.glob('C:\\Users\\Karim\\Downloads\\att_faces\\New folder/*.pgm')
filenames.sort()
img = [Image.open(fn).convert('L').resize((90, 90)) for fn in filenames]
images = np.asarray([np.array(im).flatten() for im in img])
#Step 2: find the mean image and the mean-shifted input images
mean_image = images.mean(axis=0)
shifted_images = images - mean_image
#Step 3: Covariance
c = np.cov(shifted_images)
#Step 4: Sorted eigenvalues and eigenvectors
eigenvalues,eigenvectors = linalg.eig(c)
idx = np.argsort(-eigenvalues)
eigenvalues = eigenvalues[idx]
eigenvectors = eigenvectors[:, idx]
#Step 5: Only keep the top 'num_eigenfaces' eigenvectors
num_components = 20
eigenvalues = eigenvalues[0:num_components].copy()
eigenvectors = eigenvectors[:, 0:num_components].copy()
#Step 6: Finding weights
w = eigenvectors.T * np.asmatrix(shifted_images)
#Step 7: Input image
input_image = Image.open('C:\\Users\\Karim\\Downloads\\att_faces\\1.pgm').convert('L').resize((90, 90))
input_image = np.asarray(input_image).flatten()
#Step 8: get the normalized image, covariance, eigenvalues and eigenvectors for input image
shifted_in = input_image - mean_image
c = np.cov(input_image)
cmat = c.reshape(1,1)
eigenvalues_in, eigenvectors_in = linalg.eig(cmat)
#Step 9: Fing weights of input image
w_in = eigenvectors_in.T * np.asmatrix(shifted_in)
print w_in
print w_in.shape
#Step 10: Euclidean distance
d = np.sqrt(np.sum((w - w_in)**2))
idx = np.argmin(d)
match = images[idx]
我在步骤10中遇到问题,因为我收到此错误: Traceback (most recent call last): File "C:/Users/Karim/Desktop/Bachelor 2/New folder/new3.py", line 59, in <module> d = np.sqrt(np.sum((w - w_in)**2)) File "C:\\Python27\\lib\\site-packages\\numpy\\matrixlib\\defmatrix.py", line 343, in __pow__ return matrix_power(self, other) File "C:\\Python27\\lib\\site-packages\\numpy\\matrixlib\\defmatrix.py", line 160, in matrix_power raise ValueError("input must be a square array") ValueError: input must be a square array
有谁可以帮忙?
我想你想把你计算d
的行改成这样的东西:
#Step 10: Euclidean distance
d = np.sqrt(np.sum(np.asarray(w - w_in)**2, axis=1)
这将为您提供每个图像像素之间的平方,求和的根距离的长度M
(训练图像的数量)的列表。 我相信你不需要矩阵乘积,你想要每个值的元素方形,因此np.asarray
使它不是矩阵。 这为您提供了w_in
和每个w
矩阵之间的“欧几里德”差异。
当你去(w - w_in)
,结果不是方阵。 要将矩阵乘以它自己,它必须是正方形(这只是矩阵乘法的一个属性)。 因此,无论你已经构建了您的w
和w_in
矩阵错了,还是你真正的意思做的是方形矩阵中的每个元素(w - w_in)
这是一个不同的操作。 搜索逐元素乘法以查找numpy语法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.