简单创建一个认识自己的代码2:训练数据

2019年10月15号

作者:杨轮飞

将会使用到python中的opencv、dlib、sklearn库。

之前收集了数据,现在我们要来对数据处理,生成模型。

  • 先导入我们的库
import warnings
warnings.filterwarnings("ignore") #忽略警告
from os import listdir #读取图片
from sklearn.model_selection import train_test_split  #train_test_split函数
from sklearn.preprocessing import scale #去中心化
from sklearn.decomposition import PCA #PCA降维
from sklearn.svm import SVC #使用SVM多分类
from sklearn.multiclass import OneVsRestClassifier
from sklearn.externals import joblib #保存模型
import numpy as np
import cv2
  • 先写一个PCA函数,因为一张图片是64*64的大小,就会有4096维,维度太高,我们需要降至150维左右
#使用库PCA
def pca(data, n):
    pca = PCA(n_components=n)
    pca.fit(data)
    return pca.transform(data)
  • 再写一个归一化函数,将像素值从0-255归一化到0-1之间
#归一化处理
def MaxMinNormalization(x):
    xmin, xmax = np.min(x), np.max(x)
    x = (x - xmin) / (np.max(x) - xmin)
    return x
  • 我们通过访问文件夹,来一一读取图像,先将像素值归一化,然后将64*64的矩阵重新排序为一维,去中心化,然后添加入数据集。
#训练集与标签
X, Y = [], []

#载入图片路径
image_path = "face_image"
people_name = listdir(image_path)
for people in people_name:
    for image_name in listdir(image_path+"\\"+people):
        image = cv2.imread(image_path+"\\"+people+"\\"+image_name, 0)
        image = MaxMinNormalization(image)
        X.append(scale(np.array(image, np.float32).flatten().astype('float32')))
        Y.append(people)
  • 得到了我们的数据集后,接下来开始训练模型啦。
X = np.array(X)
Y = np.array(Y)
#PCA降维处理
X = pca(X, 150)
#交叉检验建立训练集和测试集
x_train, x_test, y_train, y_test = train_test_split(X, Y)
print("训练集:", x_train.shape)
print("预测集:", x_test.shape)
print('-'*70)

face_model = OneVsRestClassifier(SVC(kernel='rbf', C=1e3, gamma='scale'))
clf = face_model.fit(x_train, y_train)

print("训练集精度:", clf.score(x_train, y_train))
print("预测集精度", clf.score(x_test, y_test))
print('-'*70)

tryone = x_test[:1]
lable = y_test[:1]
result = clf.predict(tryone)
print("原标签:", lable)
print("预测标签:", result)
print('-'*70)

#保存模型
joblib.dump(clf, "face_train_model.m")
print("模型已保存:face_train_model.m")
  • 跑一遍看看我们的结果

可以看出来,结果还是非常不错的。

好了,下一步就是该打开摄像头来进行识别了~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值