因为WEKA中所有分类器都实现了Serializable,所以只需要用java的ObjectOutputStream就可以实现了。
/** * 存储model * * @param model * 训练过的分类器 例如J48 * @param ModelPath * 存储路径 */ private void persistModel(Classifier model, String ModelPath) { ObjectOutputStream oos = null; try { oos = new ObjectOutputStream(new FileOutputStream(ModelPath)); oos.writeObject(model); oos.flush(); oos.close(); } catch (IOException e) { e.printStackTrace(); } } /** * 加载model * * @param ModelPath * 存储路径 * @return 分类器 */ private Classifier reloadPersistModel(String ModelPath) { ObjectInputStream ois = null; try { ois = new ObjectInputStream(new FileInputStream(new File(ModelPath))); Classifier model = (Classifier) ois.readObject(); ois.close(); return model; } catch (Exception e) { e.printStackTrace(); } return null; }
调用的地方
Classifier m_classifier = new J48(); m_classifier.buildClassifier(instances); // 存储model persistModel(m_classifier, "/data/data/com.example.wekatest/model"); // 读取model Classifier m_classifier2 = reloadPersistModel("/data/data/com.example.wekatest/model"); Log.d(LOG_TAG, m_classifier2.toString());