我正在使用SVM进行面部表情识别,代码我使用Dlib提取面部地标并训练多类SVM分类器来识别面部表情(情绪)。
我已经训练过SVM分类器,生成的模型保存到.bin文件中。
现在我想使用这个保存的模型来预测真实图像中的表达,这意味着它将实际图像作为输入,结果它返回该图像的预测情绪。
这是我使用的代码:
def train(epochs=HYPERPARAMS.epochs, random_state=HYPERPARAMS.random_state,
kernel=HYPERPARAMS.kernel, decision_function=HYPERPARAMS.decision_function, train_model=True):
print "loading dataset " + DATASET.name + "..."
if train_model:
data, validation, test = load_data(validation=True, test=True)
else:
data, validation, test = load_data(validation=True, test=True)
if train_model:
# Training phase
print "building model..."
model = SVC(random_state=random_state, max_iter=epochs, kernel=kernel, decision_function_shape=decision_function)
print "start training..."
print "--"
print "kernel: {}".format(kernel)
print "decision function: {} ".format(decision_function)
print "max epochs: {} ".format(epochs)
print "--"
print "Training samples: {}".format(len(data['Y']))
print "Validation samples: {}".format(len(validation['Y']))
print "Test samples: {}".format(len(test['Y']))
print "--"
start_time = time.time()
model.fit(data['X'], data['Y'])
training_time = time.time() - start_time
print "training time = {0:.1f} sec".format(training_time)
if TRAINING.save_model:
print "saving model..."
with open(TRAINING.save_model_path, 'wb') as f:
cPickle.dump(model, f)
print "evaluating..."
validation_accuracy = evaluate(model, validation['X'], validation['Y'])
print " - validation accuracy = {0:.1f}".format(validation_accuracy*100)
return validation_accuracy
else:
# Testing phase : load saved model and evaluate on test dataset
print "start evaluation..."
print "loading pretrained model..."
if os.path.isfile(TRAINING.save_model_path):
with open(TRAINING.save_model_path, 'rb') as f:
model = cPickle.load(f)
else:
print "Error: file '{}' not found".format(TRAINING.save_model_path)
exit()
print "--"
print "Validation samples: {}".format(len(validation['Y']))
print "Test samples: {}".format(len(test['Y']))
print "--"
print "evaluating..."
start_time = time.time()
validation_accuracy = evaluate(model, validation['X'], validation['Y'])
print " - validation accuracy = {0:.1f}".format(validation_accuracy*100)
test_accuracy = evaluate(model, test['X'], test['Y'])
print " - test accuracy = {0:.1f}".format(test_accuracy*100)
print " - evalution time = {0:.1f} sec".format(time.time() - start_time)
return test_accuracy
def evaluate(model, X, Y):
predicted_Y = model.predict(X)
accuracy = accuracy_score(Y, predicted_Y)
return accuracy(model, X, Y):
predicted_Y = model.predict(X)
accuracy = accuracy_score(Y, predicted_Y)
return accuracy
我该怎么做?