one-class svm_predict返回0或無法執行的解決方法(成功)
阿新 • • 發佈:2018-12-15
在使用svm中遇到的問題與解決,首先下面的程式碼是沒有實現的(但邏輯是沒有問題的,只是svm_predict不支援核2,3,4)
String path = Environment.getExternalStorageDirectory().toString()+ File.separator + fileDir; String test_path = path + "/test3.txt"; String output_path = path + "/result.txt"; String model_name = path + "/my_model2.txt"; String[] testArgs = {test_path, model_name, output_path}; svm_model model; model=svm.svm_load_model(model_name); svm_node[] test = new svm_node[]{new svm_node()}; for(int l=0;l<15;l++){ test[0].index = i; test[0].value = features[featuren-1][l]; } svm_predict predict = new svm_predict(); //double result_normal = svm.svm_predict.//svm_predict(model_name, test_path); System.out.println("++++++++++++++++++++++++++++++++++++++SVM predict"); double[] l = new double[2]; double pred_result = svm.svm_predict_probability(model, test,l); System.out.print("pred_result----->");System.out.println(pred_result);
這裡讀原始碼可以看到svm_predict可以支援哪些核如下
var0.param.svm_type != 2 && var0.param.svm_type != 3 && var0.param.svm_type != 4,這些核都是不支援的
0 -- C-SVC (多類分類) 1 -- nu-SVC (多類分類)核可以支援
所以當遇到對應核無法實現的時候,可以使用接下來的方法,將資料儲存到TXT(test3.txt)檔案中,使用檔案的方式對資料進行測試。(注意我這裡已經訓練好了,與訓練有關的引數都沒有使用,但是為了方便大家可能的學習,還是保留下來了)
我們解決這個問題無非是想實時呼叫,而不是隻是顯示在result.txt或者桌面上,所以接下來進行一個引數的追蹤(就是顯示在System.out中的正確率=90%(9/10),這個9就是我們要的數字,就是當前測試集中正確的個數,如果為1個,那就是這個樣例的測試結果)
String path = Environment.getExternalStorageDirectory().toString()+ File.separator + fileDir; /*File file3 = new File(path,"/test.csv"); BufferedWriter bw3 = new BufferedWriter(new FileWriter(file3,true)); bw3.write("s"); bw3.close(); System.out.println("file3");*/ String train_path = path + "/1015c.txt"; String test_path = path + "/test3.txt"; String output_path = path + "/result.txt"; String model_name = path + "/my_model2.txt"; //String[] trainArgs = {train_path, model_name};//、、"-s 2 -t 2 -n 0.01"關於引數可以在train。Java中直接進行修改,這裡就不操作了 String[] testArgs = {test_path, model_name, output_path}; //______svm_train train = new svm_train(); svm_predict predict = new svm_predict(); //double result_normal = svm.svm_predict.//svm_predict(model_name, test_path); System.out.println("++++++++++++++++++++++++++++++++++++++SVM predict"); //______train.main(trainArgs); predict.main(testArgs);
之後在svm_predict.java中對其中的引數進行引用,可以將這個結果拿出來作為其他.java的使用
//**********svm——predict 112行左右
if(svm_type == svm_parameter.EPSILON_SVR ||
svm_type == svm_parameter.NU_SVR)
{
svm_predict.info("Mean squared error = "+error/total+" (regression)\n");
svm_predict.info("Squared correlation coefficient = "+
((total*sumvy-sumv*sumy)*(total*sumvy-sumv*sumy))/
((total*sumvv-sumv*sumv)*(total*sumyy-sumy*sumy))+
" (regression)\n");
}
else
MainActivity.correctnn(correct);
//程式碼修改在上一行,這個correctnn是最後分類正確的個數,你就可以通過傳遞這個引數到某.java
//使用java呼叫就可以解決這個問題
System.out.println(correct);
svm_predict.info("Accuracy = "+(double)correct/total*100+
"% ("+correct+"/"+total+") (classification)\n");
}
本人第一次寫部落格,對於程式碼上的問題比較大的感慨就是如何去debug與讀原始碼,只有深入瞭解了 才有可能做出需要的修改
本人原創,轉載請註明出處謝謝