SVM人脸识别分类案例(机器学习)

运用sklearn自带的数据集做一个分类任务

from sklearn.datasets import fetch_lfw_people
faces = fetch_lfw_people(min_faces_per_person=60)
fig, ax = plt.subplots(3, 5)
for i, axi in enumerate(ax.flat):
    axi.imshow(faces.images[i], cmap='bone')
    axi.set(xticks=[], yticks=[],
            xlabel=faces.target_names[faces.target[i]])

打印结果:


from sklearn.svm import SVC
#from sklearn.decomposition import RandomizedPCA
from sklearn.decomposition import PCA
from sklearn.pipeline import make_pipeline

pca = PCA(n_components=150, whiten=True, random_state=42)
svc = SVC(kernel='rbf', class_weight='balanced')
model = make_pipeline(pca, svc)
from sklearn.model_selection import train_test_split
Xtrain, Xtest, ytrain, y
  • 4
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是《机器学习实战》第六章应用案例人脸识别的代码,包括数据预处理、特征提取和分类器训练等过程: ``` # 导入所需的库 import os import numpy as np from sklearn.model_selection import train_test_split from sklearn.preprocessing import LabelEncoder from sklearn.svm import SVC from sklearn.metrics import accuracy_score import cv2 # 定义数据预处理函数 def preprocess_data(data_path): images = [] labels = [] for sub_folder in os.listdir(data_path): sub_folder_path = os.path.join(data_path, sub_folder) for file_name in os.listdir(sub_folder_path): if file_name.startswith('.'): continue image_path = os.path.join(sub_folder_path, file_name) image = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE) image = cv2.resize(image, (128, 128)) images.append(np.asarray(image, dtype=np.uint8)) labels.append(sub_folder) return images, labels # 定义特征提取函数 def extract_features(images): features = [] for image in images: hist = cv2.calcHist([image], [0], None, [256], [0, 256]) features.append(hist) features = np.asarray(features) features = np.reshape(features, (features.shape[0], -1)) return features # 加载数据 data_path = 'path_to_data_folder' images, labels = preprocess_data(data_path) # 特征提取 features = extract_features(images) # 标签编码 le = LabelEncoder() labels = le.fit_transform(labels) # 划分训练集和测试集 X_train, X_test, y_train, y_test = train_test_split(features, labels, test_size=0.2, random_state=42) # 训练分类器 clf = SVC(kernel='linear', C=1.0, random_state=42) clf.fit(X_train, y_train) # 预测并计算准确率 y_pred = clf.predict(X_test) accuracy = accuracy_score(y_test, y_pred) print('Accuracy: %.2f%%' % (accuracy * 100.0)) ``` 需要注意的是,以上代码只是一个示例,请根据实际情况进行修改和调整。同时,为了让模型具有更好的性能,建议使用更多的训练数据和更复杂的特征提取和分类器模型。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值