如何使用ANN预测HOG提取功能?

时间:2019-05-20 23:33:09

标签: python opencv machine-learning mnist

我正在使用MNIST数据集对具有猪特征提取的ANN进行手写数字分类。但是,当我通过hog函数时,出现此错误。

---> 44 X_test = calc_hog_features(X_test, pixels_per_cell=(8, 8))
     45 
     46 X_train=x_train/255

<ipython-input-38-19c269636b3b> in calc_hog_features(X, image_shape, pixels_per_cell)
     35     fd_list = []
     36     for row in X:
---> 37         img = row.reshape(image_shape)
     38         fd = hog(img, orientations=8, pixels_per_cell=pixels_per_cell, cells_per_block=(1, 1))
     39         fd_list.append(fd)

ValueError: cannot reshape array of size 72 into shape (28,28)

产生上述错误的完整代码如下。

import numpy as np # linear algebra
import pandas as pd
from skimage.feature import hog
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
import mlxtend
from mlxtend.data import loadlocal_mnist
from keras.utils import np_utils
from keras.datasets import mnist
(X_train,y_train),(X_test,y_test)=mnist.load_data()

img_rows=X_train[0].shape[0]
img_cols=X_train[1].shape[0]

X_train=X_train.reshape(x_train.shape[0],img_rows,img_cols,1)
X_test=X_test.reshape(x_test.shape[0],img_rows,img_cols,1)
#Store single image shape
input_shape=(img_rows,img_cols,1)

X_train=X_train.astype('float32')
X_test=x_test.astype('float32')


def calc_hog_features(X, image_shape=(28, 28), pixels_per_cell=(8, 8)):
    fd_list = []
    for row in X:
        img = row.reshape(image_shape)
        fd = hog(img, orientations=8, pixels_per_cell=pixels_per_cell, cells_per_block=(1, 1))
        fd_list.append(fd)

    return np.array(fd_list)

X_train = calc_hog_features(X_train, pixels_per_cell=(8, 8))
X_test = calc_hog_features(X_test, pixels_per_cell=(8, 8))

X_train=x_train/255
X_test=x_test/255



y_train=np_utils.to_categorical(y_train)
y_test=np_utils.to_categorical(y_test)

from sklearn.naive_bayes import GaussianNB
from sklearn.model_selection import cross_val_score
from sklearn.metrics import accuracy_score, roc_curve
from sklearn.preprocessing import normalize

from keras.models import Sequential
from keras.layers import Dense, Dropout
from keras.wrappers.scikit_learn import KerasClassifier

num_pixels=x_train.shape[1]*x_train.shape[2]

model=Sequential()
model.add(Conv2D(32,kernel_size=(3,3),activation='relu',input_shape=input_shape))
model.add(Conv2D(64,(3,3),activation='relu'))

model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(128,activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(num_classes,activation='softmax'))
model.compile(loss='categorical_crossentropy',optimizer=SGD(0.01),metrics=['accuracy'])
print(model.summary())

我使用了相同的代码进行预测,而没有使用CNN的生猪功能,因此代码运行完美。

关于如何解决此错误的任何建议?

0 个答案:

没有答案