羅吉斯迴歸(LR)演算法java實現<轉>__演算法
最後更新:2018-07-26
來源:互聯網
上載者:User
按照機器學習實戰的python代碼,用java重寫LR的梯度上升演算法:
package com.log;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import Jama.Matrix;
public class LogProcess {
/**
* 擷取特徵資料
*/
public Matrix getDataMat(){
try {
ArrayList<double[]> list = new ArrayList<double[]>();
String pathname = "C:\\testSet.txt";
File filename = new File(pathname);
InputStreamReader reader = new InputStreamReader(
new FileInputStream(filename));
BufferedReader br = new BufferedReader(reader);
String line = "";
line = br.readLine();
while (line != null) {
String [] tmp=line.split("\t");
double [] value=new double[3];
value[0]=1.0;
value[1]=Double.parseDouble(tmp[0]);
value[2]=Double.parseDouble(tmp[1]);
list.add(value);
line = br.readLine(); // 一次讀入一行資料
}
//特徵轉化為二維數組
Iterator<double[]> datalIt = list.iterator();
double [][] data = new double[list.size()][3];
int i=0;
while (datalIt.hasNext()) {
double [] tmp = datalIt.next();
data[i][0]=tmp[0];
data[i][1]=tmp[1];
data[i][2]=tmp[2];
i++;
}
Matrix dataMatrix = new Matrix(data);
return dataMatrix;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 擷取標籤資料
*/
public Matrix getLabelMat(){
try {
ArrayList<int[]> list = new ArrayList<int[]>();
String pathname = "C:\\testSet.txt";
File filename = new File(pathname);
InputStreamReader reader = new InputStreamReader(
new FileInputStream(filename));
BufferedReader br = new BufferedReader(reader);
String line = "";
line = br.readLine();
while (line != null) {
String [] tmp=line.split("\t");
int [] value=new int[1];
value[0]=Integer.parseInt(tmp[2]);
list.add(value);
line = br.readLine(); // 一次讀入一行資料
}
//將標籤轉化為二維數組
Iterator<int[]> labelIt = list.iterator();
double [][] label = new double[list.size()][1];
int j=0;
while (labelIt.hasNext()) {
label[j][0]=labelIt.next()[0];
j++;
}
Matrix labelMatrix = new Matrix(label);
return labelMatrix;
} catch (Exception e) {