face-api/src/ageGenderNet/AgeGenderNet.ts

121 lines
4.2 KiB
TypeScript
Raw Normal View History

2020-12-23 18:58:47 +01:00
import * as tf from '../../dist/tfjs.esm';
2020-08-18 13:54:53 +02:00
import { fullyConnectedLayer } from '../common/fullyConnectedLayer';
import { seperateWeightMaps } from '../faceProcessor/util';
import { TinyXception } from '../xception/TinyXception';
import { extractParams } from './extractParams';
2021-01-12 16:14:33 +01:00
import { extractParamsFromWeightMap } from './extractParamsFromWeightMap';
2021-03-19 23:46:36 +01:00
import { AgeAndGenderPrediction, Gender, NetOutput, NetParams } from './types';
2020-08-18 13:54:53 +02:00
import { NeuralNetwork } from '../NeuralNetwork';
2020-12-19 17:46:41 +01:00
import { NetInput, TNetInput, toNetInput } from '../dom/index';
2020-08-18 13:54:53 +02:00
export class AgeGenderNet extends NeuralNetwork<NetParams> {
private _faceFeatureExtractor: TinyXception
constructor(faceFeatureExtractor: TinyXception = new TinyXception(2)) {
2020-12-23 17:26:55 +01:00
super('AgeGenderNet');
this._faceFeatureExtractor = faceFeatureExtractor;
2020-08-18 13:54:53 +02:00
}
public get faceFeatureExtractor(): TinyXception {
2020-12-23 17:26:55 +01:00
return this._faceFeatureExtractor;
2020-08-18 13:54:53 +02:00
}
public runNet(input: NetInput | tf.Tensor4D): NetOutput {
2020-12-23 17:26:55 +01:00
const { params } = this;
2020-08-18 13:54:53 +02:00
if (!params) {
2020-12-23 17:26:55 +01:00
throw new Error(`${this._name} - load model before inference`);
2020-08-18 13:54:53 +02:00
}
return tf.tidy(() => {
const bottleneckFeatures = input instanceof NetInput
? this.faceFeatureExtractor.forwardInput(input)
2020-12-23 17:26:55 +01:00
: input;
2020-08-18 13:54:53 +02:00
2020-12-23 17:26:55 +01:00
const pooled = tf.avgPool(bottleneckFeatures, [7, 7], [2, 2], 'valid').as2D(bottleneckFeatures.shape[0], -1);
const age = fullyConnectedLayer(pooled, params.fc.age).as1D();
const gender = fullyConnectedLayer(pooled, params.fc.gender);
return { age, gender };
});
2020-08-18 13:54:53 +02:00
}
public forwardInput(input: NetInput | tf.Tensor4D): NetOutput {
return tf.tidy(() => {
2020-12-23 17:26:55 +01:00
const { age, gender } = this.runNet(input);
return { age, gender: tf.softmax(gender) };
});
2020-08-18 13:54:53 +02:00
}
public async forward(input: TNetInput): Promise<NetOutput> {
2020-12-23 17:26:55 +01:00
return this.forwardInput(await toNetInput(input));
2020-08-18 13:54:53 +02:00
}
public async predictAgeAndGender(input: TNetInput): Promise<AgeAndGenderPrediction | AgeAndGenderPrediction[]> {
2020-12-23 17:26:55 +01:00
const netInput = await toNetInput(input);
const out = await this.forwardInput(netInput);
2020-08-18 13:54:53 +02:00
2020-12-23 17:26:55 +01:00
const ages = tf.unstack(out.age);
const genders = tf.unstack(out.gender);
2020-08-18 13:54:53 +02:00
const ageAndGenderTensors = ages.map((ageTensor, i) => ({
ageTensor,
2020-12-23 17:26:55 +01:00
genderTensor: genders[i],
}));
2020-08-18 13:54:53 +02:00
const predictionsByBatch = await Promise.all(
ageAndGenderTensors.map(async ({ ageTensor, genderTensor }) => {
2021-03-20 02:39:45 +01:00
const age = (ageTensor.dataSync())[0];
const probMale = (genderTensor.dataSync())[0];
2020-12-23 17:26:55 +01:00
const isMale = probMale > 0.5;
const gender = isMale ? Gender.MALE : Gender.FEMALE;
const genderProbability = isMale ? probMale : (1 - probMale);
ageTensor.dispose();
genderTensor.dispose();
return { age, gender, genderProbability };
}),
);
out.age.dispose();
out.gender.dispose();
return netInput.isBatchInput ? predictionsByBatch as AgeAndGenderPrediction[] : predictionsByBatch[0] as AgeAndGenderPrediction;
2020-08-18 13:54:53 +02:00
}
protected getDefaultModelName(): string {
2020-12-23 17:26:55 +01:00
return 'age_gender_model';
2020-08-18 13:54:53 +02:00
}
2021-09-08 19:51:28 +02:00
public override dispose(throwOnRedispose = true) {
2020-12-23 17:26:55 +01:00
this.faceFeatureExtractor.dispose(throwOnRedispose);
super.dispose(throwOnRedispose);
2020-08-18 13:54:53 +02:00
}
public loadClassifierParams(weights: Float32Array) {
2020-12-23 17:26:55 +01:00
const { params, paramMappings } = this.extractClassifierParams(weights);
this._params = params;
this._paramMappings = paramMappings;
2020-08-18 13:54:53 +02:00
}
public extractClassifierParams(weights: Float32Array) {
2020-12-23 17:26:55 +01:00
return extractParams(weights);
2020-08-18 13:54:53 +02:00
}
2021-01-12 16:14:33 +01:00
protected extractParamsFromWeightMap(weightMap: tf.NamedTensorMap) {
2020-12-23 17:26:55 +01:00
const { featureExtractorMap, classifierMap } = seperateWeightMaps(weightMap);
2020-08-18 13:54:53 +02:00
2020-12-23 17:26:55 +01:00
this.faceFeatureExtractor.loadFromWeightMap(featureExtractorMap);
2020-08-18 13:54:53 +02:00
2021-01-12 16:14:33 +01:00
return extractParamsFromWeightMap(classifierMap);
2020-08-18 13:54:53 +02:00
}
protected extractParams(weights: Float32Array) {
2020-12-23 17:26:55 +01:00
const classifierWeightSize = (512 * 1 + 1) + (512 * 2 + 2);
2020-08-18 13:54:53 +02:00
2020-12-23 17:26:55 +01:00
const featureExtractorWeights = weights.slice(0, weights.length - classifierWeightSize);
const classifierWeights = weights.slice(weights.length - classifierWeightSize);
2020-08-18 13:54:53 +02:00
2020-12-23 17:26:55 +01:00
this.faceFeatureExtractor.extractWeights(featureExtractorWeights);
return this.extractClassifierParams(classifierWeights);
2020-08-18 13:54:53 +02:00
}
2020-12-23 17:26:55 +01:00
}