【機械学習】画像の0から1への分類、注目点、ピット点にはsklearnの統合学習を利用


序文

ディープラーニングの台頭後、機械学習は衰退したように見えますが、固定されたシナリオでは依然として非常に役立ちます。以下は展示ホールプロジェクトの特定タスクです。原則として、総合学習の基礎知識は少ないか、そうではありません。なぜなら、そのような記事はすでにたくさんあるからです。主にシナリオベースのビジネス問題解決を行います。


1. 需要分析

1.1 シナリオ

ここに画像の説明を挿入
額縁の中の小さな人物が水辺の左側に移動し、警察に通報します。yolovなどのターゲット検出も実現可能ですが、今度はsklearnの統合学習について学びたいと思います。そこでこの方法を採用しました。

挑戦、光の変化
ここに画像の説明を挿入

1.2 解決策

カメラは動いていないので、分類のためにこの部分を切り出すために opencv が使用されます。人には 2 種類があり、0 は誰かがいる、1 は誰もいないことを意味します。
ここに画像の説明を挿入

2. コード

2.1 特徴抽出

画像の特徴を抽出する方法はたくさんありますが、ここでは haar と lbp の 2 つの方法を紹介します。

# 提取Haar特征
def extract_haar_features(images):
    features = []

    for image in images:
        # a = 1
        # feature = cv2.HOGDescriptor().compute(image)
        feature = cv2.HOGDescriptor().compute(image).flatten()
        features.append(feature)

    return np.array(features)

# 提取lbp特征
def extract_lbp_features(images):
    features = []

    for image in images:
        # a = 1
        feature = local_binary_pattern(image, 8, 1, method='uniform').flatten()
        features.append(feature)

    return np.array(features)

2.2 分類器の構築

ここでは、デシジョン ツリー、ランダム フォレスト、KNN、SVM の 4 つの分類子を使用しました。これらは sklearn によってパッケージ化されており、呼び出しが非常に簡単であるためです。

# 构建决策树分类器
def build_decision_tree_classifier(X_train, y_train):
    clf = DecisionTreeClassifier(max_depth=5)
    clf.fit(X_train, y_train)
    return clf

# 构建随机森林分类器
def build_random_forest_classifier(X_train, y_train):
    clf = RandomForestClassifier(n_estimators=50, max_depth=3)
    clf.fit(X_train, y_train)
    return clf

# 构建KNN分类器
def build_knn_classifier(X_train, y_train):
    clf = KNeighborsClassifier(n_neighbors=10,algorithm='kd_tree')
    clf.fit(X_train, y_train)
    return clf

# 构建SVM分类器
def build_svm_classifier(X_train, y_train):
    clf = SVC(kernel='linear', C=0.025)
    clf.fit(X_train, y_train)
    return clf

2.4 統合モデル

アンサンブル モデルを構築して重みを保存すると、clf の最終予測がいくつかの分類器の投票によって形成されます。

# 构建集成模型
def build_ensemble_model(X_train, y_train):
    clfs = []

    clf1 = build_decision_tree_classifier(X_train, y_train)
    clfs.append(('dt', clf1))

    clf2 = build_random_forest_classifier(X_train, y_train)
    clfs.append(('rf', clf2))

    clf3 = build_knn_classifier(X_train, y_train)
    clfs.append(('knn', clf3))

    clf4 = build_svm_classifier(X_train, y_train)
    clfs.append(('svm', clf4))

    eclf = VotingClassifier(estimators=clfs, voting='hard')
    
    # 输出训练过程
    for clf in [clf1,clf2,clf3,clf4, eclf]:
        clf.fit(X_train, y_train)
        y_pred = clf.predict(X_test)
        acc = accuracy_score(y_test, y_pred)
        print(f'{
      
      clf.__class__.__name__} Accuracy: {
      
      acc}')

    eclf.fit(X_train, y_train)

    # 保存模型权重
    joblib.dump(eclf, target_weight_path)
    


    return eclf

2.5 トレーニング コードの合計

import cv2
import numpy as np
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier, VotingClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.svm import SVC
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
import joblib
from util_help import read_images
import os
import pickle
from skimage.feature import local_binary_pattern

