/* * Copyright (C) 2011 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.bordeaux.learning; import android.util.Log; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.ConcurrentHashMap; /** * A histogram based predictor which records co-occurrences of applations with a speficic * feature, for example, location, * time of day, etc. The histogram is kept in a two level * hash table. The first level key is the feature value and the second level key is the app * id. */ // TODOS: // 1. Use forgetting factor to downweight istances propotional to the time // 2. Different features could have different weights on prediction scores. // 3. Add function to remove sampleid (i.e. remove apps that are uninstalled). public class HistogramPredictor { final static String TAG = "HistogramPredictor"; private HashMap mPredictor = new HashMap(); private HashMap mClassCounts = new HashMap(); private HashSet mBlacklist = new HashSet(); private static final int MINIMAL_FEATURE_VALUE_COUNTS = 5; private static final int MINIMAL_APP_APPEARANCE_COUNTS = 5; // This parameter ranges from 0 to 1 which determines the effect of app prior. // When it is set to 0, app prior means completely neglected. When it is set to 1 // the predictor is a standard naive bayes model. private static final int PRIOR_K_VALUE = 1; private static final String[] APP_BLACKLIST = { "com.android.contacts", "com.android.chrome", "com.android.providers.downloads.ui", "com.android.settings", "com.android.vending", "com.android.mms", "com.google.android.gm", "com.google.android.gallery3d", "com.google.android.apps.googlevoice", }; public HistogramPredictor(String[] blackList) { for (String appName : blackList) { mBlacklist.add(appName); } } /* * This class keeps the histogram counts for each feature and provide the * joint probabilities of . */ private class HistogramCounter { private HashMap > mCounter = new HashMap >(); public HistogramCounter() { mCounter.clear(); } public void setCounter(HashMap > counter) { resetCounter(); mCounter.putAll(counter); } public void resetCounter() { mCounter.clear(); } public void addSample(String className, String featureValue) { HashMap classCounts; if (!mCounter.containsKey(featureValue)) { classCounts = new HashMap(); mCounter.put(featureValue, classCounts); } else { classCounts = mCounter.get(featureValue); } int count = (classCounts.containsKey(className)) ? classCounts.get(className) + 1 : 1; classCounts.put(className, count); } public HashMap getClassScores(String featureValue) { HashMap classScores = new HashMap(); if (mCounter.containsKey(featureValue)) { int totalCount = 0; for(Map.Entry entry : mCounter.get(featureValue).entrySet()) { String app = entry.getKey(); int count = entry.getValue(); // For apps with counts less than or equal to one, we treated // those as having count one. Hence their score, i.e. log(count) // would be zero. classScroes stores only apps with non-zero scores. // Note that totalCount also neglect app with single occurrence. if (count > 1) { double score = Math.log((double) count); classScores.put(app, score); totalCount += count; } } if (totalCount < MINIMAL_FEATURE_VALUE_COUNTS) { classScores.clear(); } } return classScores; } public byte[] getModel() { try { ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); ObjectOutputStream objStream = new ObjectOutputStream(byteStream); synchronized(mCounter) { objStream.writeObject(mCounter); } byte[] bytes = byteStream.toByteArray(); return bytes; } catch (IOException e) { throw new RuntimeException("Can't get model"); } } public boolean setModel(final byte[] modelData) { mCounter.clear(); HashMap > model; try { ByteArrayInputStream input = new ByteArrayInputStream(modelData); ObjectInputStream objStream = new ObjectInputStream(input); model = (HashMap >) objStream.readObject(); } catch (IOException e) { throw new RuntimeException("Can't load model"); } catch (ClassNotFoundException e) { throw new RuntimeException("Learning class not found"); } synchronized(mCounter) { mCounter.putAll(model); } return true; } public HashMap > getCounter() { return mCounter; } public String toString() { String result = ""; for (Map.Entry > entry : mCounter.entrySet()) { result += "{ " + entry.getKey() + " : " + entry.getValue().toString() + " }"; } return result; } } /* * Given a map of feature name -value pairs returns topK mostly likely apps to * be launched with corresponding likelihoods. If topK is set zero, it will return * the whole list. */ public List > findTopClasses(Map features, int topK) { // Most sophisticated function in this class HashMap appScores = new HashMap(); int validFeatureCount = 0; // compute all app scores for (Map.Entry entry : mPredictor.entrySet()) { String featureName = entry.getKey(); HistogramCounter counter = entry.getValue(); if (features.containsKey(featureName)) { String featureValue = features.get(featureName); HashMap scoreMap = counter.getClassScores(featureValue); if (scoreMap.isEmpty()) { continue; } validFeatureCount++; for (Map.Entry item : scoreMap.entrySet()) { String appName = item.getKey(); double appScore = item.getValue(); if (appScores.containsKey(appName)) { appScore += appScores.get(appName); } appScores.put(appName, appScore); } } } HashMap appCandidates = new HashMap(); for (Map.Entry entry : appScores.entrySet()) { String appName = entry.getKey(); if (mBlacklist.contains(appName)) { Log.i(TAG, appName + " is in blacklist"); continue; } if (!mClassCounts.containsKey(appName)) { throw new RuntimeException("class count error!"); } int appCount = mClassCounts.get(appName); if (appCount < MINIMAL_APP_APPEARANCE_COUNTS) { Log.i(TAG, appName + " doesn't have enough counts"); continue; } double appScore = entry.getValue(); double appPrior = Math.log((double) appCount); appCandidates.put(appName, appScore - appPrior * (validFeatureCount - PRIOR_K_VALUE)); } // sort app scores List > appList = new ArrayList >(appCandidates.size()); appList.addAll(appCandidates.entrySet()); Collections.sort(appList, new Comparator >() { public int compare(Map.Entry o1, Map.Entry o2) { return o2.getValue().compareTo(o1.getValue()); } }); if (topK == 0) { topK = appList.size(); } return appList.subList(0, Math.min(topK, appList.size())); } /* * Add a new observation of given sample id and features to the histograms */ public void addSample(String sampleId, Map features) { for (Map.Entry entry : features.entrySet()) { String featureName = entry.getKey(); String featureValue = entry.getValue(); useFeature(featureName); HistogramCounter counter = mPredictor.get(featureName); counter.addSample(sampleId, featureValue); } int sampleCount = (mClassCounts.containsKey(sampleId)) ? mClassCounts.get(sampleId) + 1 : 1; mClassCounts.put(sampleId, sampleCount); } /* * reset predictor to a empty model */ public void resetPredictor() { // TODO: not sure this step would reduce memory waste for (HistogramCounter counter : mPredictor.values()) { counter.resetCounter(); } mPredictor.clear(); mClassCounts.clear(); } /* * convert the prediction model into a byte array */ public byte[] getModel() { // TODO: convert model to a more memory efficient data structure. HashMap > > model = new HashMap > >(); for(Map.Entry entry : mPredictor.entrySet()) { model.put(entry.getKey(), entry.getValue().getCounter()); } try { ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); ObjectOutputStream objStream = new ObjectOutputStream(byteStream); objStream.writeObject(model); byte[] bytes = byteStream.toByteArray(); return bytes; } catch (IOException e) { throw new RuntimeException("Can't get model"); } } /* * set the prediction model from a model data in the format of byte array */ public boolean setModel(final byte[] modelData) { HashMap > > model; try { ByteArrayInputStream input = new ByteArrayInputStream(modelData); ObjectInputStream objStream = new ObjectInputStream(input); model = (HashMap > >) objStream.readObject(); } catch (IOException e) { throw new RuntimeException("Can't load model"); } catch (ClassNotFoundException e) { throw new RuntimeException("Learning class not found"); } resetPredictor(); for (Map.Entry > > entry : model.entrySet()) { useFeature(entry.getKey()); mPredictor.get(entry.getKey()).setCounter(entry.getValue()); } // TODO: this is a temporary fix for now loadClassCounter(); return true; } private void loadClassCounter() { String TIME_OF_WEEK = "Time of Week"; if (!mPredictor.containsKey(TIME_OF_WEEK)) { throw new RuntimeException("Precition model error: missing Time of Week!"); } HashMap > counter = mPredictor.get(TIME_OF_WEEK).getCounter(); mClassCounts.clear(); for (HashMap map : counter.values()) { for (Map.Entry entry : map.entrySet()) { int classCount = entry.getValue(); String className = entry.getKey(); // mTotalClassCount += classCount; if (mClassCounts.containsKey(className)) { classCount += mClassCounts.get(className); } mClassCounts.put(className, classCount); } } Log.i(TAG, "class counts: " + mClassCounts); } private void useFeature(String featureName) { if (!mPredictor.containsKey(featureName)) { mPredictor.put(featureName, new HistogramCounter()); } } }