下面列出了怎么用weka.core.SerializationHelper的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* tests for a serialVersionUID. Fails in case the schemes don't declare
* a UID (both must!).
*
* @return index 0 is true if the scheme declares a UID
*/
protected boolean[] declaresSerialVersionUID() {
boolean[] result = new boolean[2];
boolean eval;
boolean search;
print("serialVersionUID...");
eval = !SerializationHelper.needsUID(m_Evaluator.getClass());
search = !SerializationHelper.needsUID(m_Search.getClass());
result[0] = eval && search;
if (result[0])
println("yes");
else
println("no");
return result;
}
public NERTool(){
try {
// URL realPath = Thread.currentThread().getContextClassLoader().getResource("");
// System.out.println("realPath:"+realPath);
// String decoded = URLDecoder.decode(realPath.getFile(), "UTF-8");
// File fileRource1 = new File(decoded, GlobalSetting.rule_base_acdat_model);
// File fileRource2 = new File(decoded, GlobalSetting.rule_base_dict_model);
// System.out.println("f1="+fileRource1.getAbsolutePath());
// System.out.println("f2="+fileRource2.getAbsolutePath());
Resource fileRource = new ClassPathResource(rule_based_model);
this.rbm =(RuleBasedModels) SerializationHelper.read(new GZIPInputStream(fileRource.getInputStream()));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void initialise(String browserModelFilePath, String osModelFilePath, String fontsPath) throws Exception{
browserAttributes = new ArrayList<Attribute>();
osAttributes = new ArrayList<Attribute>();
browserClassAttribute = new Attribute("className", browserGroupsWeCareAbout);
osClassAttribute = new Attribute("className", osGroupsWeCareAbout);
browserAttributes.add(browserClassAttribute);
osAttributes.add(osClassAttribute);
for(int i = 1; i <= 5300; ++i){
browserAttributes.add(new Attribute(Integer.toString(i)));
osAttributes.add(new Attribute(Integer.toString(i)));
}
browserClassifier = (Classifier) SerializationHelper.read(browserModelFilePath);
osClassifier = (Classifier) SerializationHelper.read(osModelFilePath);
BrowserOsGuessFingerprintNumericRepresentation.initialise(fontsPath);
}
/**
* Returns the action lister to use in the menu.
*
* @param history the current history
* @param index the selected history item
* @return the listener
*/
@Override
public ActionListener getActionListener(final ResultHistoryList history, final int index) {
return new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int retVal = getFileChooser().showSaveDialog(null);
if (retVal != MekaFileChooser.APPROVE_OPTION)
return;
File file = getFileChooser().getSelectedFile();
try {
SerializationHelper.writeAll(file.getAbsolutePath(), (Object[]) history.getPayloadAt(index));
}
catch (Exception ex) {
String msg = "Failed to write model to '" + file + "'!";
System.err.println(msg);
ex.printStackTrace();
JOptionPane.showMessageDialog(
null, msg + "\n" + e);
}
}
};
}
public static void main(String[] args) throws Exception {
Classifier j48 = new J48();
Instances trainingData = GenerateTestVessels.getData();
j48.buildClassifier(trainingData);
System.out.println(j48);
double[] vesselUnderTest = GenerateTestVessels.getBarco(5);
DenseInstance inst = new DenseInstance(1.0,vesselUnderTest);
inst.setDataset(trainingData);
inst.setClassMissing();
System.out.println(inst);
double result = j48.classifyInstance(inst);
System.out.println(GenerateTestVessels.types[(int)result]);
SerializationHelper.write(new FileOutputStream("tmp"), j48);
J48 j48Read = (J48)SerializationHelper.read(new FileInputStream("tmp"));
}
/**
* tests for a serialVersionUID. Fails in case the scheme doesn't declare
* a UID.
*
* @return index 0 is true if the scheme declares a UID
*/
protected boolean[] declaresSerialVersionUID() {
boolean[] result = new boolean[2];
print("serialVersionUID...");
result[0] = !SerializationHelper.needsUID(m_Clusterer.getClass());
if (result[0])
println("yes");
else
println("no");
return result;
}
/**
* tests for a serialVersionUID. Fails in case the scheme doesn't declare
* a UID.
*
* @return index 0 is true if the scheme declares a UID
*/
protected boolean[] declaresSerialVersionUID() {
boolean[] result = new boolean[2];
print("serialVersionUID...");
result[0] = !SerializationHelper.needsUID(m_Associator.getClass());
if (result[0])
println("yes");
else
println("no");
return result;
}
/**
* tests for a serialVersionUID. Fails in case the scheme doesn't declare
* a UID.
*
* @return index 0 is true if the scheme declares a UID
*/
protected boolean[] declaresSerialVersionUID() {
boolean[] result = new boolean[2];
print("serialVersionUID...");
result[0] = !SerializationHelper.needsUID(m_Classifier.getClass());
if (result[0])
println("yes");
else
println("no");
return result;
}
/**
* tests for a serialVersionUID. Fails in case the scheme doesn't declare
* a UID.
*
* @return index 0 is true if the scheme declares a UID
*/
protected boolean[] declaresSerialVersionUID() {
boolean[] result = new boolean[2];
print("serialVersionUID...");
result[0] = !SerializationHelper.needsUID(m_Kernel.getClass());
if (result[0])
println("yes");
else
println("no");
return result;
}
public static void saveModel(Classifier classifier, String modelName) {
try {
SerializationHelper.write(modelName, classifier);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Save the currently selected experiment output to a file.
*
* @param name the name of the buffer to save
*/
protected void saveModel(Object[] data) {
int retVal = m_ModelFileChooser.showSaveDialog(CollectiveClassifierPanel.this);
if (retVal != JFileChooser.APPROVE_OPTION)
return;
try {
SerializationHelper.writeAll(m_ModelFileChooser.getSelectedFile().getAbsolutePath(), data);
m_Log.logMessage("Model saved successfully");
}
catch (Exception ex) {
String msg = "Failed to save model to '" + m_ModelFileChooser.getSelectedFile() + "': " + ex;
m_Log.logMessage(msg);
JOptionPane.showMessageDialog(CollectiveClassifierPanel.this, msg);
}
}
/**
* Reads the statistics.
*
* @return the statistics that were read
*/
@Override
public List<EvaluationStatistics> read() {
List<EvaluationStatistics> result;
try {
result = (List<EvaluationStatistics>) SerializationHelper.read(m_File.getAbsolutePath());
}
catch (Exception e) {
result = null;
handleException("Failed to read serialized statistics from: " + m_File, e);
}
return result;
}
/**
* Stores the given statistics.
*
* @param stats the statistics to store
* @return null if successfully stored, otherwise error message
*/
@Override
public String write(List<EvaluationStatistics> stats) {
log("Writing " + stats.size() + " statistics to: " + m_File);
try {
SerializationHelper.write(m_File.getAbsolutePath(), stats);
return null;
}
catch (Exception e) {
return handleException("Failed to write statistics to: " + m_File, e);
}
}
/**
* Reads an experiment from disk.
*
* @param file the file to load
* @return the experiment, null if failed to load
*/
@Override
public Experiment read(File file) {
try {
return (Experiment) SerializationHelper.read(file.getAbsolutePath());
}
catch (Exception e) {
handleException("Failed to read experiment from: " + file, e);
return null;
}
}
/**
* Writes and experiment to disk.
*
* @param exp the experiment to save
* @param file the file to save to
* @return null if successful, otherwise error message
*/
@Override
public String write(Experiment exp, File file) {
String result;
result = null;
try {
SerializationHelper.write(file.getAbsolutePath(), exp);
}
catch (Exception e) {
result = handleException("Failed to write experiment to: " + file, e);
}
return result;
}
/**
* Opens the specified model file.
*
* @param file the model file to load
*/
public void open(File file) {
Object[] data;
java.util.List<AbstractObjectRenderer> renderers;
JPanel panel;
m_TabbedPane.removeAll();
try {
data = SerializationHelper.readAll(file.getAbsolutePath());
for (Object obj: data) {
if (obj == null)
continue;
JTextArea text = new JTextArea(20, 40);
text.setFont(GUIHelper.getMonospacedFont());
renderers = AbstractObjectRenderer.getRenderer(obj);
if (renderers.size() == 0)
continue;
panel = new JPanel(new BorderLayout());
renderers.get(0).render(obj, panel);
m_TabbedPane.addTab(obj.getClass().getName(), panel);
}
m_RecentFilesHandler.addRecentItem(file);
m_LabelFile.setText(file.getAbsolutePath());
}
catch (Exception e) {
m_TabbedPane.removeAll();
m_LabelFile.setText(NO_FILE_LOADED);
System.err.println("Failed to load data from '" + file + "':");
e.printStackTrace();
JOptionPane.showMessageDialog(
this,
"Failed to load dataset from '" + file + "':\n" + e,
"Error loading",
JOptionPane.ERROR_MESSAGE);
}
}
@Override
public boolean initialize() {
try {
cls_act = (Classifier) SerializationHelper.read(Environment.getExternalStorageDirectory().getAbsolutePath()
+ "/Android/data/tinygsn/" + fileName);
} catch (Exception e) {
return false;
}
return true;
}
private static void serializeModel(final CommandLine commandLine, final ISupervisedLearner bestClassifier) throws Exception {
SerializationHelper.write(commandLine.getOptionValue(modelFileOption, modelFile), bestClassifier);
}
public static void main(String[] args) throws Exception {
if (args.length != 2) {
System.out.println("Usage: WekaSpeechActClassifier <train_set_input_file> <test_set_input_file>");
System.exit(0);
}
String arffFileTrain = args[0];
String arffFileTest = args[1];
LibSVM wekaClassifier = new LibSVM();
wekaClassifier.setOptions(new String[] {"-B", "-H"});
Instances preparedData = (Instances) SerializationHelper.read(arffFileTrain);
Instances preparedTest = (Instances) SerializationHelper.read(arffFileTest);
System.out.println("Reading train set and test set done!");
System.out.print("\nTraining...");
wekaClassifier.buildClassifier(preparedData);
System.out.println("\nTraining...done!");
Evaluation evalTrain = new Evaluation(preparedData);
evalTrain.evaluateModel(wekaClassifier, preparedData);
DecimalFormat formatter = new DecimalFormat("#0.0");
System.out.println("\nEvaluating on trainSet...");
System.out.println(evalTrain.toSummaryString());
System.out.println("\nResult on trainSet...");
System.out.println("Precision:" + formatter.format(100*evalTrain.precision(0)) + "%" +
" - Recal: " + formatter.format(100*evalTrain.recall(0)) + "%" +
" - F1: " + formatter.format(evalTrain.fMeasure(0)) + "%");
Evaluation eval = new Evaluation(preparedTest);
eval.evaluateModel(wekaClassifier, preparedTest);
System.out.println("\nEvaluating on testSet...");
System.out.println(eval.toSummaryString());
System.out.println("\nResult on testSet...");
System.out.println("Precision:" + formatter.format(100*eval.precision(0)) + "%" +
" - Recal: " + formatter.format(100*eval.recall(0)) + "%" +
" - F1: " + formatter.format(100*eval.fMeasure(0)) + "%");
System.out.println("True positive rate: " + formatter.format(100*eval.truePositiveRate(0)) + "%" +
" - True negative rate: " + formatter.format(100*eval.trueNegativeRate(0)) + "%");
System.out.println("Accuracy: " + formatter.format(100*((eval.truePositiveRate(0) + eval.trueNegativeRate(0)) / 2)) + "%");
System.out.println("\nDone!");
}