File size: 4,217 Bytes
bd035eb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
import gradio as gr
import torch
import numpy as np
import plotly.graph_objects as go
from cognitive_net import DynamicCognitiveNet

class ModelDemo:
    def __init__(self):
        self.net = DynamicCognitiveNet(input_size=5, output_size=1)
        self.training_history = []
        self.emotional_history = []
        
    def train_sequence(self, sequence_str, epochs):
        """Train model on input sequence and return visualizations"""
        try:
            # Parse input sequence
            sequence = [float(x.strip()) for x in sequence_str.split(',')]
            if len(sequence) < 6:
                return "Error: Please input at least 6 numbers", None, None
            
            # Prepare training data
            X = torch.tensor(sequence[:-1]).float()
            y = torch.tensor([sequence[-1]]).float()
            
            # Training loop
            losses = []
            emotions = []
            for epoch in range(epochs):
                loss = self.net.train_step(X, y)
                losses.append(loss)
                emotions.append(self.net.emotional_state.item())
            
            # Create loss plot
            loss_fig = go.Figure()
            loss_fig.add_trace(go.Scatter(y=losses, name='Loss'))
            loss_fig.update_layout(title='Training Loss', 
                                 xaxis_title='Epoch',
                                 yaxis_title='Loss')
            
            # Create emotion plot
            emotion_fig = go.Figure()
            emotion_fig.add_trace(go.Scatter(y=emotions, name='Emotional State'))
            emotion_fig.update_layout(title='Emotional State', 
                                    xaxis_title='Epoch',
                                    yaxis_title='Value')
            
            # Make prediction
            with torch.no_grad():
                pred = self.net(X)
                result = f"Prediction: {pred.item():.4f} (Target: {y.item():.4f})"
            
            return result, loss_fig, emotion_fig
            
        except Exception as e:
            return f"Error: {str(e)}", None, None
    
    def visualize_memory(self):
        """Visualize memory importance weights"""
        memories = []
        importances = []
        
        for mem in self.net.nodes['input_0'].memory.memory_queue:
            memories.append(mem['context'].numpy())
            importances.append(mem['importance'].item())
            
        if not memories:
            return "No memories stored yet"
            
        fig = go.Figure()
        fig.add_trace(go.Bar(y=importances))
        fig.update_layout(title='Memory Importance',
                         xaxis_title='Memory Index',
                         yaxis_title='Importance')
        return fig

# Initialize demo
demo = ModelDemo()

# Create Gradio interface
with gr.Blocks(title="Cognitive Network Demo") as iface:
    gr.Markdown("""
    # Cognitive Network Interactive Demo
    
    This demo shows a neural network with:
    - Dynamic memory
    - Emotional modulation
    - Adaptive structure
    
    Enter a sequence of numbers (comma-separated) to train the model to predict the next number.
    """)
    
    with gr.Row():
        with gr.Column():
            input_seq = gr.Textbox(label="Input Sequence (comma-separated)", 
                                 value="1, 2, 3, 4, 5, 6")
            epochs = gr.Slider(minimum=10, maximum=500, value=100, 
                             step=10, label="Training Epochs")
            train_btn = gr.Button("Train Model")
        
        result_text = gr.Textbox(label="Prediction Result")
    
    with gr.Row():
        loss_plot = gr.Plot(label="Training Loss")
        emotion_plot = gr.Plot(label="Emotional State")
    
    with gr.Row():
        memory_btn = gr.Button("Visualize Memory")
        memory_plot = gr.Plot(label="Memory Importance")
    
    # Connect components
    train_btn.click(
        fn=demo.train_sequence,
        inputs=[input_seq, epochs],
        outputs=[result_text, loss_plot, emotion_plot]
    )
    
    memory_btn.click(
        fn=demo.visualize_memory,
        inputs=None,
        outputs=memory_plot
    )

# Launch app
iface.launch()