WIki上面的ROC曲線說明的很詳細了。 因爲要寫連續值的roc曲線。需要確定閾值,wiki上面的說明如下。
當訊號偵測(或變數測量)的結果是一個連續值時,類與類的邊界必須用一個閾值(英語:threshold)來界定。
Java代碼如下:
public double[][] getROC(double thershold, double[] product, double[] predict) { //thershold是閾值,也就是基準
if(product.length != predict.length)
throw new IllegalStateException("長度必須一致");
else if(product.length == 0
|| predict.length == 0
|| product == null
|| predict == null)
throw new IllegalStateException("請傳入有參數的數值");
log.error("origin data: "+ product.toString() + "\t" + "predict data: " + predict);
double sumTp = 0.0;
double sumFn = 0.0;
double sumFp = 0.0;
double sumTn = 0.0;
double tpr = 0.0;
double fpr = 0.0;
int len = product.length;
double[] X = new double[len];
double[] Y = new double[len];
for(int i = 0; i < len; i++) { //後面的product[i], 可以用自己想要的維度來替換
if((Math.abs(product[i]-predict[i]) /product[i] > thershold) & (product[i] > 4) == true)
sumTp += 1.0;
if((Math.abs(product[i]-predict[i]) /product[i] > thershold) & (product[i] > 4) == false)
sumFn += 1.0;
if((Math.abs(product[i]-predict[i]) /product[i] < thershold) & (product[i] > 4) == true)
sumFp += 1.0;
if((Math.abs(product[i]-predict[i]) /product[i] < thershold) & (product[i] > 4) == false)
sumTn += 1.0;
if (sumTp == 0.0)
tpr = 0.0;
else
tpr = sumTp / (sumTp + sumFn);
if (sumFp == 0.0)
fpr = 0.0;
else
fpr = sumFp / (sumFp + sumTn);
X[i] = fpr;
Y[i] = tpr;
} //爲了畫出一個曲線,所以我選擇存入二維數組中
double[][] roc = {X,Y};
return roc;
}