From 9852815267606c379d86495c6726194c10580183 Mon Sep 17 00:00:00 2001 From: nicode3141 Date: Sat, 14 Nov 2026 16:58:27 +0100 Subject: [PATCH] (detector): trainModel last implementations for Detector --- .../java/de/nicode3141/genredct/Detector.java | 126 +++++++++++++++--- .../de/nicode3141/genredct/GenreData.java | 19 +-- .../de/nicode3141/genredct/TextCounts.java | 21 +++ src/test/java/genredct/DetectorTests.java | 17 ++- 4 files changed, 153 insertions(+), 30 deletions(-) create mode 100644 src/main/java/de/nicode3141/genredct/TextCounts.java diff --git a/src/main/java/de/nicode3141/genredct/Detector.java b/src/main/java/de/nicode3141/genredct/Detector.java index 180ef57..d0bb71c 100644 --- a/src/main/java/de/nicode3141/genredct/Detector.java +++ b/src/main/java/de/nicode3141/genredct/Detector.java @@ -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 modelData; - private final String[] vocabulary; + private static final int WEIGHTS_COUNT = 500; + private static final int EPOCH_SIZE = 10; + private int genreCount; + public Map modelData; + public final Set 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> genreData = GenreData.loadGenres("data/labels.csv"); + assert genreData != null; + List allPaths = genreData.values() + .stream() + .flatMap(List::stream) + .toList(); + + vocabulary = GenreData.countWords(allPaths, WEIGHTS_COUNT).keySet(); + + Map> trainingCounts = GenreData.countTrainData(genreData, vocabulary); + modelData = new LinkedHashMap<>(); + + genreCount = 0; + // Loop all genres + for(Map.Entry> 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 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 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>[] inputText){ + double[] trainModel(Map> 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 texts = new ArrayList<>(); + List expected = new ArrayList<>(); + + // Loop thru all genres and assign expected result + for(Map.Entry> 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 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 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 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 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; } } diff --git a/src/main/java/de/nicode3141/genredct/GenreData.java b/src/main/java/de/nicode3141/genredct/GenreData.java index deef9eb..61260d3 100644 --- a/src/main/java/de/nicode3141/genredct/GenreData.java +++ b/src/main/java/de/nicode3141/genredct/GenreData.java @@ -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>> countTrainData(Map> texts, Set vocabulary){ - Map>> genreWordCounts = new LinkedHashMap<>(); + public static Map> countTrainData(Map> texts, Set vocabulary){ + Map> genreWordCounts = new LinkedHashMap<>(); // Loop thru each genre for(Map.Entry> textPaths : texts.entrySet()){ - List> genreTextCount = new ArrayList<>(); + List genreTextCount = new ArrayList<>(); // Loop thru all Texts for(String textPath : textPaths.getValue()){ - Map 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 countCommonWords(String path, Set vocabulary){ + public static TextCounts countCommonWords(String path, Set vocabulary){ // TODO: Scan text line by line and count words from vocabulary. Map 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); } } diff --git a/src/main/java/de/nicode3141/genredct/TextCounts.java b/src/main/java/de/nicode3141/genredct/TextCounts.java new file mode 100644 index 0000000..a702b47 --- /dev/null +++ b/src/main/java/de/nicode3141/genredct/TextCounts.java @@ -0,0 +1,21 @@ +package de.nicode3141.genredct; + +import java.util.Map; + +public class TextCounts { + public final Map vocabCount; + public final int totalWords; + + public TextCounts(Map vocabCount, int totalWords) { + this.vocabCount = vocabCount; + this.totalWords = totalWords; + } + + public Map getVocabCount(){ + return this.vocabCount; + } + + public int getTotalWords(){ + return this.totalWords; + } +} diff --git a/src/test/java/genredct/DetectorTests.java b/src/test/java/genredct/DetectorTests.java index 6c696a6..27f41fd 100644 --- a/src/test/java/genredct/DetectorTests.java +++ b/src/test/java/genredct/DetectorTests.java @@ -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 vocabulary = GenreData.countWords(allPaths, 500); - Map 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 vocabulary = GenreData.countWords(allPaths, 500); - Map>> trainingCounts = GenreData.countTrainData(genreData, vocabulary.keySet()); + Map> 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); } }