1. ホーム

ターゲットチェック時のエラー: activation_4 の形状が (1,) であることを期待したが、形状 (3,) の配列を得た。

2022-02-23 08:53:33
<パス

from dataSet import DataSet
from keras.models import Sequential,load_model
from keras.layers import Dense,Activation,Convolution2D,MaxPooling2D,Flatten,Dropout(ドロップアウト)
numpyをnpとしてインポートする

CNNベースの顔認識モデルの構築

クラス Model(object)。
FILE_PATH = "E:\picmodel.h5" # モデルの格納場所と読み込み場所
IMAGE_SIZE = 128 #モデルが受け入れる顔画像は128*128である必要があります。

def __init__(self):
    self.model = None

# read the instantiated DataSet class as the data source for training
def read_trainData(self,dataset):
    self.dataset = dataset

# Build a CNN model, one layer of convolution, one layer of pooling, one layer of convolution, one layer of pooling, full linkage after smoothing, and finally classification
def build_model(self):
    self.model = Sequential()
    self.model.add(
        Convolution2D(
            filters=32,
            kernel_size=(5, 5),
            padding='same',
            dim_ordering='th',
            input_shape=self.dataset.X_train.shape[1:]
        )
    )

    self.model.add(Activation('relu'))
    self.model.add(
        MaxPooling2D(
            pool_size=(2, 2),
            strides=(2, 2),
            padding='same'
        )
    )


    self.model.add(Convolution2D(filters=64, kernel_size=(5, 5), padding='same'))
    self.model.add(Activation('relu'))
    self.model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2), padding='same'))

    self.model.add(Flatten())
    self.model.add(Dense(512))
    self.model.add(Activation('relu'))


    self.model.add(Dense(self.dataset.num_classes))
    self.model.add(Activation('softmax'))
    self.model.summary()

# the function to train the model, the specific optimizer, loss can be selected differently
def train_model(self):
    self.model.compile(
        optimizer='adam', # there are many optional optimizer, such as RMSprop, Adagrad, you can also try which is good, I personally feel that the difference is not large
        loss='sparse_categorical_crossentropy', # you can choose squared_hinge as the loss to see which is better
        metrics=['accuracy'])

    #epochs, batch_size are adjustable parameters, epochs is the number of training rounds, batch_size is the number of samples trained each time
    self.model.fit(self.dataset.X_train,self.dataset.Y_train,epochs=7,batch_size=20)

def evaluate_model(self):
    print('\nTesting---------------')
    loss, accuracy = self.model.evaluate(self.dataset.X_test, self.dataset.Y_test)

    print('test loss;', loss)
    print('test accuracy:', accuracy)

def save(self, file_path=FILE_PATH):
    print('Model Saved.')
    self.model.save(file_path)

def load(self, file_path=FILE_PATH):
    print('Model Loaded.')
    self.model = load_model(file_path)

# need to ensure that the input img must be grayed out (channel =1 ) and the size of the IMAGE_SIZE face image
def predict(self,img):
    img = img.reshape((1, 1, self.IMAGE_SIZE, self.IMAGE_SIZE))
    img = img.astype('float32')
    img = img/255.0

    result = self.model.predict_proba(img) # measure the probability that the img belongs to a label
    max_index = np.argmax(result) #find the highest probability

    return max_index,result[0][max_index] #The first parameter is the index of the label with the highest probability, and the second parameter is the corresponding probability


もし 名前 == ' メイン ':
dataset = DataSet('E:\workPIC╱dataset')
model = モデル()
model.read_trainData(データセット)
model.build_model()
model.train_model()
model.evaluate_model()
model.save()