Rkruemmel commited on
Commit
6481b89
·
verified ·
1 Parent(s): f986136

Upload 5 files

Browse files
Files changed (6) hide show
  1. .gitattributes +1 -0
  2. README.md +58 -3
  3. doku.md +1286 -0
  4. gradio_app.py +161 -0
  5. model_with_qa.json +3 -0
  6. warum.md +25 -0
.gitattributes CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ model_with_qa.json filter=lfs diff=lfs merge=lfs -text
README.md CHANGED
@@ -1,3 +1,58 @@
1
- ---
2
- license: lgpl-3.0
3
- ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ **Programmübersicht: DRLCogNet – Ein dynamisches, lernfähiges kognitives Netzwerk**
2
+
3
+ DRLCogNet ist ein fortschrittliches Softwareprogramm, das ein dynamisches, sich selbst optimierendes kognitives Netzwerk simuliert. Es wurde entwickelt, um komplexe Informationen zu verarbeiten, Zusammenhänge zu erkennen und auf der Grundlage des Erlernten Entscheidungen zu treffen, die an menschliches Verhalten angelehnt sind. Das Programm vereint Methoden des Deep Reinforcement Learning, der Neurobiologie und der kognitiven Wissenschaft, um eine hochflexible und adaptive Intelligenz zu schaffen.
4
+
5
+ **Kernfunktionen und Innovationen:**
6
+
7
+ 1. **Dynamische Netzwerktopologie:**
8
+ * **Anpassbare Struktur:** Das Netzwerk besteht aus miteinander verbundenen Knoten, die Kategorien und Fragen darstellen. Diese Verbindungen passen sich dynamisch an, basierend auf der Häufigkeit und Relevanz der Interaktionen.
9
+ * **Causale Beziehungen:** DRLCogNet analysiert kausale Beziehungen zwischen den Knoten, was zu einem besseren Verständnis von Zusammenhängen und Abhängigkeiten führt.
10
+ * **Erweiterbar:** Neue Kategorien und Fragen können jederzeit hinzugefügt werden, wodurch das Wissen des Netzwerks kontinuierlich erweitert wird.
11
+
12
+ 2. **Fortgeschrittene Lernmechanismen:**
13
+ * **Hebbsches Lernen:** Die Stärke der Verbindungen zwischen Knoten wird durch eine erweiterte Hebbsche Lernregel modifiziert. Verbindungen, die durch häufige Aktivierung gestärkt werden, werden stärker gewichtet, während inaktive Verbindungen mit der Zeit abgebaut werden (decay).
14
+ * **Kontextabhängiges Lernen:** Das Lernen wird durch externe Faktoren und Kontexte beeinflusst, was zu einer adaptiveren Informationsverarbeitung führt.
15
+ * **Emotionales Lernen:** Emotionale Zustände und Gewichtungen beeinflussen die Art und Weise, wie Informationen verarbeitet und Entscheidungen getroffen werden, wodurch ein realistischeres Verhaltensmodell entsteht.
16
+ * **Sozialer Einfluss:** Das Netzwerk ist in der Lage, sozialen Einfluss zu simulieren, wodurch es sich an gruppenspezifisches Wissen und Präferenzen anpassen kann.
17
+
18
+ 3. **Multilevel-Memory-System:**
19
+ * **Kurz-, Mittel- und Langzeitgedächtnis:** Das System simuliert verschiedene Gedächtnisebenen, wobei Informationen dynamisch zwischen diesen Ebenen verschoben werden. Wichtige Informationen werden im Langzeitgedächtnis gespeichert, während unwichtige Details mit der Zeit verblassen.
20
+
21
+ 4. **Kreative und kritische Denkprozesse:**
22
+ * **Cortex Creativus:** Das System generiert neue Ideen, basierend auf den aktuellen Aktivierungszuständen des Netzwerks.
23
+ * **Cortex Criticus:** Ideen werden bewertet und bewertet, wodurch eine Iteration zur Verbesserung und Optimierung der Lösungen ermöglicht wird.
24
+ * **Simulatrix Neuralis:** Das System ist in der Lage, Szenarien zu simulieren, um verschiedene Resultate und Optionen zu bewerten.
25
+
26
+ 5. **Benutzerfreundliche Schnittstelle:**
27
+ * **Dashboard:** Ein interaktives Dashboard bietet einen visuellen Einblick in die Aktivierungshistorie, die Gedächtnisverteilung und die Netzwerktopologie.
28
+ * **Einfache Bedienung:** Das Programm wurde mit einer einfachen Bedienung entwickelt, die auch für nicht-technische Benutzer geeignet ist.
29
+ * **Anpassbare Parameter:** Parameter wie Lernrate, Verfallsrate, Belohnungsintervalle usw. können vom Benutzer angepasst werden.
30
+
31
+ **Technische Details:**
32
+
33
+ * **Python-basiert:** Das Programm ist in Python geschrieben und nutzt verschiedene Bibliotheken, darunter Pandas, NumPy, NetworkX, Seaborn, PyTorch und Tkinter.
34
+ * **Datenverarbeitung:** Die Daten werden aus CSV-Dateien geladen und mit Methoden der Data-Science vorbereitet.
35
+ * **Modellspeicherung:** Das trainierte Modell kann gespeichert und geladen werden, was es ermöglicht, den Lernprozess kontinuierlich fortzusetzen.
36
+ * **Skalierbarkeit:** Mit der Dask-Bibliothek können große Datenmengen effizient verarbeitet werden.
37
+ * **Logging:** Ein umfassendes Logging-System dokumentiert alle relevanten Prozesse des Lernens und der Netzwerkaktivität.
38
+
39
+ **Potenzielle Anwendungen:**
40
+
41
+ * **Personalisierte Bildung:** DRLCogNet könnte eingesetzt werden, um Lernplattformen zu entwickeln, die sich individuell an die Bedürfnisse und das Lerntempo der Schüler anpassen.
42
+ * **Kundenbetreuung:** Das System kann als Chatbot oder virtueller Assistent dienen, der Kundenanfragen versteht und auf der Basis seiner Erfahrungen adäquate Antworten gibt.
43
+ * **Entscheidungsfindung:** Die Analyse kausaler Beziehungen kann Unternehmen helfen, fundierte Entscheidungen zu treffen.
44
+ * **Medizinische Diagnose:** Durch die Analyse von Patientendaten kann DRLCogNet helfen, Muster zu erkennen, die bei der Diagnose von Krankheiten hilfreich sein können.
45
+ * **Forschung:** Das System kann als Forschungswerkzeug dienen, um das menschliche Denken und Verhalten zu simulieren und zu studieren.
46
+
47
+ **Investitionspotenzial:**
48
+
49
+ * **Innovative Technologie:** DRLCogNet ist eine innovative Technologie mit erheblichem Marktpotenzial.
50
+ * **Anpassbarkeit:** Das System kann an unterschiedliche Anforderungen und Branchen angepasst werden.
51
+ * **Echtzeit-Lernen:** Das dynamische Lernen und die Anpassungsfähigkeit ermöglichen Echtzeit-Reaktionen auf Veränderungen.
52
+ * **Skalierbarkeit:** Das System kann auf großen Datensätzen trainiert werden.
53
+ * **Wachstumspotential:** Es gibt ein großes Wachstumspotential im Bereich der KI- und kognitiven Technologien.
54
+
55
+ **Zusammenfassung:**
56
+
57
+ DRLCogNet ist ein vielversprechendes Projekt, das durch seine innovative Technologie und die breiten Anwendungsbereiche hervorsticht. Es kombiniert bewährte und neuartige Ansätze, um eine dynamische, adaptive und lernfähige Intelligenz zu schaffen, die in vielen Branchen und Bereichen eingesetzt werden kann. Es bietet ein erhebliches Wachstumspotenzial und kann zu neuen Entwicklungen im Bereich der künstlichen Intelligenz führen.
58
+
doku.md ADDED
@@ -0,0 +1,1286 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Code-Dokumentation
2
+
3
+ ## Einführung
4
+
5
+ Dieses Dokument beschreibt den Code zur Verarbeitung und Simulation von Daten aus einer CSV-Datei, die in einem neuronalen Netzwerk verwendet werden. Der Code umfasst Funktionen zur Initialisierung des Netzwerks, zur Verarbeitung der CSV-Datei, zur Simulation des Lernprozesses und zur Speicherung und Laden des Modells.
6
+
7
+ ## Abhängigkeiten
8
+
9
+ - `pandas`: Zur Verarbeitung von CSV-Dateien.
10
+ - `numpy`: Für numerische Operationen.
11
+ - `random`: Für zufällige Operationen.
12
+ - `tqdm`: Für Fortschrittsanzeigen.
13
+ - `tkinter`: Für die grafische Benutzeroberfläche.
14
+ - `seaborn`: Für die Visualisierung.
15
+ - `networkx`: Für die Erstellung und Analyse von Graphen.
16
+ - `json`: Für die Speicherung und das Laden von Modellen.
17
+ - `os`: Für Dateioperationen.
18
+ - `time`: Für Zeitmessungen.
19
+ - `torch`: Für neuronale Netzwerke.
20
+ - `threading`: Für die Verwaltung von Threads.
21
+ - `logging`: Für die Protokollierung.
22
+ - `sqlite3`: Für die Verwendung von SQLite-Datenbanken.
23
+ - `dask.dataframe`: Für die parallele Verarbeitung von Daten.
24
+
25
+ ## Konfiguration des Loggers
26
+
27
+ ```python
28
+ logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
29
+ ```
30
+
31
+ ## Globale Variablen
32
+
33
+ - `initialized`: Überprüft, ob das Netzwerk initialisiert wurde.
34
+ - `category_nodes`: Liste der Knoten im Netzwerk.
35
+ - `questions`: Liste der Fragen.
36
+ - `model_saved`: Schutzvariable, um zu überprüfen, ob das Modell gespeichert wurde.
37
+
38
+ ## Überprüfen, ob der Ordner existiert
39
+
40
+ ```python
41
+ output_dir = "plots"
42
+ if not os.path.exists(output_dir):
43
+ os.makedirs(output_dir)
44
+ ```
45
+
46
+ ## Funktionen
47
+
48
+ ### Funktion zum Aufteilen der CSV-Datei
49
+
50
+ ```python
51
+ def split_csv(filename, chunk_size=1000, output_dir="data"):
52
+ if not os.path.exists(output_dir):
53
+ os.makedirs(output_dir)
54
+
55
+ chunk_iter = pd.read_csv(filename, chunksize=chunk_size)
56
+ for i, chunk in enumerate(chunk_iter):
57
+ chunk.to_csv(os.path.join(output_dir, f"data_part_{i}.csv"), index=False)
58
+ logging.info(f"Chunk {i} mit {len(chunk)} Zeilen gespeichert.")
59
+ ```
60
+
61
+ ### Verbesserung 1: Verstärkung der Verbindungen bei häufig gestellten Fragen
62
+
63
+ ```python
64
+ def strengthen_question_connection(category_nodes, question, category):
65
+ category_node = next((node for node in category_nodes if node.label == category), None)
66
+ if category_node:
67
+ for conn in category_node.connections:
68
+ if conn.target_node.label == question:
69
+ old_weight = conn.weight
70
+ conn.weight += 0.1 # Verstärkung der Verbindung
71
+ conn.weight = np.clip(conn.weight, 0, 1.0)
72
+ logging.info(f"Verstärkte Verbindung für Frage '{question}' in Kategorie '{category}': {old_weight:.4f} -> {conn.weight:.4f}")
73
+ ```
74
+
75
+ ### Verbesserung 2: Erweiterte Hebb'sche Lernregel zur besseren Zuordnung von Fragen
76
+
77
+ ```python
78
+ def enhanced_hebbian_learning(node, target_node, learning_rate=0.2, decay_factor=0.01):
79
+ old_weight = None
80
+ for conn in node.connections:
81
+ if conn.target_node == target_node:
82
+ old_weight = conn.weight
83
+ conn.weight += learning_rate * node.activation * target_node.activation
84
+ conn.weight = np.clip(conn.weight - decay_factor * conn.weight, 0, 1.0)
85
+ break
86
+
87
+ if old_weight is not None:
88
+ logging.info(f"Hebb'sches Lernen angewendet: Gewicht {old_weight:.4f} -> {conn.weight:.4f}")
89
+ ```
90
+
91
+ ### Verbesserung 3: Simulation der Frageverarbeitung im Netzwerk
92
+
93
+ ```python
94
+ def simulate_question_answering(category_nodes, question, questions):
95
+ category = next((q['category'] for q in questions if q['question'] == question), None)
96
+ if not category:
97
+ logging.warning(f"Frage '{question}' nicht gefunden!")
98
+ return None
99
+
100
+ category_node = next((node for node in category_nodes if node.label == category), None)
101
+ if category_node:
102
+ propagate_signal(category_node, input_signal=0.9, emotion_weights={}, emotional_state=1.0)
103
+ activation = category_node.activation
104
+ if activation is None or activation <= 0:
105
+ logging.warning(f"Kategorie '{category}' hat eine ungültige Aktivierung: {activation}")
106
+ return 0.0 # Rückgabe von 0, falls die Aktivierung fehlschlägt
107
+ logging.info(f"Verarbeite Frage: '{question}' → Kategorie: '{category}' mit Aktivierung {activation:.4f}")
108
+ return activation # Entfernte doppelte Logging-Ausgabe
109
+ else:
110
+ logging.warning(f"Kategorie '{category}' nicht im Netzwerk gefunden. Die Kategorie wird neu hinzugefügt!")
111
+ return 0.0
112
+ ```
113
+
114
+ ### Verbesserung 4: Finden der besten passenden Frage zur Benutzeranfrage
115
+
116
+ ```python
117
+ def find_question_by_keyword(questions, keyword):
118
+ matching_questions = [q for q in questions if keyword.lower() in q['question'].lower()]
119
+ return matching_questions if matching_questions else None
120
+ ```
121
+
122
+ ### Verbesserung 5: Suche nach der ähnlichsten Frage basierend auf einfachen Ähnlichkeitsmetriken
123
+
124
+ ```python
125
+ def find_similar_question(questions, query):
126
+ from difflib import get_close_matches
127
+ question_texts = [q['question'] for q in questions]
128
+ closest_matches = get_close_matches(query, question_texts, n=1, cutoff=0.6)
129
+
130
+ if closest_matches:
131
+ matched_question = next((q for q in questions if q['question'] == closest_matches[0]), None)
132
+ return matched_question
133
+ else:
134
+ return {"question": "Keine passende Frage gefunden", "category": "Unbekannt"}
135
+ ```
136
+
137
+ ### Verbesserung 6: Testfunktion zur Überprüfung des Modells
138
+
139
+ ```python
140
+ def test_model(category_nodes, questions, query):
141
+ matched_question = find_question_by_keyword(questions, query)
142
+ if matched_question:
143
+ logging.info(f"Gefundene Frage: {matched_question[0]['question']} -> Kategorie: {matched_question[0]['category']}")
144
+ simulate_question_answering(category_nodes, matched_question[0]['question'], questions)
145
+ else:
146
+ logging.warning("Keine passende Frage gefunden.")
147
+
148
+ similarity_question = find_similar_question(questions, query)
149
+ logging.info(f"Ähnlichste Frage: {similarity_question['question']} -> Kategorie: {similarity_question['category']}")
150
+ ```
151
+
152
+ ### NetworkX-Funktionen für kausale Graphen
153
+
154
+ ```python
155
+ def build_causal_graph(category_nodes):
156
+ G = nx.DiGraph()
157
+ for node in category_nodes:
158
+ G.add_node(node.label)
159
+ for conn in node.connections:
160
+ G.add_edge(node.label, conn.target_node.label, weight=conn.weight)
161
+ return G
162
+
163
+ def analyze_causality_multiple(G, num_pairs=3):
164
+ if len(G.nodes) < 2:
165
+ logging.warning("Graph enthält nicht genügend Knoten für eine Analyse.")
166
+ return
167
+
168
+ for _ in range(num_pairs):
169
+ start_node, target_node = random.sample(G.nodes, 2)
170
+ logging.info(f"Analysiere kausale Pfade von '{start_node}' nach '{target_node}'")
171
+
172
+ try:
173
+ paths = list(nx.all_simple_paths(G, source=start_node, target=target_node))
174
+ if paths:
175
+ for path in paths:
176
+ logging.info(f"Kausaler Pfad: {' -> '.join(path)}")
177
+ else:
178
+ logging.info(f"Kein Pfad gefunden von '{start_node}' nach '{target_node}'")
179
+ except nx.NetworkXNoPath:
180
+ logging.warning(f"Kein direkter Pfad zwischen '{start_node}' und '{target_node}' gefunden.")
181
+
182
+ def analyze_node_influence(G):
183
+ influence_scores = nx.pagerank(G, alpha=0.85)
184
+ sorted_influences = sorted(influence_scores.items(), key=lambda x: x[1], reverse=True)
185
+ for node, score in sorted_influences:
186
+ logging.info(f"Knoten: {node}, Einfluss: {score:.4f}")
187
+ ```
188
+
189
+ ### Funktion für Interventionen basierend auf Pearl's Do-Operator
190
+
191
+ ```python
192
+ def do_intervention(node, new_value):
193
+ logging.info(f"Intervention: Setze {node.label} auf {new_value}")
194
+ node.activation = new_value
195
+ for conn in node.connections:
196
+ conn.target_node.activation += node.activation * conn.weight
197
+ ```
198
+
199
+ ### Kontextabhängiges Lernen verstärken
200
+
201
+ ```python
202
+ def contextual_causal_analysis(node, context_factors, learning_rate=0.1):
203
+ context_factor = context_factors.get(node.label, 1.0)
204
+ if node.activation > 0.8 and context_factor > 1.0:
205
+ logging.info(f"Kausale Beziehung verstärkt für {node.label} aufgrund des Kontextes.")
206
+ for conn in node.connections:
207
+ conn.weight += learning_rate * context_factor
208
+ conn.weight = np.clip(conn.weight, 0, 1.0)
209
+ logging.info(f"Gewicht aktualisiert: {node.label} → {conn.target_node.label}, Gewicht: {conn.weight:.4f}")
210
+ ```
211
+
212
+ ### PyTorch-Modell für kausale Inferenz
213
+
214
+ ```python
215
+ class CausalInferenceNN(nn.Module):
216
+ def __init__(self):
217
+ super(CausalInferenceNN, self).__init__()
218
+ self.fc1 = nn.Linear(10, 20)
219
+ self.fc2 = nn.Linear(20, 1)
220
+
221
+ def forward(self, x):
222
+ x = torch.relu(self.fc1(x))
223
+ return self.fc2(x)
224
+ ```
225
+
226
+ ### Debugging-Funktion
227
+
228
+ ```python
229
+ def debug_connections(category_nodes):
230
+ start_time = time.time()
231
+ for node in category_nodes:
232
+ logging.info(f"Knoten: {node.label}")
233
+ for conn in node.connections:
234
+ logging.info(f" Verbindung zu: {conn.target_node.label}, Gewicht: {conn.weight}")
235
+ end_time = time.time()
236
+ logging.info(f"debug_connections Ausführungszeit: {end_time - start_time:.4f} Sekunden")
237
+ ```
238
+
239
+ ### Hilfsfunktionen
240
+
241
+ ```python
242
+ def sigmoid(x):
243
+ return 1 / (1 + np.exp(-x))
244
+
245
+ def add_activation_noise(activation, noise_level=0.1):
246
+ noise = np.random.normal(0, noise_level)
247
+ return np.clip(activation + noise, 0.0, 1.0)
248
+
249
+ def decay_weights(category_nodes, decay_rate=0.002, forgetting_curve=0.95):
250
+ for node in category_nodes:
251
+ for conn in node.connections:
252
+ conn.weight *= (1 - decay_rate) * forgetting_curve
253
+
254
+ def reward_connections(category_nodes, target_category, reward_factor=0.1):
255
+ for node in category_nodes:
256
+ if node.label == target_category:
257
+ for conn in node.connections:
258
+ conn.weight += reward_factor
259
+ conn.weight = np.clip(conn.weight, 0, 1.0)
260
+
261
+ def apply_emotion_weight(activation, category_label, emotion_weights, emotional_state=1.0):
262
+ emotion_factor = emotion_weights.get(category_label, 1.0) * emotional_state
263
+ return activation * emotion_factor
264
+
265
+ def generate_simulated_answers(data, personality_distributions):
266
+ simulated_answers = []
267
+ for _, row in data.iterrows():
268
+ category = row['Kategorie']
269
+ mean = personality_distributions.get(category, 0.5)
270
+ simulated_answer = np.clip(np.random.normal(mean, 0.2), 0.0, 1.0)
271
+ simulated_answers.append(simulated_answer)
272
+ return simulated_answers
273
+
274
+ def social_influence(category_nodes, social_network, influence_factor=0.1):
275
+ for node in category_nodes:
276
+ for conn in node.connections:
277
+ social_impact = sum([social_network.get(conn.target_node.label, 0)]) * influence_factor
278
+ conn.weight += social_impact
279
+ conn.weight = np.clip(conn.weight, 0, 1.0)
280
+
281
+ def update_emotional_state(emotional_state, emotional_change_rate=0.02):
282
+ emotional_state += np.random.normal(0, emotional_change_rate)
283
+ return np.clip(emotional_state, 0.7, 1.5)
284
+
285
+ def apply_contextual_factors(activation, node, context_factors):
286
+ context_factor = context_factors.get(node.label, 1.0)
287
+ return activation * context_factor * random.uniform(0.9, 1.1)
288
+
289
+ def long_term_memory(category_nodes, long_term_factor=0.01):
290
+ for node in category_nodes:
291
+ for conn in node.connections:
292
+ conn.weight += long_term_factor * conn.weight
293
+ conn.weight = np.clip(conn.weight, 0, 1.0)
294
+
295
+ def hebbian_learning(node, learning_rate=0.3, weight_limit=1.0, reg_factor=0.005):
296
+ for connection in node.connections:
297
+ old_weight = connection.weight
298
+ connection.weight += learning_rate * node.activation * connection.target_node.activation
299
+ connection.weight = np.clip(connection.weight, -weight_limit, weight_limit)
300
+ connection.weight -= reg_factor * connection.weight
301
+ node.activation_history.append(node.activation) # Aktivierung speichern
302
+ connection.target_node.activation_history.append(connection.target_node.activation)
303
+ logging.info(f"Hebb'sches Lernen: Gewicht von {old_weight:.4f} auf {connection.weight:.4f} erhöht")
304
+ ```
305
+
306
+ ### Klassen für Netzwerkstruktur
307
+
308
+ ```python
309
+ class Connection:
310
+ def __init__(self, target_node, weight=None):
311
+ self.target_node = target_node
312
+ self.weight = weight if weight is not None else random.uniform(0.1, 1.0)
313
+
314
+ class Node:
315
+ def __init__(self, label):
316
+ self.label = label
317
+ self.connections = []
318
+ self.activation = 0.0
319
+ self.activation_history = []
320
+
321
+ def add_connection(self, target_node, weight=None):
322
+ self.connections.append(Connection(target_node, weight))
323
+
324
+ def save_state(self):
325
+ return {
326
+ "label": self.label,
327
+ "activation": self.activation,
328
+ "activation_history": self.activation_history,
329
+ "connections": [{"target": conn.target_node.label, "weight": conn.weight} for conn in self.connections]
330
+ }
331
+
332
+ @staticmethod
333
+ def load_state(state, nodes_dict):
334
+ node = Node(state["label"])
335
+ node.activation = state["activation"]
336
+ node.activation_history = state["activation_history"]
337
+ for conn_state in state["connections"]:
338
+ target_node = nodes_dict[conn_state["target"]]
339
+ connection = Connection(target_node, conn_state["weight"])
340
+ node.connections.append(connection)
341
+ return node
342
+
343
+ class MemoryNode(Node):
344
+ def __init__(self, label, memory_type="short_term"):
345
+ super().__init__(label)
346
+ self.memory_type = memory_type
347
+ self.retention_time = {"short_term": 5, "mid_term": 20, "long_term": 100}[memory_type]
348
+ self.time_in_memory = 0
349
+
350
+ def decay(self, decay_rate, context_factors, emotional_state):
351
+ context_factor = context_factors.get(self.label, 1.0)
352
+ emotional_factor = emotional_state
353
+ for conn in self.connections:
354
+ if self.memory_type == "short_term":
355
+ conn.weight *= (1 - decay_rate * 2 * context_factor * emotional_factor)
356
+ elif self.memory_type == "mid_term":
357
+ conn.weight *= (1 - decay_rate * context_factor * emotional_factor)
358
+ elif self.memory_type == "long_term":
359
+ conn.weight *= (1 - decay_rate * 0.5 * context_factor * emotional_factor)
360
+
361
+ def promote(self, activation_threshold=0.7):
362
+ if len(self.activation_history) == 0:
363
+ return
364
+ if self.memory_type == "short_term" and np.mean(self.activation_history[-5:]) > activation_threshold:
365
+ self.memory_type = "mid_term"
366
+ self.retention_time = 20
367
+ elif self.memory_type == "mid_term" and np.mean(self.activation_history[-20:]) > activation_threshold:
368
+ self.memory_type = "long_term"
369
+ self.retention_time = 100
370
+
371
+ class CortexCreativus(Node):
372
+ def __init__(self, label):
373
+ super().__init__(label)
374
+
375
+ def generate_new_ideas(self, category_nodes):
376
+ new_ideas = []
377
+ for node in category_nodes:
378
+ if node.activation > 0.5:
379
+ new_idea = f"New idea based on {node.label} with activation {node.activation}"
380
+ new_ideas.append(new_idea)
381
+ return new_ideas
382
+
383
+ class SimulatrixNeuralis(Node):
384
+ def __init__(self, label):
385
+ super().__init__(label)
386
+
387
+ def simulate_scenarios(self, category_nodes):
388
+ scenarios = []
389
+ for node in category_nodes:
390
+ if node.activation > 0.5:
391
+ scenario = f"Simulated scenario based on {node.label} with activation {node.activation}"
392
+ scenarios.append(scenario)
393
+ return scenarios
394
+
395
+ class CortexCriticus(Node):
396
+ def __init__(self, label):
397
+ super().__init__(label)
398
+
399
+ def evaluate_ideas(self, ideas):
400
+ evaluated_ideas = []
401
+ for idea in ideas:
402
+ evaluation_score = random.uniform(0, 1)
403
+ evaluation = f"Evaluated idea: {idea} - Score: {evaluation_score}"
404
+ evaluated_ideas.append(evaluation)
405
+ return evaluated_ideas
406
+
407
+ class LimbusAffectus(Node):
408
+ def __init__(self, label):
409
+ super().__init__(label)
410
+
411
+ def apply_emotion_weight(self, ideas, emotional_state):
412
+ weighted_ideas = []
413
+ for idea in ideas:
414
+ weighted_idea = f"Emotionally weighted idea: {idea} - Weight: {emotional_state}"
415
+ weighted_ideas.append(weighted_idea)
416
+ return weighted_ideas
417
+
418
+ class MetaCognitio(Node):
419
+ def __init__(self, label):
420
+ super().__init__(label)
421
+
422
+ def optimize_system(self, category_nodes):
423
+ for node in category_nodes:
424
+ node.activation *= random.uniform(0.9, 1.1)
425
+
426
+ class CortexSocialis(Node):
427
+ def __init__(self, label):
428
+ super().__init__(label)
429
+
430
+ def simulate_social_interactions(self, category_nodes):
431
+ interactions = []
432
+ for node in category_nodes:
433
+ if node.activation > 0.5:
434
+ interaction = f"Simulated social interaction based on {node.label} with activation {node.activation}"
435
+ interactions.append(interaction)
436
+ return interactions
437
+
438
+ def connect_new_brains_to_network(category_nodes, new_brains):
439
+ for brain in new_brains:
440
+ for node in category_nodes:
441
+ brain.add_connection(node)
442
+ node.add_connection(brain)
443
+ ```
444
+
445
+ ### Netzwerk-Initialisierung
446
+
447
+ ```python
448
+ def initialize_quiz_network(categories):
449
+ try:
450
+ category_nodes = [Node(c) for c in categories]
451
+ for node in category_nodes:
452
+ for target_node in category_nodes:
453
+ if node != target_node:
454
+ node.add_connection(target_node)
455
+ logging.debug(f"Verbindung hinzugefügt: {node.label} → {target_node.label}")
456
+ debug_connections(category_nodes)
457
+ for node in category_nodes:
458
+ logging.info(f"Knoten erstellt: {node.label}")
459
+ for conn in node.connections:
460
+ logging.info(f" → Verbindung zu {conn.target_node.label} mit Gewicht {conn.weight:.4f}")
461
+ return category_nodes
462
+ except Exception as e:
463
+ logging.error(f"Fehler bei der Netzwerk-Initialisierung: {e}")
464
+ return []
465
+ ```
466
+
467
+ ### Signalpropagation
468
+
469
+ ```python
470
+ def propagate_signal(node, input_signal, emotion_weights, emotional_state=1.0, context_factors=None):
471
+ node.activation = add_activation_noise(sigmoid(input_signal * random.uniform(0.8, 1.2)))
472
+ node.activation_history.append(node.activation) # Aktivierung speichern
473
+ node.activation = apply_emotion_weight(node.activation, node.label, emotion_weights, emotional_state)
474
+ if context_factors:
475
+ node.activation = apply_contextual_factors(node.activation, node, context_factors)
476
+ logging.info(f"Signalpropagation für {node.label}: Eingangssignal {input_signal:.4f}")
477
+ for connection in node.connections:
478
+ logging.info(f" → Signal an {connection.target_node.label} mit Gewicht {connection.weight:.4f}")
479
+ connection.target_node.activation += node.activation * connection.weight
480
+
481
+ def propagate_signal_with_memory(node, input_signal, category_nodes, memory_nodes, context_factors, emotional_state):
482
+ node.activation = add_activation_noise(sigmoid(input_signal))
483
+ node.activation_history.append(node.activation)
484
+ for connection in node.connections:
485
+ connection.target_node.activation += node.activation * connection.weight
486
+ for memory_node in memory_nodes:
487
+ memory_node.time_in_memory += 1
488
+ memory_node.promote()
489
+ ```
490
+
491
+ ### Simulation mit Anpassungen
492
+
493
+ ```python
494
+ def simulate_learning(data, category_nodes, personality_distributions, epochs=1, learning_rate=0.8, reward_interval=5, decay_rate=0.002, emotional_state=1.0, context_factors=None):
495
+ if context_factors is None:
496
+ context_factors = {}
497
+
498
+ weights_history = {f"{node.label} → {conn.target_node.label}": [] for node in category_nodes for conn in node.connections}
499
+ activation_history = {node.label: [] for node in category_nodes}
500
+ question_nodes = []
501
+
502
+ for idx, row in data.iterrows():
503
+ q_node = Node(row['Frage'])
504
+ question_nodes.append(q_node)
505
+ category_label = row['Kategorie'].strip()
506
+ category_node = next((c for c in category_nodes if c.label == category_label), None)
507
+ if category_node:
508
+ q_node.add_connection(category_node)
509
+ logging.debug(f"Verbindung hinzugefügt: {q_node.label} → {category_node.label}")
510
+ else:
511
+ logging.warning(f"Warnung: Kategorie '{category_label}' nicht gefunden für Frage '{row['Frage']}'.")
512
+
513
+ emotion_weights = {category: 1.0 for category in data['Kategorie'].unique()}
514
+ social_network = {category: random.uniform(0.1, 1.0) for category in data['Kategorie'].unique()}
515
+
516
+ for epoch in range(epochs):
517
+ logging.info(f"\n--- Epoche {epoch + 1} ---")
518
+ simulated_answers = generate_simulated_answers(data, personality_distributions)
519
+
520
+ for node in category_nodes:
521
+ node.activation_sum = 0.0
522
+ node.activation_count = 0
523
+
524
+ for node in category_nodes:
525
+ propagate_signal(node, random.uniform(0.1, 0.9), emotion_weights, emotional_state, context_factors)
526
+ node.activation_history.append(node.activation) # Aktivierung speichern
527
+
528
+ for idx, q_node in enumerate(question_nodes):
529
+ for node in category_nodes + question_nodes:
530
+ node.activation = 0.0
531
+ answer = simulated_answers[idx]
532
+ propagate_signal(q_node, answer, emotion_weights, emotional_state, context_factors)
533
+ q_node.activation_history.append(q_node.activation) # Aktivierung speichern
534
+ hebbian_learning(q_node, learning_rate)
535
+
536
+ for node in category_nodes:
537
+ node.activation_sum += node.activation
538
+ if node.activation > 0:
539
+ node.activation_count += 1
540
+
541
+ for node in category_nodes:
542
+ for conn in node.connections:
543
+ weights_history[f"{node.label} → {conn.target_node.label}"].append(conn.weight)
544
+ logging.debug(f"Gewicht aktualisiert: {node.label} → {conn.target_node.label}, Gewicht: {conn.weight}")
545
+
546
+ # Kausalitätsverstärkung anwenden
547
+ contextual_causal_analysis(q_node, context_factors, learning_rate)
548
+
549
+ for node in category_nodes:
550
+ if node.activation_count > 0:
551
+ mean_activation = node.activation_sum / node.activation_count
552
+ activation_history[node.label].append(mean_activation)
553
+ logging.info(f"Durchschnittliche Aktivierung für Knoten {node.label}: {mean_activation:.4f}")
554
+ else:
555
+ activation_history[node.label].append(0.0)
556
+ logging.info(f"Knoten {node.label} wurde in dieser Epoche nicht aktiviert.")
557
+
558
+ if (epoch + 1) % reward_interval == 0:
559
+ target_category = random.choice(data['Kategorie'].unique())
560
+ reward_connections(category_nodes, target_category=target_category)
561
+
562
+ decay_weights(category_nodes, decay_rate=decay_rate)
563
+ social_influence(category_nodes, social_network)
564
+
565
+ logging.info("Simulation abgeschlossen. Ergebnisse werden analysiert...")
566
+ return activation_history, weights_history
567
+ ```
568
+
569
+ ### Simulation mit mehrstufigem Gedächtnis
570
+
571
+ ```python
572
+ def simulate_multilevel_memory(data, category_nodes, personality_distributions, epochs=1):
573
+ short_term_memory = [MemoryNode(c, "short_term") for c in category_nodes]
574
+ mid_term_memory = []
575
+ long_term_memory = []
576
+ memory_nodes = short_term_memory + mid_term_memory + long_term_memory
577
+ context_factors = {question: random.uniform(0.9, 1.1) for question in data['Frage'].unique()}
578
+ emotional_state = 1.0
579
+ for epoch in range(epochs):
580
+ logging.info(f"\n--- Epoche {epoch + 1} ---")
581
+ for node in short_term_memory:
582
+ input_signal = random.uniform(0.1, 1.0)
583
+ propagate_signal_with_memory(node, input_signal, category_nodes, memory_nodes, context_factors, emotional_state)
584
+ for memory_node in memory_nodes:
585
+ memory_node.decay(decay_rate=0.01, context_factors=context_factors, emotional_state=emotional_state)
586
+ for memory_node in memory_nodes:
587
+ memory_node.promote()
588
+ short_term_memory, mid_term_memory, long_term_memory = update_memory_stages(memory_nodes)
589
+ logging.info(f"Epoche {epoch + 1}: Kurzzeit {len(short_term_memory)}, Mittelzeit {len(mid_term_memory)}, Langzeit {len(long_term_memory)}")
590
+ return short_term_memory, mid_term_memory, long_term_memory
591
+
592
+ def update_memory_stages(memory_nodes):
593
+ short_term_memory = [node for node in memory_nodes if node.memory_type == "short_term"]
594
+ mid_term_memory = [node for node in memory_nodes if node.memory_type == "mid_term"]
595
+ long_term_memory = [node for node in memory_nodes if node.memory_type == "long_term"]
596
+ return short_term_memory, mid_term_memory, long_term_memory
597
+ ```
598
+
599
+ ### Plot-Funktionen
600
+
601
+ ```python
602
+ def plot_activation_history(activation_history, filename="activation_history.png"):
603
+ if not activation_history:
604
+ logging.warning("No activation history to plot")
605
+ return
606
+ plt.figure(figsize=(12, 8))
607
+ for label, activations in activation_history.items():
608
+ if len(activations) > 0:
609
+ plt.plot(range(1, len(activations) + 1), activations, label=label)
610
+ plt.title("Entwicklung der Aktivierungen während des Lernens")
611
+ plt.xlabel("Epoche")
612
+ plt.ylabel("Aktivierung")
613
+ plt.legend()
614
+ plt.grid(True)
615
+ plt.savefig(os.path.join(output_dir, filename), dpi=300, bbox_inches="tight")
616
+ plt.close()
617
+ logging.info(f"Plot gespeichert unter: {os.path.join(output_dir, filename)}")
618
+
619
+ def plot_dynamics(activation_history, weights_history, filename="dynamics.png"):
620
+ if not weights_history:
621
+ logging.error("weights_history ist leer.")
622
+ return
623
+
624
+ plt.figure(figsize=(16, 12))
625
+ plt.subplot(2, 2, 1)
626
+ for label, activations in activation_history.items():
627
+ if len(activations) > 0:
628
+ plt.plot(range(1, len(activations) + 1), activations, label=label)
629
+ plt.title("Entwicklung der Aktivierungen während des Lernens")
630
+ plt.xlabel("Epoche")
631
+ plt.ylabel("Aktivierung")
632
+ plt.legend()
633
+ plt.grid(True)
634
+
635
+ plt.subplot(2, 2, 2)
636
+ for label, weights in weights_history.items():
637
+ if len(weights) > 0:
638
+ plt.plot(range(1, len(weights) + 1), weights, label=label, alpha=0.7)
639
+ plt.title("Entwicklung der Verbindungsgewichte während des Lernens")
640
+ plt.xlabel("Epoche")
641
+ plt.ylabel("Gewicht")
642
+ plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left')
643
+ plt.grid(True)
644
+
645
+ plt.savefig(os.path.join(output_dir, filename), dpi=300, bbox_inches="tight")
646
+ plt.close()
647
+ logging.info(f"Plot gespeichert unter: {os.path.join(output_dir, filename)}")
648
+
649
+ def plot_memory_distribution(short_term_memory, mid_term_memory, long_term_memory, filename="memory_distribution.png"):
650
+ counts = [len(short_term_memory), len(mid_term_memory), len(long_term_memory)]
651
+ labels = ["Kurzfristig", "Mittelfristig", "Langfristig"]
652
+ plt.figure(figsize=(8, 6))
653
+ plt.bar(labels, counts, color=["red", "blue", "green"])
654
+ plt.title("Verteilung der Gedächtnisknoten")
655
+ plt.ylabel("Anzahl der Knoten")
656
+ plt.savefig(os.path.join(output_dir, filename), dpi=300, bbox_inches="tight")
657
+ plt.close()
658
+ logging.info(f"Plot gespeichert unter: {os.path.join(output_dir, filename)}")
659
+
660
+ def plot_activation_heatmap(activation_history, filename="activation_heatmap.png"):
661
+ if not activation_history:
662
+ logging.warning("No activation history to plot")
663
+ return
664
+
665
+ min_length = min(len(activations) for activations in activation_history.values())
666
+ truncated_activations = {key: values[:min_length] for key, values in activation_history.items()}
667
+
668
+ plt.figure(figsize=(12, 8))
669
+ heatmap_data = np.array([activations for activations in truncated_activations.values()])
670
+
671
+ if heatmap_data.size == 0:
672
+ logging.error("Heatmap-Daten sind leer. Überprüfen Sie die Aktivierungshistorie.")
673
+ return
674
+
675
+ sns.heatmap(heatmap_data, cmap="YlGnBu", xticklabels=truncated_activations.keys(), yticklabels=False)
676
+ plt.title("Heatmap der Aktivierungswerte")
677
+ plt.xlabel("Kategorie")
678
+ plt.ylabel("Epoche")
679
+ plt.savefig(os.path.join(output_dir, filename), dpi=300, bbox_inches="tight")
680
+ plt.close()
681
+ logging.info(f"Plot gespeichert unter: {os.path.join(output_dir, filename)}")
682
+
683
+ def plot_network_topology(category_nodes, new_brains, filename="network_topology.png"):
684
+ G = nx.DiGraph()
685
+ for node in category_nodes:
686
+ G.add_node(node.label)
687
+ for conn in node.connections:
688
+ G.add_edge(node.label, conn.target_node.label, weight=conn.weight)
689
+ for brain in new_brains:
690
+ G.add_node(brain.label, color='red')
691
+ for conn in brain.connections:
692
+ G.add_edge(brain.label, conn.target_node.label, weight=conn.weight)
693
+
694
+ pos = nx.spring_layout(G)
695
+ edge_labels = {(u, v): d['weight'] for u, v, d in G.edges(data=True)}
696
+ node_colors = [G.nodes[node].get('color', 'skyblue') for node in G.nodes()]
697
+
698
+ nx.draw(G, pos, with_labels=True, node_size=3000, node_color=node_colors, font_size=10, font_weight="bold", edge_color="gray")
699
+ nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels)
700
+ plt.title("Netzwerktopologie")
701
+ plt.savefig(os.path.join(output_dir, filename), dpi=300, bbox_inches="tight")
702
+ plt.close()
703
+ logging.info(f"Plot gespeichert unter: {os.path.join(output_dir, filename)}")
704
+ ```
705
+
706
+ ### Modell speichern und laden
707
+
708
+ ```python
709
+ def save_model(category_nodes, filename="model.json"):
710
+ model_data = {
711
+ "nodes": [node.save_state() for node in category_nodes]
712
+ }
713
+ with open(filename, "w") as file:
714
+ json.dump(model_data, file, indent=4)
715
+ logging.info(f"Modell gespeichert in {filename}")
716
+
717
+ def save_model_with_questions_and_answers(category_nodes, questions, filename="model_with_qa.json"):
718
+ global model_saved
719
+ logging.info("Starte Speichern des Modells...")
720
+
721
+ # Überprüfen, ob Änderungen vorgenommen wurden
722
+ current_model_data = {
723
+ "nodes": [node.save_state() for node in category_nodes],
724
+ "questions": questions
725
+ }
726
+
727
+ if os.path.exists(filename):
728
+ try:
729
+ with open(filename, "r", encoding="utf-8") as file:
730
+ existing_model_data = json.load(file)
731
+ if existing_model_data == current_model_data:
732
+ logging.info("Keine Änderungen erkannt, erneutes Speichern übersprungen.")
733
+ return
734
+ except Exception as e:
735
+ logging.warning(f"Fehler beim Überprüfen des vorhandenen Modells: {e}")
736
+
737
+ # Speichern des aktualisierten Modells
738
+ try:
739
+ with open(filename, "w", encoding="utf-8") as file:
740
+ json.dump(current_model_data, file, indent=4)
741
+ logging.info(f"Modell erfolgreich gespeichert unter {filename}.")
742
+ model_saved = True # Setze auf True nach erfolgreichem Speichern
743
+ except Exception as e:
744
+ logging.error(f"Fehler beim Speichern des Modells: {e}")
745
+
746
+ def load_model_with_questions_and_answers(filename="model_with_qa.json"):
747
+ global initialized
748
+ if initialized:
749
+ logging.info("Modell bereits initialisiert.")
750
+ return None, None
751
+
752
+ if not os.path.exists(filename):
753
+ logging.warning(f"Datei {filename} nicht gefunden. Netzwerk wird initialisiert.")
754
+ return None, None
755
+
756
+ try:
757
+ with open(filename, "r", encoding="utf-8") as file:
758
+ model_data = json.load(file)
759
+
760
+ nodes_dict = {node_data["label"]: Node(node_data["label"]) for node_data in model_data["nodes"]}
761
+
762
+ for node_data in model_data["nodes"]:
763
+ node = nodes_dict[node_data["label"]]
764
+ node.activation = node_data.get("activation", 0.0)
765
+ for conn_state in node_data["connections"]:
766
+ target_node = nodes_dict.get(conn_state["target"])
767
+ if target_node:
768
+ node.add_connection(target_node, conn_state["weight"])
769
+
770
+ questions = model_data.get("questions", [])
771
+ logging.info(f"Modell geladen mit {len(nodes_dict)} Knoten und {len(questions)} Fragen")
772
+ initialized = True
773
+ return list(nodes_dict.values()), questions
774
+
775
+ except json.JSONDecodeError as e:
776
+ logging.error(f"Fehler beim Parsen der JSON-Datei: {e}")
777
+ return None, None
778
+ ```
779
+
780
+ ### Fragen aktualisieren
781
+
782
+ ```python
783
+ def update_questions_with_answers(filename="model_with_qa.json"):
784
+ with open(filename, "r") as file:
785
+ model_data = json.load(file)
786
+
787
+ for question in model_data["questions"]:
788
+ if "answer" not in question:
789
+ question["answer"] = input(f"Gib die Antwort für: '{question['question']}': ")
790
+
791
+ with open(filename, "w") as file:
792
+ json.dump(model_data, file, indent=4)
793
+ logging.info(f"Fragen wurden mit Antworten aktualisiert und gespeichert in {filename}")
794
+ ```
795
+
796
+ ### Beste Antwort finden
797
+
798
+ ```python
799
+ def find_best_answer(category_nodes, questions, query):
800
+ matched_question = find_similar_question(questions, query)
801
+ if matched_question:
802
+ logging.info(f"Gefundene Frage: {matched_question['question']} -> Kategorie: {matched_question['category']}")
803
+ answer = matched_question.get("answer", "Keine Antwort verfügbar")
804
+ logging.info(f"Antwort: {answer}")
805
+ return answer
806
+ else:
807
+ logging.warning("Keine passende Frage gefunden.")
808
+ return None
809
+ ```
810
+
811
+ ### Dashboard erstellen
812
+
813
+ ```python
814
+ def create_dashboard(category_nodes, activation_history, short_term_memory, mid_term_memory, long_term_memory):
815
+ root = tk.Tk()
816
+ root.title("Psyco Dashboard")
817
+
818
+ # Anzeige der Aktivierungshistorie
819
+ activation_frame = ttk.Frame(root, padding="10")
820
+ activation_frame.pack(fill=tk.BOTH, expand=True)
821
+ activation_label = ttk.Label(activation_frame, text="Aktivierungshistorie")
822
+ activation_label.pack()
823
+ if activation_history:
824
+ for label, activations in activation_history.items():
825
+ fig, ax = plt.subplots()
826
+ ax.plot(range(1, len(activations) + 1), activations)
827
+ ax.set_title(label)
828
+ canvas = FigureCanvasTkAgg(fig, master=activation_frame)
829
+ canvas.draw()
830
+ canvas.get_tk_widget().pack()
831
+ else:
832
+ no_data_label = ttk.Label(activation_frame, text="Keine Aktivierungshistorie verfügbar.")
833
+ no_data_label.pack()
834
+
835
+ # Anzeige der Gedächtnisverteilung
836
+ memory_frame = ttk.Frame(root, padding="10")
837
+ memory_frame.pack(fill=tk.BOTH, expand=True)
838
+ memory_label = ttk.Label(memory_frame, text="Gedächtnisverteilung")
839
+ memory_label.pack()
840
+ memory_counts = [len(short_term_memory), len(mid_term_memory), len(long_term_memory)]
841
+ labels = ["Kurzfristig", "Mittelfristig", "Langfristig"]
842
+ fig, ax = plt.subplots()
843
+ ax.bar(labels, memory_counts, color=["red", "blue", "green"])
844
+ ax.set_title("Verteilung der Gedächtnisknoten")
845
+ ax.set_ylabel("Anzahl der Knoten")
846
+ canvas = FigureCanvasTkAgg(fig, master=memory_frame)
847
+ canvas.draw()
848
+ canvas.get_tk_widget().pack()
849
+
850
+ # Anzeige der Netzwerktopologie
851
+ topology_frame = ttk.Frame(root, padding="10")
852
+ topology_frame.pack(fill=tk.BOTH, expand=True)
853
+ topology_label = ttk.Label(topology_frame, text="Netzwerktopologie")
854
+ topology_label.pack()
855
+ G = nx.DiGraph()
856
+ for node in category_nodes:
857
+ G.add_node(node.label)
858
+ for conn in node.connections:
859
+ G.add_edge(node.label, conn.target_node.label, weight=conn.weight)
860
+ pos = nx.spring_layout(G)
861
+ edge_labels = {(u, v): d['weight'] for u, v, d in G.edges(data=True)}
862
+ node_colors = ['skyblue' for _ in G.nodes()]
863
+ fig, ax = plt.subplots()
864
+ nx.draw(G, pos, with_labels=True, node_size=3000, node_color=node_colors, font_size=10, font_weight="bold", edge_color="gray", ax=ax)
865
+ nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels, ax=ax)
866
+ ax.set_title("Netzwerktopologie")
867
+ canvas = FigureCanvasTkAgg(fig, master=topology_frame)
868
+ canvas.draw()
869
+ canvas.get_tk_widget().pack()
870
+
871
+ # Anzeige der Heatmap der Aktivierungswerte
872
+ heatmap_frame = ttk.Frame(root, padding="10")
873
+ heatmap_frame.pack(fill=tk.BOTH, expand=True)
874
+ heatmap_label = ttk.Label(heatmap_frame, text="Heatmap der Aktivierungswerte")
875
+ heatmap_label.pack()
876
+ if activation_history:
877
+ min_length = min(len(activations) for activations in activation_history.values())
878
+ truncated_activations = {key: values[:min_length] for key, values in activation_history.items()}
879
+ heatmap_data = np.array([activations for activations in truncated_activations.values()])
880
+ if heatmap_data.size > 0:
881
+ fig, ax = plt.subplots()
882
+ sns.heatmap(heatmap_data, cmap="YlGnBu", xticklabels=truncated_activations.keys(), yticklabels=False, ax=ax)
883
+ ax.set_title("Heatmap der Aktivierungswerte")
884
+ ax.set_xlabel("Kategorie")
885
+ ax.set_ylabel("Epoche")
886
+ canvas = FigureCanvasTkAgg(fig, master=heatmap_frame)
887
+ canvas.draw()
888
+ canvas.get_tk_widget().pack()
889
+ else:
890
+ no_data_label = ttk.Label(heatmap_frame, text="Heatmap-Daten sind leer. Überprüfen Sie die Aktivierungshistorie.")
891
+ no_data_label.pack()
892
+ else:
893
+ no_data_label = ttk.Label(heatmap_frame, text="Keine Aktivierungshistorie verfügbar.")
894
+ no_data_label.pack()
895
+
896
+ root.mainloop()
897
+ ```
898
+
899
+ ### CSV-Datei verarbeiten
900
+
901
+ ```python
902
+ def process_csv_in_chunks(filename, chunk_size=10000):
903
+ global category_nodes, questions
904
+ logging.info(f"Beginne Verarbeitung der Datei: {filename}")
905
+
906
+ try:
907
+ # Test, ob die Datei existiert
908
+ if not os.path.exists(filename):
909
+ logging.error(f"Datei {filename} nicht gefunden.")
910
+ return None
911
+
912
+ all_chunks = []
913
+ for chunk in pd.read_csv(filename, chunksize=chunk_size, encoding="utf-8", on_bad_lines='skip'):
914
+ logging.info(f"Chunk mit {len(chunk)} Zeilen gelesen.")
915
+ if 'Frage' not in chunk.columns or 'Kategorie' not in chunk.columns or 'Antwort' not in chunk.columns:
916
+ logging.error("CSV-Datei enthält nicht die erwarteten Spalten: 'Frage', 'Kategorie', 'Antwort'")
917
+ return None
918
+
919
+ all_chunks.append(chunk)
920
+
921
+ data = pd.concat(all_chunks, ignore_index=True)
922
+ logging.info(f"Alle Chunks erfolgreich verarbeitet. Gesamtzeilen: {len(data)}")
923
+
924
+ return data
925
+
926
+ except pd.errors.EmptyDataError:
927
+ logging.error("CSV-Datei ist leer.")
928
+ except pd.errors.ParserError as e:
929
+ logging.error(f"Parsing-Fehler in CSV-Datei: {e}")
930
+ except Exception as e:
931
+ logging.error(f"Unerwarteter Fehler beim Verarbeiten der Datei: {e}")
932
+
933
+ return None
934
+ ```
935
+
936
+ ### Einzelne Einträge verarbeiten
937
+
938
+ ```python
939
+ def process_single_entry(question, category, answer):
940
+ global category_nodes, questions
941
+
942
+ # Sicherstellen, dass die globalen Variablen initialisiert sind
943
+ if category_nodes is None:
944
+ category_nodes = []
945
+ logging.warning("Kategorie-Knotenliste war None, wurde nun initialisiert.")
946
+
947
+ if questions is None:
948
+ questions = []
949
+ logging.warning("Fragenliste war None, wurde nun initialisiert.")
950
+
951
+ # Überprüfen, ob die Kategorie bereits vorhanden ist
952
+ if not any(node.label == category for node in category_nodes):
953
+ category_nodes.append(Node(category))
954
+ logging.info(f"Neue Kategorie '{category}' dem Netzwerk hinzugefügt.")
955
+
956
+ # Frage, Kategorie und Antwort zur Liste hinzufügen
957
+ questions.append({"question": question, "category": category, "answer": answer})
958
+ logging.info(f"Neue Frage hinzugefügt: '{question}' -> Kategorie: '{category}'")
959
+ ```
960
+
961
+ ### CSV-Datei mit Dask verarbeiten
962
+
963
+ ```python
964
+ def process_csv_with_dask(filename, chunk_size=10000):
965
+ try:
966
+ ddf = dd.read_csv(filename, blocksize=chunk_size)
967
+ ddf = ddf.astype({'Kategorie': 'category'})
968
+
969
+ for row in ddf.itertuples(index=False, name=None):
970
+ process_single_entry(row[0], row[1], row[2])
971
+
972
+ logging.info("Alle Chunks erfolgreich mit Dask verarbeitet.")
973
+ except Exception as e:
974
+ logging.error(f"Fehler beim Verarbeiten der Datei mit Dask: {e}")
975
+ ```
976
+
977
+ ### In SQLite speichern
978
+
979
+ ```python
980
+ def save_to_sqlite(filename, db_name="dataset.db"):
981
+ conn = sqlite3.connect(db_name)
982
+ chunk_iter = pd.read_csv(filename, chunksize=10000)
983
+ for chunk in chunk_iter:
984
+ chunk.to_sql("qa_data", conn, if_exists="append", index=False)
985
+ logging.info(f"Chunk mit {len(chunk)} Zeilen gespeichert.")
986
+ conn.close()
987
+ logging.info("CSV-Daten wurden erfolgreich in SQLite gespeichert.")
988
+ ```
989
+
990
+ ### Aus SQLite laden
991
+
992
+ ```python
993
+ def load_from_sqlite(db_name="dataset.db"):
994
+ conn = sqlite3.connect(db_name)
995
+ query = "SELECT Frage, Kategorie, Antwort FROM qa_data"
996
+ data = pd.read_sql_query(query, conn)
997
+ conn.close()
998
+ return data
999
+ ```
1000
+
1001
+ ### Teilmodell speichern
1002
+
1003
+ ```python
1004
+ def save_partial_model(filename="partial_model.json"):
1005
+ model_data = {
1006
+ "nodes": [node.save_state() for node in category_nodes],
1007
+ "questions": questions
1008
+ }
1009
+ with open(filename, "w") as file:
1010
+ json.dump(model_data, file, indent=4)
1011
+ logging.info("Teilmodell gespeichert.")
1012
+ ```
1013
+
1014
+ ### CSV-Datei faul laden
1015
+
1016
+ ```python
1017
+ def lazy_load_csv(filename, chunk_size=10000):
1018
+ for chunk in pd.read_csv(filename, chunksize=chunk_size):
1019
+ for _, row in chunk.iterrows():
1020
+ yield row['Frage'], row['Kategorie'], row['Antwort']
1021
+ ```
1022
+
1023
+ ### Hauptfunktion
1024
+
1025
+ ```python
1026
+ def main():
1027
+ start_time = time.time()
1028
+ category_nodes, questions = load_model_with_questions_and_answers("model_with_qa.json")
1029
+
1030
+ if category_nodes is None:
1031
+ csv_file = "data.csv"
1032
+ data = process_csv_in_chunks(csv_file)
1033
+ if data is None:
1034
+ logging.error("Fehler beim Laden der CSV-Datei.")
1035
+ return
1036
+
1037
+ if len(data) > 1000:
1038
+ logging.info("Datei hat mehr als 1000 Zeilen. Aufteilen in kleinere Dateien...")
1039
+ split_csv(csv_file)
1040
+
1041
+ # Verarbeite jede aufgeteilte Datei
1042
+ data_dir = "data"
1043
+ for filename in os.listdir(data_dir):
1044
+ if filename.endswith(".csv"):
1045
+ file_path = os.path.join(data_dir, filename)
1046
+ logging.info(f"Verarbeite Datei: {file_path}")
1047
+
1048
+ data = process_csv_in_chunks(file_path)
1049
+ if data is None:
1050
+ logging.error("Fehler beim Laden der CSV-Datei.")
1051
+ return
1052
+
1053
+ categories = data['Kategorie'].unique()
1054
+ category_nodes = initialize_quiz_network(categories)
1055
+ questions = [{"question": row['Frage'], "category": row['Kategorie'], "answer": row['Antwort']} for _, row in data.iterrows()]
1056
+
1057
+ personality_distributions = {category: random.uniform(0.5, 0.8) for category in [node.label for node in category_nodes]}
1058
+ activation_history, weights_history = simulate_learning(data, category_nodes, personality_distributions)
1059
+
1060
+ save_model_with_questions_and_answers(category_nodes, questions)
1061
+ else:
1062
+ logging.info("Datei hat weniger als 1000 Zeilen. Keine Aufteilung erforderlich.")
1063
+ categories = data['Kategorie'].unique()
1064
+ category_nodes = initialize_quiz_network(categories)
1065
+ questions = [{"question": row['Frage'], "category": row['Kategorie'], "answer": row['Antwort']} for _, row in data.iterrows()]
1066
+
1067
+ personality_distributions = {category: random.uniform(0.5, 0.8) for category in [node.label for node in category_nodes]}
1068
+ activation_history, weights_history = simulate_learning(data, category_nodes, personality_distributions)
1069
+
1070
+ save_model_with_questions_and_answers(category_nodes, questions)
1071
+
1072
+ end_time = time.time()
1073
+ logging.info(f"Simulation abgeschlossen. Gesamtdauer: {end_time - start_time:.2f} Sekunden")
1074
+ ```
1075
+
1076
+ ### Simulation aus der GUI starten
1077
+
1078
+ ```python
1079
+ def run_simulation_from_gui(learning_rate, decay_rate, reward_interval, epochs):
1080
+ global model_saved
1081
+ model_saved = False # Erzwinge das Speichern nach dem Training
1082
+
1083
+ start_time = time.time()
1084
+ csv_file = "data.csv"
1085
+
1086
+ category_nodes, questions = load_model_with_questions_and_answers("model_with_qa.json")
1087
+
1088
+ if category_nodes is None:
1089
+ data = process_csv_in_chunks(csv_file)
1090
+ if not isinstance(data, pd.DataFrame):
1091
+ logging.error("Fehler beim Laden der CSV-Datei. Erwarteter DataFrame wurde nicht zurückgegeben.")
1092
+ return
1093
+
1094
+ if len(data) > 1000:
1095
+ logging.info("Datei hat mehr als 1000 Zeilen. Aufteilen in kleinere Dateien...")
1096
+ split_csv(csv_file)
1097
+
1098
+ # Verarbeite jede aufgeteilte Datei
1099
+ data_dir = "data"
1100
+ for filename in os.listdir(data_dir):
1101
+ if filename.endswith(".csv"):
1102
+ file_path = os.path.join(data_dir, filename)
1103
+ logging.info(f"Verarbeite Datei: {file_path}")
1104
+
1105
+ data = process_csv_in_chunks(file_path)
1106
+ if not isinstance(data, pd.DataFrame):
1107
+ logging.error("Fehler beim Laden der CSV-Datei. Erwarteter DataFrame wurde nicht zurückgegeben.")
1108
+ return
1109
+
1110
+ categories = data['Kategorie'].unique()
1111
+ category_nodes = initialize_quiz_network(categories)
1112
+ questions = [{"question": row['Frage'], "category": row['Kategorie'], "answer": row['Antwort']} for _, row in data.iterrows()]
1113
+
1114
+ personality_distributions = {category: random.uniform(0.5, 0.8) for category in [node.label for node in category_nodes]}
1115
+ activation_history, weights_history = simulate_learning(
1116
+ data, category_nodes, personality_distributions,
1117
+ epochs=int(epochs),
1118
+ learning_rate=float(learning_rate),
1119
+ reward_interval=int(reward_interval),
1120
+ decay_rate=float(decay_rate)
1121
+ )
1122
+
1123
+ save_model_with_questions_and_answers(category_nodes, questions)
1124
+ else:
1125
+ logging.info("Datei hat weniger als 1000 Zeilen. Keine Aufteilung erforderlich.")
1126
+ categories = data['Kategorie'].unique()
1127
+ category_nodes = initialize_quiz_network(categories)
1128
+ questions = [{"question": row['Frage'], "category": row['Kategorie'], "answer": row['Antwort']} for _, row in data.iterrows()]
1129
+
1130
+ personality_distributions = {category: random.uniform(0.5, 0.8) for category in [node.label for node in category_nodes]}
1131
+ activation_history, weights_history = simulate_learning(
1132
+ data, category_nodes, personality_distributions,
1133
+ epochs=int(epochs),
1134
+ learning_rate=float(learning_rate),
1135
+ reward_interval=int(reward_interval),
1136
+ decay_rate=float(decay_rate)
1137
+ )
1138
+
1139
+ save_model_with_questions_and_answers(category_nodes, questions)
1140
+ else:
1141
+ data = process_csv_in_chunks(csv_file)
1142
+ if not isinstance(data, pd.DataFrame):
1143
+ logging.error("Fehler beim Laden der CSV-Datei. Erwarteter DataFrame wurde nicht zurückgegeben.")
1144
+ return
1145
+
1146
+ logging.info(f"Anzahl der Zeilen in der geladenen CSV: {len(data)}")
1147
+
1148
+ personality_distributions = {category: random.uniform(0.5, 0.8) for category in [node.label for node in category_nodes]}
1149
+
1150
+ activation_history, weights_history = simulate_learning(
1151
+ data, category_nodes, personality_distributions,
1152
+ epochs=int(epochs),
1153
+ learning_rate=float(learning_rate),
1154
+ reward_interval=int(reward_interval),
1155
+ decay_rate=float(decay_rate)
1156
+ )
1157
+
1158
+ save_model_with_questions_and_answers(category_nodes, questions)
1159
+
1160
+ end_time = time.time()
1161
+ logging.info(f"Simulation abgeschlossen. Gesamtdauer: {end_time - start_time:.2f} Sekunden")
1162
+ messagebox.showinfo("Ergebnis", f"Simulation abgeschlossen! Dauer: {end_time - start_time:.2f} Sekunden")
1163
+ ```
1164
+
1165
+ ### Netzwerk asynchron initialisieren
1166
+
1167
+ ```python
1168
+ def async_initialize_network():
1169
+ global category_nodes, questions, model_saved
1170
+ logging.info("Starte Initialisierung des Netzwerks...")
1171
+
1172
+ category_nodes, questions = load_model_with_questions_and_answers("model_with_qa.json")
1173
+
1174
+ if category_nodes is None:
1175
+ category_nodes = []
1176
+ logging.warning("Keine gespeicherten Kategorien gefunden. Neues Netzwerk wird erstellt.")
1177
+ model_saved = False # Zurücksetzen der Speicher-Flagge
1178
+
1179
+ if questions is None:
1180
+ questions = []
1181
+ logging.warning("Keine gespeicherten Fragen gefunden. Neues Fragen-Array wird erstellt.")
1182
+ model_saved = False # Zurücksetzen der Speicher-Flagge
1183
+
1184
+ if not category_nodes:
1185
+ csv_file = "data.csv"
1186
+ data = process_csv_in_chunks(csv_file)
1187
+ if isinstance(data, pd.DataFrame):
1188
+ if len(data) > 1000:
1189
+ logging.info("Datei hat mehr als 1000 Zeilen. Aufteilen in kleinere Dateien...")
1190
+ split_csv(csv_file)
1191
+
1192
+ # Verarbeite jede aufgeteilte Datei
1193
+ data_dir = "data"
1194
+ for filename in os.listdir(data_dir):
1195
+ if filename.endswith(".csv"):
1196
+ file_path = os.path.join(data_dir, filename)
1197
+ logging.info(f"Verarbeite Datei: {file_path}")
1198
+
1199
+ data = process_csv_in_chunks(file_path)
1200
+ if isinstance(data, pd.DataFrame):
1201
+ categories = data['Kategorie'].unique()
1202
+ category_nodes = initialize_quiz_network(categories)
1203
+ questions = [{"question": row['Frage'], "category": row['Kategorie'], "answer": row['Antwort']} for _, row in data.iterrows()]
1204
+ logging.info("Netzwerk aus CSV-Daten erfolgreich erstellt.")
1205
+ model_saved = False # Zurücksetzen der Speicher-Flagge
1206
+ else:
1207
+ logging.info("Datei hat weniger als 1000 Zeilen. Keine Aufteilung erforderlich.")
1208
+ categories = data['Kategorie'].unique()
1209
+ category_nodes = initialize_quiz_network(categories)
1210
+ questions = [{"question": row['Frage'], "category": row['Kategorie'], "answer": row['Antwort']} for _, row in data.iterrows()]
1211
+ logging.info("Netzwerk aus CSV-Daten erfolgreich erstellt.")
1212
+ model_saved = False # Zurücksetzen der Speicher-Flagge
1213
+ else:
1214
+ logging.error("Fehler beim Laden der CSV-Daten. Netzwerk konnte nicht initialisiert werden.")
1215
+ return
1216
+
1217
+ save_model_with_questions_and_answers(category_nodes, questions)
1218
+ logging.info("Netzwerk erfolgreich initialisiert.")
1219
+ ```
1220
+
1221
+ ### GUI starten
1222
+
1223
+ ```python
1224
+ def start_gui():
1225
+ def start_simulation():
1226
+ try:
1227
+ threading.Thread(target=run_simulation_from_gui, args=(0.8, 0.002, 5, 10), daemon=True).start()
1228
+ messagebox.showinfo("Info", "Simulation gestartet!")
1229
+ logging.info("Simulation gestartet")
1230
+ except Exception as e:
1231
+ logging.error(f"Fehler beim Start der Simulation: {e}")
1232
+ messagebox.showerror("Fehler", f"Fehler: {e}")
1233
+
1234
+ root = tk.Tk()
1235
+ root.title("DRLCogNet GUI")
1236
+ root.geometry("400x300")
1237
+
1238
+ header_label = tk.Label(root, text="Simulationseinstellungen", font=("Helvetica", 16))
1239
+ header_label.pack(pady=10)
1240
+
1241
+ start_button = tk.Button(root, text="Simulation starten", command=start_simulation)
1242
+ start_button.pack(pady=20)
1243
+
1244
+ root.mainloop()
1245
+ ```
1246
+
1247
+ ### Hauptprogramm
1248
+
1249
+ ```python
1250
+ if __name__ == "__main__":
1251
+ # Starte die Initialisierung in einem Thread
1252
+ threading.Thread(target=async_initialize_network, daemon=True).start()
1253
+ start_gui()
1254
+ ```
1255
+
1256
+ ## Fragen zur Datenbank (SQLite)
1257
+
1258
+ ### Wird die Datenbank im Arbeitsspeicher erstellt?
1259
+
1260
+ Ja, die SQLite-Datenbank wird im Arbeitsspeicher erstellt, wenn die Funktion `save_to_sqlite` aufgerufen wird. Diese Funktion erstellt eine SQLite-Datenbankdatei (standardmäßig `dataset.db`), die im Arbeitsspeicher gespeichert wird, wenn Sie sie nicht an einem anderen Ort speichern.
1261
+
1262
+ ### Wie wird die Datenbank erstellt?
1263
+
1264
+ Die Datenbank wird erstellt, indem eine Verbindung zur SQLite-Datenbank hergestellt wird. Wenn die Datei `dataset.db` nicht existiert, wird sie erstellt. Anschließend werden die Daten aus der CSV-Datei in Chunks gelesen und in die Tabelle `qa_data` der SQLite-Datenbank gespeichert.
1265
+
1266
+ ### Wie werden die Daten in die Datenbank geladen?
1267
+
1268
+ Die Daten werden in Chunks aus der CSV-Datei gelesen und in die Tabelle `qa_data` der SQLite-Datenbank gespeichert. Die Funktion `to_sql` von Pandas wird verwendet, um die Daten in die Datenbank zu schreiben.
1269
+
1270
+ ### Wie werden die Daten aus der Datenbank geladen?
1271
+
1272
+ Die Daten werden aus der Datenbank geladen, indem eine Verbindung zur SQLite-Datenbank hergestellt und eine SQL-Abfrage ausgeführt wird, um die Daten aus der Tabelle `qa_data` zu lesen. Die Funktion `read_sql_query` von Pandas wird verwendet, um die Daten in einen Pandas-DataFrame zu laden.
1273
+
1274
+ ### Beispielcode zur Verwendung der Datenbank
1275
+
1276
+ ```python
1277
+ # Daten in die Datenbank speichern
1278
+ save_to_sqlite("data.csv")
1279
+
1280
+ # Daten aus der Datenbank laden
1281
+ data = load_from_sqlite()
1282
+ ```
1283
+
1284
+ ## Fazit
1285
+
1286
+ Diese Dokumentation bietet eine umfassende Übersicht über den Code und die Verwendung der SQLite-Datenbank zur Speicherung und zum Laden von Daten. Der Code ist modular aufgebaut und ermöglicht die Verarbeitung und Simulation von Daten aus einer CSV-Datei in einem neuronalen Netzwerk. Die SQLite-Datenbank wird im Arbeitsspeicher erstellt und ermöglicht die effiziente Speicherung und das Laden von Daten.
gradio_app.py ADDED
@@ -0,0 +1,161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import gradio as gr
3
+ import time
4
+ import json
5
+
6
+ from main import (
7
+ load_model_with_questions_and_answers,
8
+ simulate_question_answering,
9
+ find_similar_question
10
+ )
11
+
12
+ # Deaktiviere alle Logging-Ausgaben außer kritischen Fehlern
13
+ logging.getLogger().setLevel(logging.CRITICAL)
14
+
15
+ # Modell laden
16
+ category_nodes, questions = load_model_with_questions_and_answers("model_with_qa.json")
17
+
18
+ def test_model_with_answers(category_nodes, questions, query):
19
+ """
20
+ Testet das Modell mit einer Abfrage und gibt die gefundene Frage, Antwort und Gewichtung zurück.
21
+
22
+ Args:
23
+ category_nodes (list): Liste der Kategorie-Knoten.
24
+ questions (list): Liste der Fragen.
25
+ query (str): Die Abfrage, nach der gesucht werden soll.
26
+
27
+ Returns:
28
+ tuple: Die gefundene Frage, Antwort und Gewichtung.
29
+ """
30
+ # Suche nach der ähnlichsten Frage im Modell
31
+ matched_question = find_similar_question(questions, query)
32
+
33
+ if matched_question and matched_question.get('question') != "Keine passende Frage gefunden":
34
+ answer = matched_question.get('answer', 'Keine Antwort verfügbar')
35
+
36
+ # Simulation der Fragebeantwortung (Gewichtung/Aktivierung)
37
+ activation = simulate_question_answering(category_nodes, matched_question['question'], questions)
38
+
39
+ # Rückgabe der relevanten Informationen
40
+ return f"Frage: \"{query}\"", f"Antwort: \"{answer}\"", f"Gewichtung: {activation:.2f}"
41
+ else:
42
+ # Falls keine passende Frage gefunden wurde
43
+ return f"Frage: \"{query}\"", "Antwort: \"Keine passende Frage gefunden\"", "Gewichtung: 0.00"
44
+
45
+ def measure_response_time(func, *args, **kwargs):
46
+ """
47
+ Misst die Zeit, die eine Funktion benötigt, um ausgeführt zu werden, und gibt die Ergebnisse zusammen mit der Zeit zurück.
48
+
49
+ Args:
50
+ func (callable): Die auszuführende Funktion.
51
+ *args: Positionsargumente für die Funktion.
52
+ **kwargs: Schlüsselwortargumente für die Funktion.
53
+
54
+ Returns:
55
+ tuple: Die Ergebnisse der Funktion und die verstrichene Zeit in Millisekunden.
56
+ """
57
+ start_time = time.time()
58
+ result = func(*args, **kwargs)
59
+ end_time = time.time()
60
+ elapsed_time = (end_time - start_time) * 1000 # Umwandlung in Millisekunden
61
+ return result, elapsed_time
62
+
63
+ def extract_questions_and_answers_from_json(input_json, output_txt):
64
+ """
65
+ Extrahiert Fragen und Antworten aus einer JSON-Datei und schreibt sie in eine Textdatei.
66
+
67
+ Args:
68
+ input_json (str): Der Pfad zur Eingabe-JSON-Datei.
69
+ output_txt (str): Der Pfad zur Ausgabe-Textdatei.
70
+ """
71
+ try:
72
+ with open(input_json, mode='r', encoding='utf-8') as jsonfile, open(output_txt, mode='w', encoding='utf-8') as txtfile:
73
+ data = json.load(jsonfile)
74
+ questions = data.get('questions', [])
75
+ for question in questions:
76
+ q = question.get('question', '')
77
+ a = question.get('answer', '')
78
+ if q and a:
79
+ txtfile.write(f'"question": "{q}",\n')
80
+ txtfile.write(f'"answer": "{a}"\n\n')
81
+ print(f"Fragen und Antworten wurden erfolgreich in {output_txt} geschrieben.")
82
+ except FileNotFoundError:
83
+ print(f"Die Datei {input_json} wurde nicht gefunden.")
84
+ except json.JSONDecodeError:
85
+ print(f"Fehler beim Parsen der JSON-Datei {input_json}.")
86
+ except Exception as e:
87
+ print(f"Ein Fehler ist aufgetreten: {e}")
88
+
89
+ def load_questions_and_answers(file_path):
90
+ """
91
+ Lädt Fragen und Antworten aus einer Textdatei.
92
+
93
+ Args:
94
+ file_path (str): Der Pfad zur Textdatei.
95
+
96
+ Returns:
97
+ str: Der Inhalt der Textdatei.
98
+ """
99
+ try:
100
+ with open(file_path, mode='r', encoding='utf-8') as file:
101
+ content = file.read()
102
+ return content
103
+ except FileNotFoundError:
104
+ return "Datei nicht gefunden."
105
+ except Exception as e:
106
+ return f"Fehler beim Lesen der Datei: {e}"
107
+
108
+ # Gradio-Interface
109
+ def gradio_interface(query):
110
+ """
111
+ Gradio-Schnittstelle zur Verarbeitung der Benutzerabfrage.
112
+
113
+ Args:
114
+ query (str): Die Abfrage des Benutzers.
115
+
116
+ Returns:
117
+ tuple: Die gefundene Frage, Antwort, Gewichtung und die verstrichene Zeit in Millisekunden.
118
+ """
119
+ if category_nodes and questions:
120
+ result, elapsed_time = measure_response_time(test_model_with_answers, category_nodes, questions, query)
121
+ return *result, f"Reaktionszeit: {elapsed_time:.2f} ms"
122
+ else:
123
+ logging.critical("Kein Modell gefunden.")
124
+ return "Fehler", "Kein Modell geladen.", "0.00", "Reaktionszeit: 0.00 ms"
125
+
126
+ # Pfade zu den Dateien
127
+ input_json = 'model_with_qa.json'
128
+ output_txt = 'questions_and_answers.txt'
129
+
130
+ # Extrahiere Fragen und Antworten aus der JSON-Datei und speichere sie in der Textdatei
131
+ extract_questions_and_answers_from_json(input_json, output_txt)
132
+
133
+ # Lade die Fragen und Antworten aus der Textdatei
134
+ questions_and_answers_content = load_questions_and_answers(output_txt)
135
+
136
+ # Erstelle das Gradio-Interface
137
+ iface = gr.Interface(
138
+ fn=gradio_interface,
139
+ inputs=gr.Textbox(label="Frage eingeben", placeholder="Stellen Sie eine Frage..."),
140
+ outputs=[
141
+ gr.Textbox(label="Frage"),
142
+ gr.Textbox(label="Antwort"),
143
+ gr.Textbox(label="Gewichtung"),
144
+ gr.Textbox(label="Reaktionszeit")
145
+ ],
146
+ title="Frage-Antwort-Modell",
147
+ description="Stellen Sie eine Frage, und das Modell wird versuchen, eine passende Antwort mit Gewichtung zu finden."
148
+ )
149
+
150
+ # Füge ein aufklappbares Ausgabefenster hinzu, das die Liste der Fragen und Antworten anzeigt
151
+ with gr.Blocks() as demo:
152
+ gr.Markdown("## Frage-Antwort-Modell")
153
+ with gr.Row():
154
+ with gr.Column():
155
+ iface.render()
156
+ with gr.Column():
157
+ gr.Markdown("### Fragen und Antworten")
158
+ gr.Textbox(value=questions_and_answers_content, lines=20, label="Fragen und Antworten", interactive=False)
159
+
160
+ # Starte das Gradio-Interface
161
+ demo.launch()
model_with_qa.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:34eacbaffd1e18ea850939abb13fb2e1f798e363ace16d70d3adf235dc2f8c20
3
+ size 11131278
warum.md ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ **Meine Motivation hinter DRLCogNet: Eine KI gegen den Strom**
2
+
3
+ Ich habe diese KI, die ich DRLCogNet (Deep Reinforcement Learning Cognitive Network) nenne, mit einer tiefen Skepsis gegenüber dem etablierten Paradigma der KI-Entwicklung entworfen. Es schien mir nicht richtig, dass der Zugang zu leistungsfähiger KI von gigantischen Investitionen in Hardware und komplexen, ressourcenintensiven Modellen abhängen sollte. Die gängige Praxis, KI-Modelle an strenge Normen anzupassen, erschien mir einschränkend und wenig förderlich für echte Innovation.
4
+
5
+ Mein Forschungsdrang war getrieben von der Frage: Gibt es eine Alternative? Kann KI auch anders funktionieren, ohne die astronomischen Kosten und den Ressourcenverbrauch, die oft damit einhergehen? Diese Frage hat mich dazu gebracht, die Grenzen des Bekannten zu verlassen und eine neue Richtung einzuschlagen.
6
+
7
+ **DRLCogNet: Mein Anti-Establishment-Ansatz**
8
+
9
+ DRLCogNet ist nicht nur ein weiteres KI-Modell; es ist ein Ergebnis meines Bestrebens, konventionelle Denkweisen zu überwinden. Anstatt einfach den etablierten Pfaden zu folgen, habe ich mich entschieden,:
10
+
11
+ * **Netzwerkstrukturen zu erforschen:** Ich wollte ein Netzwerk entwickeln, das auf einfachen Knoten und Verbindungen basiert, die in der Lage sind, komplexe kognitive Prozesse zu simulieren.
12
+ * **Innovative Lernmechanismen zu implementieren:** DRLCogNet lernt durch Hebb'sches Lernen und weitere an den Neurowissenschaften angelehnten Lernalgorithmen, die ich an meine Bedürfnisse angepasst habe.
13
+ * **Kausale Beziehungen zu untersuchen:** Es war mein Ziel, ein System zu schaffen, das nicht nur Muster erkennt, sondern auch die zugrundeliegenden Ursache-Wirkungs-Beziehungen versteht.
14
+ * **Emotionen und Kontext zu integrieren:** Ich wollte, dass DRLCogNet nicht nur Daten verarbeitet, sondern auch auf Emotionen und Kontextfaktoren reagieren kann, um eine menschlichere Form der Intelligenz anzustreben.
15
+ * **Visualisierung und Interpretierbarkeit zu ermöglichen:** Anstatt ein schwarzer Kasten zu sein, sollte DRLCogNet Einblicke in seine eigenen Prozesse ermöglichen, um seine Entscheidungen nachvollziehbar zu machen.
16
+
17
+ **Das Ergebnis: Eine KI die anders denkt**
18
+
19
+ Das Ergebnis meiner Arbeit ist DRLCogNet, eine KI, die sich bewusst vom Standard abhebt. Es ist ein Netzwerk, das sich durch seine Anpassungsfähigkeit, seine Fähigkeit zu kausalem Denken und seine Berücksichtigung von Kontext und Emotionen auszeichnet. Es ist der Beweis dafür, dass es möglich ist, leistungsfähige KI-Systeme zu entwickeln, die nicht zwangsläufig auf teure Hardware und eine massive Datenverarbeitung angewiesen sind.
20
+
21
+ DRLCogNet ist ein Schritt auf dem Weg zu einer KI, die nicht nur intelligent, sondern auch zugänglicher, effizienter und transparenter ist. Ich bin stolz darauf, dieses Projekt vorzustellen, und hoffe, dass es die Grenzen dessen, was in der KI-Entwicklung möglich ist, erweitert.
22
+
23
+ * **Die kontinuierliche Weiterentwicklung:** Man Drang nach mehr wird mich sicherlich dazu bringen DRLCogNet kontinuierlich zu verbessern und zu erweitern.
24
+
25
+