model_name = "people_drown"
weight_name = model_name + ".joblib"
save_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)),"weight",model_name)
os.makedirs(save_dir,exist_ok=True)
target_weight_path = os.path.join(save_dir,weight_name)
# 提取Haar特征
def extract_haar_features(images):
    features = []

    for image in images:
        # a = 1
        # feature = cv2.HOGDescriptor().compute(image)
        feature = cv2.HOGDescriptor().compute(image).flatten()
        features.append(feature)

    return np.array(features)

# 提取Haar特征
def extract_lbp_features(images):
    features = []

    for image in images:
        # a = 1
        feature = local_binary_pattern(image, 8, 1, method='uniform').flatten()
        features.append(feature)

    return np.array(features)

# 构建决策树分类器
def build_decision_tree_classifier(X_train, y_train):
    clf = DecisionTreeClassifier(max_depth=5)
    clf.fit(X_train, y_train)
    return clf

# 构建随机森林分类器
def build_random_forest_classifier(X_train, y_train):
    clf = RandomForestClassifier(n_estimators=50, max_depth=3)
    clf.fit(X_train, y_train)
    return clf

# 构建KNN分类器
def build_knn_classifier(X_train, y_train):
    clf = KNeighborsClassifier(n_neighbors=10,algorithm='kd_tree')
    clf.fit(X_train, y_train)
    return clf

# 构建SVM分类器
def build_svm_classifier(X_train, y_train):
    clf = SVC(kernel='linear', C=0.025)
    clf.fit(X_train, y_train)
    return clf

# 构建集成模型
def build_ensemble_model(X_train, y_train):
    clfs = []

    clf1 = build_decision_tree_classifier(X_train, y_train)
    clfs.append(('dt', clf1))

    clf2 = build_random_forest_classifier(X_train, y_train)
    clfs.append(('rf', clf2))

    clf3 = build_knn_classifier(X_train, y_train)
    clfs.append(('knn', clf3))

    clf4 = build_svm_classifier(X_train, y_train)
    clfs.append(('svm', clf4))

    eclf = VotingClassifier(estimators=clfs, voting='hard')
    
    # 输出训练过程
    for clf in [clf1,clf2,clf3,clf4, eclf]:
        clf.fit(X_train, y_train)
        y_pred = clf.predict(X_test)
        acc = accuracy_score(y_test, y_pred)
        print(f'{
      
      clf.__class__.__name__} Accuracy: {
      
      acc}')

    eclf.fit(X_train, y_train)

    # 保存模型权重
    joblib.dump(eclf, target_weight_path)
    


    return eclf

# 对测试集进行预测
def predict(model, test_features):
    preds = model.predict(test_features)
    return preds

# 评估模型准确率
def evaluate(y_true, y_pred):
    acc = accuracy_score(y_true, y_pred)
    print(f'Accuracy: {
      
      acc}')

# 加载模型权重

clf = joblib.load(target_weight_path) if os.path.exists(target_weight_path)  else None

image_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)),"data","handle",model_name)
# 读取数据集
images, labels = read_images(image_dir)
print(len(images))
# 提取特征
# features = extract_haar_features(images)
features = extract_lbp_features(images)

# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(features, labels, test_size=0.25, random_state=42)

# 构建或加载集成模型
if clf is None:
    clf = build_ensemble_model(X_train, y_train)

# 对测试集进行预测
y_pred = predict(clf, X_test)

# 评估模型性能
evaluate(y_test, y_pred)

3. 高速 API カプセル化

続き、開発中です。

4. まとめ

ライト効果の場合、グレースケールに変換すると違いが生じますか?これは大きなトピックですか? つづく。
さらに、Haar を使用して特徴を抽出すると、ウェイト ファイルが恐ろしい 12G に達し、トレーニング中にメモリが爆発してしまうため、この問題により長い間作業が遅れましたが、原因は不明です。
その後、lbpに変更する方法は非常に小さく、速度は非常に高速です。

おすすめ

転載: blog.csdn.net/weixin_40293999/article/details/130523651