当我尝试使用KNN模型和gabor描述符进行图像分类时,总是出现此错误。我认为这与y_hat
和Ytest
之间的尺寸不匹配有关。
有人可以帮助我纠正此错误吗?
这是代码:
def build_filters3():
filters = []
ksize = 9
for theta in np.arange(0, np.pi, np.pi/12):
for lamda in np.arange(0.5, 4, 0.3) :
kern = cv2.getGaborKernel((ksize, ksize), 1.0, theta, lamda, 0.5, 0, ktype=cv2.CV_32F)
kern/= 1.5*kern.sum()
filters.append(kern)
return filters
def process(img, filters):
accum = np.zeros_like(img)
for kern in filters:
fimg = cv2.filter2D(img, cv2.CV_8UC3, kern)
np.maximum(accum, fimg, accum)
return accum
def gaborfiltersapp(f, Path):
imgg = cv2.imread(Path, 0)
feat = []
# calculating the local energy for each convolved image
for j in range(f.shape[0]):
res = process(imgg, f[j])
temp = 0
for p in range(128):
for q in range(128):
temp = temp + res[p][q] * res[p][q]
feat.append(temp)
# calculating the mean amplitude for each convolved image
for j in range(f.shape[0]):
res = process(imgg, f[j])
temp = 0
for p in range(128):
for q in range(128):
temp = temp + abs(res[p][q])
feat.append(temp)
return np.ravel(feat)
filters3 = []
filters3 = build_filters3()
filters3 = np.asarray(filters3)
nbClass = 2
Xtrain = []
Ytrain = []
Xtest = []
Ytest = []
y_hat = []
def getTrainTest(nbClass) :
Xtrain = []
Ytrain = []
Xtest = []
Ytest = []
compteur = 0
for i in range(nbClass):
print('le nombre i est :'+ str(i))
cible = zeros(nbClass)
cible[i] = 1
X = []
Y = []
for j in range(2):
ch = path+ 'ps' + str(i)+'/'+'ps'+str(i)+'_img'+str(j)+'.jpg'
GaborImage = gaborfiltersapp(filters3, ch)
Xtrain.append(GaborImage)
Ytrain.append(cible)
print('element ajoutee au data train')
GaborImageTest = gaborfiltersapp(filters3, pathtest+'ps'+str(i)+'/'+'ps'+str(i)+'_img.jpg')
Xtest.append(GaborImageTest)
Ytest.append(cible)
print('element ajoutee au data test')
return Xtrain,Ytrain,Xtest,Ytest
Xtrain,Ytrain,Xtest,Ytest = getTrainTest(nbClass)
clf = KNeighborsClassifier(algorithm='auto', leaf_size=30, metric='minkowski', metric_params=None, n_jobs=1, n_neighbors=1, p=2, weights='uniform')
clf.fit(Xtrain, Ytrain)
y_hat = clf.predict(Xtest)
print('accuracy :' + str(clf.score(Ytest , y_hat)))
这是我从上一条指令中得到的错误:
ValueError:查询数据维必须与训练数据维匹配