把它用python改写:clear; dir=('pictures'); testdir=('testPictures'); trainingSet = imageSet(dir,'recursive'); testSet = imageSet(testdir,'recursive'); [trainingFeatures,trainingLabels,testFeatures,testLabels]=extractFeature(trainingSet,testSet); %% %训练一个svm分类器 %fitcecoc 使用1对1的方案 classifier = fitcecoc(trainingFeatures, trainingLabels); save classifier.mat classifier; % 使用测试图像的特征向量预测样本标签 predictedLabels = predict(classifier, testFeatures); %% 评估分类器 %使用没有标签的图像数据进行测试,生成一个混淆矩阵表明分类效果 confMat=confusionmat(testLabels, predictedLabels) % accuracy=(confMat(1,1)/sum(confMat(1,:))+confMat(2,2)/sum(confMat(2,:))+... % confMat(3,3)/sum(confMat(3,:))+confMat(4,4)/sum(confMat(4,:)))/4 accuracy=(confMat(1,1)/sum(confMat(1,:))+confMat(2,2)/sum(confMat(2,:))+... confMat(3,3)/sum(confMat(3,:)))/3
时间: 2024-02-01 10:17:10 浏览: 77
Python单元测试Pytest官方文档
以下是Python版的代码:
```python
import os
import numpy as np
from sklearn import svm
from sklearn.metrics import confusion_matrix
dir = 'pictures'
testdir = 'testPictures'
# 获取训练集和测试集
trainingSet = []
trainingLabels = []
testSet = []
testLabels = []
for root, dirs, files in os.walk(dir):
for file in files:
if file.endswith('.jpg'):
trainingSet.append(os.path.join(root, file))
trainingLabels.append(os.path.basename(root))
for root, dirs, files in os.walk(testdir):
for file in files:
if file.endswith('.jpg'):
testSet.append(os.path.join(root, file))
testLabels.append(os.path.basename(root))
# 提取特征
def extract_feature(data):
features = []
for item in data:
# TODO: 提取特征,这里用随机生成的特征代替
feature = np.random.rand(10)
features.append(feature)
return features
trainingFeatures = extract_feature(trainingSet)
testFeatures = extract_feature(testSet)
# 训练分类器
clf = svm.SVC(decision_function_shape='ovr')
clf.fit(trainingFeatures, trainingLabels)
# 保存分类器
from joblib import dump
dump(clf, 'classifier.joblib')
# 预测样本标签
predictedLabels = clf.predict(testFeatures)
# 评估分类器
confMat = confusion_matrix(testLabels, predictedLabels)
accuracy = (confMat[0, 0] / np.sum(confMat[0, :]) + confMat[1, 1] / np.sum(confMat[1, :]) + confMat[2, 2] / np.sum(confMat[2, :])) / 3
print('Accuracy: %.2f%%' % (accuracy * 100))
```
阅读全文