人脸识别K-折交叉验证的python实现

在评判分类器性能的时候,做类似LFW数据的一堆正负人脸对,使用k-fold方法输出最终的识别精度的python代码:

#coding : utf-8
import os
import sys
import csv
import numpy as np

def getAccu(score_list, begin, end, medium, tmp_thres):
    accu = 0.0
    issame = True
    counter = 0
    for i in range(begin, end):
        if i < medium:
            issame = True
        else:
            issame = False
        if (score_list[i] >= tmp_thres) == issame:
            counter += 1
    accu = counter * 1.0 / (end - begin)
    return accu

def findBestThres(k, batch, score_list):
    begin = k * batch
    end   = (k + 1) * batch
    medium = (begin + end) * 0.5
    thres_range = np.arange(0.2, 0.99, 0.01)
    best_thres = 0.0
    best_accu = 0.0
    for tmp_thres in thres_range:
        tmp_accu  = getAccu(score_list, begin, end, medium, tmp_thres)
        if tmp_accu >= best_accu:
            best_accu = tmp_accu
            best_thres = tmp_thres
    return best_thres, best_accu

def readCSV(path):
    score_list = []
    csv_file = csv.reader((open(path,'r')))
    for line in csv_file:
        score_list.append(float(line[5]))
    return score_list

def testOtherAccu(k, score_list, folds, batch, best_thres):
    counter = 0
    issame = True
    accu = 0.0
    # left 0 ~ k
    for i in range(k):
        begin = i * batch
        end = (i + 1) * batch
        medium = (begin + end) * 0.5
        for j in range(begin, end):
            if j < medium:
                issame = True
            else:
                issame = False
            if (score_list[j] >= best_thres) == issame:
                counter += 1
    for m in range(k + 1, folds):
        begin = m * batch
        end = (m + 1) * batch
        medium = (begin + end) * 0.5
        for n in range(begin, end):
            if n < medium:
                issame = True
            else:
                issame = False
            if (score_list[n] >= best_thres) == issame:
                counter += 1
    accu = counter * 1.0 / ((folds - 1) * batch)
    return accu

if __name__ == '__main__':
    # param ini
    batch = 2400
    folds = 10
    # read csv file
    score_list = readCSV('C:/Users/Administrator/Desktop/FaceOnline/kuangshi_score.csv')
    sum_accu = 0.0
    for k in range(folds):
        best_thres, best_accu = findBestThres(k, batch, score_list)
        other_accu = testOtherAccu(k, score_list, folds, batch, best_thres)
        sum_accu += other_accu
        print('k=%d, best_thres=%f, other_accu=%f\n'%(k, best_thres, other_accu))
    ave_accu = sum_accu / folds
    print('ave_accu=%f'% ave_accu)



发布了59 篇原创文章 · 获赞 57 · 访问量 7万+

猜你喜欢

转载自blog.csdn.net/xiakejiang/article/details/103613171