(detector): smaller changes for better output, epochs

master
nicode3141 2026-11-15 11:06:16 +01:00
parent 78a0da4dc0
commit 2e442ca526
5 changed files with 218 additions and 60 deletions

130
input.txt 100644
View File

@ -0,0 +1,130 @@
"That's it," Thorin says, sitting up from his chair. I can't sleep tonight knowing we didn't do anything enjoyable all day."
So much for a peaceful evening at home, I think to myself begrudgingly. “Well, I suppose we could go for a quick outing,” I say with a sigh, with extra emphasis on the word quick. “If you’re sure it isn’t too late already?” I ask, worriedly gazing out the window.
“Hmm?” he raises an eyebrow and follows my eyes to the golden hour beams illuminating the room.
Thorin laughs and shakes his head, a mischievous twinkle in his eye.
Ten minutes later, we set out into the forest, no agenda and no rules. It’s been a while since either of us has been out of the cottage, but I can tell it has affected Thorin more than it has me. It must have been awful, I think to myself, to go from being the top of the food chain to literally depending on the kindness of strangers to be able to recover. I think back to the early days of Thorin’s recovery, back when he would refuse my help and dump out any food I brought him. It’s laughable now, how stubborn he was that no one could help him. But little did he know, He met his match with me, because I was just as stubborn, forcing him to take care of himself and slow down.
As we walk towards the riverbank, he chatters excitedly about his favorite spot he used to train, a clearing not far from here that he insists we visit. Right away, he seems so much more open and carefree now that we’ve taken a break from our mundane little routine. I wonder what these past few weeks have been like for him, stuck in a tiny house and forced to live with strangers until he recovers. Unanswered questions wind through my brain, and I wonder what he would say to each. What did he think about the cottage when he first woke up? Does he miss anyone from the academy? Even more startling, I realize the question I would like to know the answer to the most:
I wonder what he thought about me?
Lost in my own thoughts, I fail to notice that Thorin is no longer by my side, and I look over my shoulder to see him peering down at the edge of the river.
“So tell me about it,” I say neutrally as I sit down at the base of a large pine tree. I pat the grass next to me and gesture for Thorin to do the same.
“About what?” He asks innocently, raising his eyebrows and pretending he doesn’t know what I’m about to ask.
“About the academy,” I reply simply, shoving him playfully in the shoulder. “About you, about your life, everything!”
His face falls instantly, and his eyes drop to his hands sitting in his lap as he continues. “Akira, you know I don’t- I mean, I’,m not-“ He starts, running his hand through his hair and looking slightly uncomfortable.
I take a deep breath, knowing that I’m currently walking on paper-thin ice. “I know you don’t like to talk about it, but I think you need to tell someone about what you’ve been through,” I say, determined to get my point across. He shrugs, and I push harder, ranting, “I mean, you’ve got to at some point, but every time I bring it up, you just try to change the subject. The problem is, I don’t see why you won’t tell me anything. Not even the tiniest detail, like the name of your roommate, or your favorite food at the mess hall, or even what happened the day my grandfather found you half dead in the forest.” He blinks. “So, why? Why can’t you tell me anything? What are you so afraid of?”
“Akira, I don’t think that this conversation is a good idea,” He says firmly. His eyes dart from side to side, and he squirms slightly. I can tell that I have to be careful, and I try to read his reaction to my words.
He opens his mouth, but before he can rattle off his usual “let’s just ignore and bury this hatchet” rehearsed response, something comes over me, and I finally say the thing that has been on my mind for the last few weeks: “Look, Thorin, whatever you were forced to do was not your fault. We both know you have done and seen things that no one should have to experience, and for that I am truly sorry. You didn’t have a choice, and that’s awful, but now you do. You can choose to let your bad memories control you for the rest of your life by keeping them locked away in some tiny box, or you can address them.” I quickly swallow and keep going before I lose the nerve I’ve been building. “I think what frightens you the most isn’t that you can never go back. I think the thing that scares you the most is the fact that deep down, you are slowly realizing that you don’t want to go back.”
He looks away like I have slapped him with a cruel insult, and I know I have gone too far. He doesn’t say anything for the longest time; instead, he just stares out into the dark woods as we sit there in painful silence.
After minutes that seem to pass by like hours, I finally break the tense air. “I’m sorry.” I say, “That was wrong of me to try and force you to open up like that. I shouldn’t have said those things.”
Now it’s my turn to be uncomfortable as my eyes drop to my wringing hands guiltily. I mentally kick myself, knowing I’ve definitely just burned any bridges of friendship that were built between us over the past month. All I can do now is close my eyes and brace myself for more silence while I wait for the blow of his retort to strike me.
“No, actually you were right.” He says, and I look at him, surprised. “That was a bit harsh, yes, but that all was true.”
I don’t know whether to smile with relief or cry with empathy as I register what he is saying.
“So? You don’t want to go back after all of this?” I ask innocently.
Thorin doesn’t answer at first, but he offers me a small smile and shrugs. Understanding what he means, I drop it and look out into the grass swaying in the breeze.
“The truth is, I didn’t tell you because it’s been easier to just pretend it never happened.” He says, admittedly. “I know it’s wrong, but ignoring my past for a few weeks, although immature and selfish, has allowed me to be myself for the first time in a long time. Yes, I’ll have to face the painful memories tomorrow, but I was trying to live for today.”
“You were just trying to survive,” I say slowly, beginning to see his point of view. “But you can’t live like that, Thorin; you can’t hide from the light.”
“You have to step into it.” We say at the same time, and then turn to each other in surprise.
“How do you-” I ask, shaking my head in confusion.
“It’s an old saying my father used to tell me,” Thorin says while twisting blades of tall grass between his fingers. “At least, I think he used to,” He says quickly. “I can’t remember my parents-they died when I was eight. I was raised in an orphanage in the capital until I was selected to attend the academy.”
His eyes flicker at the mention of his family, and I gently place my hand on his arm. “I had no idea. Thorin, I’m sor-“
“Don’t be.” He responds, shaking off my condolences. “They died in an accident a long time ago. I think about them from time to time, yeah, but I’m fine, really.”
His words tip up at the end of his sentences, and I can tell he’s trying to drive his point home. I study the expression on his face, but his jaw remains set, unmovable and strong. His eyes give me no obvious clues either, and he’s still peering into the grass with concentration. No matter how hard he tries to tell me otherwise, I can tell I’m in uncomfortable territory.
“The officer that responded to the crash found a note my dad had written for me in the wreckage and delivered it the next day. And that’s all I have left of them.” His voice trails off distractedly, and he becomes lost in thought. I reach my hand out with apprehension, but not knowing how he might react, I decide against it and let it fall back into my lap.
“All right, that’s enough of that for now,” Thorin says, brushing his hands off and standing up slowly. He holds his hand out to me, and I stare at it blankly, confused. “We came here to do something fun, not listen to my sob story. Come on, Dance with me,” He says, tilting his head at the clearing behind him.
Looking over his shoulder at the moonlit opening, I throw my head back and laugh. “HA! Here? Now?” I ask disbelievingly, shaking my head. Obviously he’s joking. Right?
“Shall we?” He asks, a familiar twinkle in his eye. His hand is still outstretched, and I take it. Two can play this game.
“I would be honored,” I say, feigning elegance as I drop into a ridiculously deep curtsy. Thorin follows suit with a stiff bow, and we both crack up, unable to take each other seriously. As we take turns recovering and then spiraling into another fit of laughter, I can’t help but notice how different I feel when I’m around him. Lighter almost. It’s as if everything else seems to melt away and I can be myself in the moment. But just as I start to explore that thought, Thorin interrupts by tackling me onto the ground, spurring another fit of laughter from both of us.
Once we finally are able to breathe again, we stand up, and he gently wraps his arm around my waist and leads me out of the trees.
Thorin laces his fingers through mine and slides his hand across my back in a comforting embrace. We sway to the breeze as the moon illuminates the glade and turns the whole world silver. The clouds roll by, occasionally casting swooping shadows for us to weave between in the forest ballroom. The trees rustle gently, the orchestra of leaves crashing and crescendoing to the rhythm of the shifting wind. Shades of green cast from the foliage flicker across my gaze. Closing my eyes, I silently wish I could stay in this moment forever. The world spins and shifts, yet Thorin’s hand on my back and the soft thump-thump of our feet keep me grounded.
Out of the corner of my eye, I suddenly spot a flash of light, and I stop dancing. I peer into the darkness at where I saw the glow. After a few seconds, I see another flash, and then another.
“Fireflies!” I gasp, unable to hide my excitement.
Thorin’s expression is blank, seemingly confused by my enthusiasm, and my jaw drops to the floor.
“Wait- you’re telling me you’ve never seen fireflies before? You’ve got to be kidding me! That’s an actual crime.” He just shakes his head, looking politely puzzled. Sighing, I grab his hand, and we head towards where I noticed the flash.
“Watch this,” I say, and with a swift sweeping movement, I push my arm through the silky grass, causing thousands of glowing lights to ascend into the air.
Thorin’s eyes grow wide as he takes in the spectacle. “You’re telling me that those are bugs?” He says, the confusion in his tone intensifying.
“Yep,” I respond simply. “Not much bigger than a grain of rice.”
“All this time- I can’t believe-“ He shakes his head, and I can tell he’s choosing his words carefully. “I can’t believe how much beauty there is in everyday things,” He says finally. “I think that’s been one of the hardest lessons for me to learn. Because at the Academy, it was instilled in us that moments like this don’t exist. We were trained to believe the lie that happiness is simply a mask for weakness, and that weakness will get you killed. For years we acted on this principle, blinded by our corrupted paradigms. But now I know for a fact that’s not true, and I can’t picture a world through another gray lens. I can’t picture a world without color.”
“That’s really amazing, Thorin,” I say, filled to the brim with hope for him and his new life.
“Yeah. I guess it is.” He says, smiling to himself proudly. The sight of his happiness pours more into my cup of joy, until I am unable to contain its contents and I start to smile too.
“Thanks for showing me the fireflies.” He says, grinning.
“Hmm?” I look at him, confused. “Thorin, that was just
Together we sprint out into the soft grass in the middle of the clearing, running our hands through the cool blades all the way. The air, warm and inviting, tells the tale of an amber sunset. I can’t help but exhale the sweet melody of peace through my nose and realize that this is the first time in a while I’ve felt truly free.
As if this were a scene in the movies, hundreds of fireflies take flight as we tear by their perches. I throw my arms out and spin in circles, sending more and more luminescent trails into the sky. Thorin laughs as the little lights shimmer around us like gems in a cavern, glittering and glowing through the night sky.
“It’s so beautiful,” I say finally, mesmerized by the light show the little creatures make. They shimmer in dazzling patterns that dance across my vision like embers in the inky black sky. I’m not able to look away, but the sound of Thorin’s voice shifts my attention as he speaks.
“Yes, it really is.” Thorin agrees. I turn my head back to look at him and realize that he isn’t looking at the fireflies anymore. We lock eyes, and I suddenly blush, and it hits me: he’s talking about me. I quickly cover myself with my hand, praying the moonlight will cover up my embarrassment and that he didn’t pick up on it.
AKIRA.
CALM.
DOWN.
I yell to myself as I stand there stupidly like a deer in headlights. Echoes of wishful daydreams bounce around in my mind, and I try my best to subdue them. Does Thorin think I’m beautiful? I wonder to myself. I steal a glance in his direction, and he quickly looks away, making me laugh under my breath.
“So how did you learn to dance?” Thorin asks

