AuthorDetector/src/main/java/de/nicode3141/Main.java

69 lines
2.3 KiB
Java

package de.nicode3141;
import de.nicode3141.genredct.Detector;
import de.nicode3141.genredct.GenreData;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
/**
* Copyright 2026 Nicolas Pfeifer nicodenetworks.com
* -
* This class is mainly for handling user dialog in the console
*/
public class Main {
public static void main(String[] args) throws FileNotFoundException {
String path = "data/labels.csv";
// User Dialog
String userInput = IO.readln("Using " + path + " as standard path for training data. Continue? (ENTER)");
if(!userInput.isEmpty()){
path = IO.readln("Enter your path: ");
}
IO.println("Starting training...");
long start = System.currentTimeMillis();
// Start training
// List params and weights
Detector genreDetector = new Detector(path);
long stop = System.currentTimeMillis();
IO.println("Training finished! (" + (int) (stop-start) +"ms)");
// User input text
// Predict genre
path = "input.txt";
userInput = IO.readln("Using input.txt as source? (y/n)");
if(!userInput.toLowerCase().contains("y")){
path = IO.readln("Enter your path");
}
Scanner scanner = new Scanner(new File(path), "UTF-8");
Map<String, Double> result = genreDetector.askModel(scanner);
IO.println("");
for (Map.Entry<String, Double> entry : result.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue().toString());
}
IO.println("");
// Calculates the confidence
double max = Collections.max(result.values());
double min = Collections.min(result.values());
// 1e-9 to prevent div by zero
double temperature = Math.max((max - min) / 4.0, 1e-9);
double sumExp = 0.0;
// Softmax calculation
for (double score : result.values()) {
sumExp += Math.exp((score - max) / temperature);
}
double topPercentage = 100.0 / sumExp;
Map.Entry<String, Double> topEntry = Collections.max(
result.entrySet(), Map.Entry.comparingByValue());
System.out.printf("Prediction: %s (relative confidence %.0f%%)%n", topEntry.getKey(), topPercentage);
}
}