All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.bigml.mimir.image.featurize.CachingFeaturizer Maven / Gradle / Ivy

The newest version!
package org.bigml.mimir.image.featurize;

import java.awt.image.BufferedImage;
import java.util.Deque;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;

/**
 * A wrapper class for an ImageFeaturizer that caches the values for the last
 * several images seen, returning them if present in the rudimentary cache. Note
 * that the cache relies on the hashcode of the input value to
 * determine if the features for the image are in the cache, and is thus
 * vunerable to collision based adversarial attacks.
 *
 * @author [email protected]
 *
 */
public class CachingFeaturizer extends ImageFeaturizer {
    public CachingFeaturizer(ImageFeaturizer featurizer) {
        _featurizer = featurizer;
        _cache = new Cache();
    };

    @Override
    public int numberOfFeatures() {
        return _featurizer.numberOfFeatures();
    }

    @Override
    protected String[] featureNames() {
        return _featurizer.featureNames();
    }

    @Override
    protected double[] featuresFromImage(BufferedImage image) {
        double[] features = _cache.lookup(image);

        if (features == null) {
            features = _featurizer.featuresFromImage(image);
            _cache.add(image, features);
        }

        return features;
    }

    private class Cache {
        private Cache() {
            _cacheMap = new HashMap();
            _cacheList = new LinkedList();
        }

        private synchronized double[] lookup(Object key) {
            if (_cacheMap.containsKey(key)) {
                _cacheList.remove(key);
                _cacheList.addFirst(key);
                return _cacheMap.get(key);
            }
            else return null;
        }

        private synchronized void add(Object key, double[] values) {
            if (_cacheList.size() >= MAX_CACHE_SIZE) {
                Object last = _cacheList.removeLast();
                _cacheMap.remove(last);
            }

            _cacheList.addFirst(key);
            _cacheMap.put(key, values);
        }

        private Map _cacheMap;
        private Deque _cacheList;
    }

    private static final int MAX_CACHE_SIZE = 128;

    private ImageFeaturizer _featurizer;
    private Cache _cache;
}