View File

@ -3,8 +3,9 @@ package de.nicode3141;
import de.nicode3141.genredct.Detector;
import de.nicode3141.genredct.GenreData;
import java.util.Arrays;
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
/**
* Copyright 2026 Nicolas Pfeifer nicodenetworks.com
@ -12,7 +13,7 @@ import java.util.Scanner;
* This class is mainly for handling user dialog in the console
*/
public class Main {
public static void main(String[] args){
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)");
@ -31,17 +32,37 @@ public class Main {
// User input text
// Predict genre
IO.println("Please enter your text here: ");
Scanner scanner = new Scanner(System.in);
double[] result = genreDetector.askModel(scanner);
path = "input.txt";
userInput = IO.readln("Using input.txt as source? (y/n)");
if(!userInput.toLowerCase().contains("y")){
path = IO.readln("Enter your path");
}
IO.print("");
Scanner scanner = new Scanner(new File(path), "UTF-8");
Map<String, Double> result = genreDetector.askModel(scanner);
IO.println("Adventure: " + result[0]);
IO.println("Romance: " + result[1]);
IO.println("Mystery: " + result[2]);
IO.println("Horror: " + result[3]);
IO.println("Sci-Fi: " + result[4]);
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);
}
}

View File

@ -1,12 +1,13 @@
package de.nicode3141.genredct;
import java.io.File;
import java.util.*;
public class Detector {
private static final int WEIGHTS_COUNT = 500;
private static final int EPOCH_SIZE = 10;
private static final int EPOCH_SIZE = 5;
private static final double SCALE = 1000.0;
private static final int SKIP_TOP = 50;
private int genreCount;
public Map<String, double[]> modelData;
public final Set<String> vocabulary;
@ -29,7 +30,7 @@ public class Detector {
.flatMap(List::stream)
.toList();
vocabulary = GenreData.countWords(allPaths, WEIGHTS_COUNT).keySet();
vocabulary = GenreData.createAlphabet(allPaths, WEIGHTS_COUNT, SKIP_TOP);
Map<String, List<TextCounts>> trainingCounts = GenreData.countTrainData(genreData, vocabulary);
modelData = new LinkedHashMap<>();
@ -66,7 +67,7 @@ public class Detector {
* @return array with value for each genre, contains the calculated sum
* Order: adventure, romance, mystery, horror, scifi
*/
public double[] askModel(Scanner scanner){
public Map<String, Double> askModel(Scanner scanner){
TextCounts wordCounts = GenreData.countCommonWords(scanner, vocabulary);
return predictGenre(wordCounts);
}
@ -81,6 +82,7 @@ public class Detector {
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
if(inputText.totalWords == 0) return bias;
double sum = bias;
int i = 0;
@ -90,7 +92,7 @@ public class Detector {
Integer wordCount = currWordMap.getValue();
double wordValue = (double) wordCount / inputText.totalWords;
sum += wordValue * weights[i];
sum += wordValue * weights[i] * SCALE;
i++;
}
@ -128,35 +130,40 @@ public class Detector {
}
}
// 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);
double[] modelParams = null;
// Go randomly thru texts
for(int i : orderIdx){
double sum = calcSum(texts.get(i), weights, bias);
int prediction = (sum >= 0) ? 1 : 0;
for(int j = 0; j < EPOCH_SIZE; j++) {
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;
// 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, new Random(2));
double[] modelParams = Arrays.copyOf(weights, weights.length +1);
modelParams[WEIGHTS_COUNT] = bias;
// 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 * SCALE);
idx++;
}
bias += error;
}
}
modelParams = Arrays.copyOf(weights, weights.length + 1);
modelParams[WEIGHTS_COUNT] = bias;
}
return modelParams;
}
@ -166,18 +173,17 @@ public class Detector {
* @param inputText word count of the text to test to the common vocabulary
* @return array with value for each genre, contains the calculated sum
*/
double[] predictGenre(TextCounts inputText){
Map<String, Double> predictGenre(TextCounts inputText){
// TODO: Fixed size array for each genre
if(modelData.isEmpty()) return null;
double[] result = new double[modelData.size()];
Map<String, Double> result = new LinkedHashMap<>();
// For each genre calcSum
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);
result.put(currGenre.getKey(), new Double(calcSum(inputText, weights, bias)));
}
return result;

View File

@ -7,7 +7,6 @@ import java.io.FileNotFoundException;
import java.util.*;
public class GenreData {
/**
* This method gets all books and their corresponding label
* @param csvPath Path of the labels.csv file
@ -75,9 +74,10 @@ public class GenreData {
* Counts top X words of all textfiles
* @param paths source plain textfiles
* @param limit only counts the top (limit) words
* @param skipWords number of first words to skip
* @return LinkedMap key: word, value: count
*/
public static Map<String, Integer> countWords(List<String> paths, int limit){
public static Set<String> createAlphabet(List<String> paths, int limit, int skipWords){
// TODO: Scan texts line by line and count already added Words.
// If word was not present, add it to the Map.
Map<String, Integer> allWords = new HashMap<>();
@ -130,9 +130,9 @@ public class GenreData {
return compared != 0 ? compared : a.getKey().compareTo(b.getKey()); // Sort by biggest, when same by ABC
});
Map<String, Integer> topWords = new LinkedHashMap<>();
for(int i = 0; i < Math.min(limit, entries.size()); i++){
topWords.put(entries.get(i).getKey(), entries.get(i).getValue());
Set<String> topWords = new LinkedHashSet<>();
for(int i = skipWords; i < Math.min(limit + skipWords, entries.size()); i++){
topWords.add(entries.get(i).getKey());
}
return topWords;

View File

@ -7,9 +7,8 @@ import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.io.FileNotFoundException;
import java.util.*;
import static org.junit.jupiter.api.Assertions.assertEquals;
@ -51,12 +50,12 @@ public class DetectorTests {
System.out.println("Genres: " + genreData.size());
System.out.println("Total paths: " + allPaths);
Map <String, Integer> vocabulary = GenreData.countWords(allPaths, 500);
Set<String> vocabulary = GenreData.createAlphabet(allPaths, 500, 50);
}
@DisplayName("Count Words against Vocabulary")
@Test
public void testCountWords(){
public void testCountWords() throws FileNotFoundException {
Map<String, List<String>> genreData = GenreData.loadGenres("data/labels.csv");
List<String> allPaths = genreData.values()
.stream()
@ -65,9 +64,11 @@ public class DetectorTests {
System.out.println("Genres: " + genreData.size());
System.out.println("Total paths: " + allPaths);
Map <String, Integer> vocabulary = GenreData.countWords(allPaths, 500);
Set<String> vocabulary = GenreData.createAlphabet(allPaths, 500, 50);
TextCounts textCounts = GenreData.countCommonWords(new File("data/train/adventure/2154_around-the-world-in-eighty-days-junior-deluxe-edit.txt"), vocabulary.keySet());
Scanner scanner = new Scanner(new File("data/train/adventure/2154_around-the-world-in-eighty-days-junior-deluxe-edit.txt"), "UTF-8");
TextCounts textCounts = GenreData.countCommonWords(scanner, vocabulary);
}
@DisplayName("Count training words against Vocabulary")
@ -81,9 +82,9 @@ public class DetectorTests {
System.out.println("Genres: " + genreData.size());
System.out.println("Total paths: " + allPaths);
Map <String, Integer> vocabulary = GenreData.countWords(allPaths, 500);
Set<String> vocabulary = GenreData.createAlphabet(allPaths, 500, 50);
Map<String, List<TextCounts>> trainingCounts = GenreData.countTrainData(genreData, vocabulary.keySet());
Map<String, List<TextCounts>> trainingCounts = GenreData.countTrainData(genreData, vocabulary);
}
@DisplayName("Test Detector Contructor")