(detector): trainModel last implementations for Detector

master
nicode3141 2026-11-14 16:58:27 +01:00
parent c51b656e25
commit 9852815267
4 changed files with 153 additions and 30 deletions

View File

@ -1,26 +1,45 @@
package de.nicode3141.genredct;
import java.util.Map;
import java.util.Objects;
import java.util.*;
public class Detector {
private final int weightsCount = 500;
private Map<String, Double[]> modelData;
private final String[] vocabulary;
private static final int WEIGHTS_COUNT = 500;
private static final int EPOCH_SIZE = 10;
private int genreCount;
public Map<String, double[]> modelData;
public final Set<String> vocabulary;
/**
* Starts the training with provided data
* @param csvPath path of the csv containing all texts
* @return created weights for each genre + bias
*/
public Detector(String csvPath, String vocabulary) {
public Detector(String csvPath) {
// Build common vocabulary
// Get labels and WordCounts from countTrainData()
// trainModel with labels and WordCount
// returns weights
this.modelData = null;
this.vocabulary = new String[weightsCount];
Map<String, List<String>> genreData = GenreData.loadGenres("data/labels.csv");
assert genreData != null;
List<String> allPaths = genreData.values()
.stream()
.flatMap(List::stream)
.toList();
vocabulary = GenreData.countWords(allPaths, WEIGHTS_COUNT).keySet();
Map<String, List<TextCounts>> trainingCounts = GenreData.countTrainData(genreData, vocabulary);
modelData = new LinkedHashMap<>();
genreCount = 0;
// Loop all genres
for(Map.Entry<String, List<TextCounts>> genres : trainingCounts.entrySet()){
double[] currWeights = trainModel(trainingCounts, genres.getKey(), genreCount);
modelData.put(genres.getKey(), currWeights);
genreCount++;
}
}
/**
@ -47,37 +66,108 @@ public class Detector {
* @param bias constant to adjust the perceptron
* @return sum of all weighted word counts
*/
public static double calcSum(Map<String, Integer> inputText, double[] weights, double bias){
public static double calcSum(TextCounts inputText, double[] weights, double bias){
// TODO: loop thru the map and add the (word count / total words) * weight to it
// After the loop, increment the sum by the bias
return 0.0d;
double sum = bias;
int i = 0;
for(Map.Entry<String, Integer> currWordMap : inputText.vocabCount.entrySet()){
if(i > WEIGHTS_COUNT) break;
Integer wordCount = currWordMap.getValue();
double wordValue = (double) wordCount / inputText.totalWords;
sum += wordValue * weights[i];
i++;
}
return sum;
}
/**
* Adjust the weights of a genre for correct result
* @param inputText word count of all texts to the common vocabulary
* @return final weights for a genre
* @param inputTexts word count of all texts to the common vocabulary
* @param currGenre current genre, that is being trained
* @return final weights for a genre, + bias
*/
double[] trainModel(Map<String, Map<String, Integer>>[] inputText){
double[] trainModel(Map<String, List<TextCounts>> inputTexts, String currGenre, int genreIdx){
// TODO: Start with all weights = 0.0, bias = 0.0
// Then loop thru multiple epochs:
// Loop thru all texts, calculate the sum
// If the sum is >= 0 -> means it belongs to the genre
// If the prediction was wrong, correct the weights
// (weights += learningRate * error * wordCount
return null;
double[] weights = new double[WEIGHTS_COUNT];
double bias = 0.0d;
// All texts
List<TextCounts> texts = new ArrayList<>();
List<Integer> expected = new ArrayList<>();
// Loop thru all genres and assign expected result
for(Map.Entry<String, List<TextCounts>> genres : inputTexts.entrySet()){
int expectedLabel = (genres.getKey().equalsIgnoreCase(currGenre)) ? 1 : 0;
// All texts
for (TextCounts genreEntry : genres.getValue()) {
texts.add(genreEntry);
expected.add(expectedLabel);
}
}
// Shuffled ordered index (currently ordered by genre)
List<Integer> orderIdx = new ArrayList<>();
for(int i = 0; i < texts.size(); i++){
orderIdx.add(i);
}
Collections.shuffle(orderIdx);
// Go randomly thru texts
for(int i : orderIdx){
double sum = calcSum(texts.get(i), weights, bias);
int prediction = (sum >= 0) ? 1 : 0;
int error = expected.get(i) - prediction;
if (error != 0) {
// correct the weights
// Loop thru vocabulary
int idx = 0;
for(Map.Entry<String, Integer> currWordMap : texts.get(i).vocabCount.entrySet()){
Integer wordCount = currWordMap.getValue();
double wordValue = (double) wordCount / texts.get(i).totalWords;
weights[idx] += error * wordValue;
idx++;
}
bias += error;
}
}
double[] modelParams = Arrays.copyOf(weights, weights.length +1);
modelParams[WEIGHTS_COUNT] = bias;
return modelParams;
}
/**
* Predicts which genre the text belongs to
* @param inputText word count of the text to test to the common vocabulary
* @param weights weights array for current genre
* @param bias bias for current genre
* @return array with value for each genre, contains the calculated sum
*/
double[] predictGenre(Map<String, Integer> inputText, double[] weights, double bias){
double[] predictGenre(TextCounts inputText){
// TODO: Fixed size array for each genre
if(modelData.isEmpty()) return null;
double[] result = new double[modelData.size()];
// For each genre calcSum
return null;
int idx = 0;
for(Map.Entry<String, double[]> currGenre : modelData.entrySet()){
double[] concatData = currGenre.getValue();
double[] weights = Arrays.copyOf(concatData, concatData.length -1);
double bias = concatData[concatData.length-1];
result[idx++] = calcSum(inputText, weights, bias);
}
return result;
}
}

View File

@ -46,17 +46,17 @@ public class GenreData {
* Counts all words against the common vocab and categorizes them to their genre.
* @param texts label, path of the genre texts
* @param vocabulary common top X words to count against
* @return Map key: genre, value: (Map: key: word, value: count)
* @return Map key: genre, value: TextCounts
*/
public static Map<String, List<Map<String, Integer>>> countTrainData(Map<String, List<String>> texts, Set<String> vocabulary){
Map<String, List<Map<String, Integer>>> genreWordCounts = new LinkedHashMap<>();
public static Map<String, List<TextCounts>> countTrainData(Map<String, List<String>> texts, Set<String> vocabulary){
Map<String, List<TextCounts>> genreWordCounts = new LinkedHashMap<>();
// Loop thru each genre
for(Map.Entry<String, List<String>> textPaths : texts.entrySet()){
List<Map<String, Integer>> genreTextCount = new ArrayList<>();
List<TextCounts> genreTextCount = new ArrayList<>();
// Loop thru all Texts
for(String textPath : textPaths.getValue()){
Map<String,Integer> textWordCount = countCommonWords(textPath, vocabulary);
TextCounts textWordCount = countCommonWords(textPath, vocabulary);
genreTextCount.add(textWordCount);
}
@ -137,12 +137,13 @@ public class GenreData {
* Counts top X words which are in the vocabulary of a textfile
* @param path source plain textfile
* @param vocabulary words to count
* @return LinkedMap key: word, value: count
* @return TextCounts -> LinkedMap key: word, value: count; totalWords
*/
public static Map<String, Integer> countCommonWords(String path, Set<String> vocabulary){
public static TextCounts countCommonWords(String path, Set<String> vocabulary){
// TODO: Scan text line by line and count words from vocabulary.
Map<String, Integer> vocabCount = new LinkedHashMap<>();
int totalWords = 0;
for(String item : vocabulary){
vocabCount.put(item, 0);
@ -159,6 +160,8 @@ public class GenreData {
word = word.replaceAll("[^\\p{L}]", "");
if(word.isEmpty()) continue;
totalWords++;
// If word matches vocabulary
if(vocabCount.containsKey(word)){
vocabCount.put(word, vocabCount.get(word) +1);
@ -171,6 +174,6 @@ public class GenreData {
IO.println("Couldn't find file " + path + " err: " + e.getLocalizedMessage());
}
return vocabCount;
return new TextCounts(vocabCount, totalWords);
}
}

View File

@ -0,0 +1,21 @@
package de.nicode3141.genredct;
import java.util.Map;
public class TextCounts {
public final Map<String, Integer> vocabCount;
public final int totalWords;
public TextCounts(Map<String, Integer> vocabCount, int totalWords) {
this.vocabCount = vocabCount;
this.totalWords = totalWords;
}
public Map<String, Integer> getVocabCount(){
return this.vocabCount;
}
public int getTotalWords(){
return this.totalWords;
}
}

View File

@ -2,6 +2,7 @@ package genredct;
import de.nicode3141.genredct.Detector;
import de.nicode3141.genredct.GenreData;
import de.nicode3141.genredct.TextCounts;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
@ -24,11 +25,12 @@ public class DetectorTests {
wordCounts.put("a", 0);
wordCounts.put("another", 0);
wordCounts.put("after", 0);
TextCounts textCounts = new TextCounts(wordCounts, 10);
double weigths[] = {0.1d, 0.0d, -1.2d, 3.4d, 5,9d, 0.0d};
double[] weigths = {0.1d, 0.0d, -1.2d, 3.4d, 5.0d,9d, 0.0d};
double bias = 0.0d;
double sum = -0.11d;
assertEquals(sum, Detector.calcSum(wordCounts, weigths, bias));
assertEquals(sum, Detector.calcSum(textCounts, weigths, bias));
}
@DisplayName("Loads Genres")
@ -64,7 +66,7 @@ public class DetectorTests {
System.out.println("Total paths: " + allPaths);
Map <String, Integer> vocabulary = GenreData.countWords(allPaths, 500);
Map<String, Integer> wordCount = GenreData.countCommonWords("data/train/adventure/2154_around-the-world-in-eighty-days-junior-deluxe-edit.txt", vocabulary.keySet());
TextCounts textCounts = GenreData.countCommonWords("data/train/adventure/2154_around-the-world-in-eighty-days-junior-deluxe-edit.txt", vocabulary.keySet());
}
@DisplayName("Count training words against Vocabulary")
@ -80,6 +82,13 @@ public class DetectorTests {
System.out.println("Total paths: " + allPaths);
Map <String, Integer> vocabulary = GenreData.countWords(allPaths, 500);
Map<String, List<Map<String, Integer>>> trainingCounts = GenreData.countTrainData(genreData, vocabulary.keySet());
Map<String, List<TextCounts>> trainingCounts = GenreData.countTrainData(genreData, vocabulary.keySet());
}
@DisplayName("Test Detector Contructor")
@Test
public void testDetector(){
Detector genreDetector = new Detector("data/labels.csv");
IO.println(genreDetector.modelData);
}
}