eyupipler commited on
Commit
022688b
·
verified ·
1 Parent(s): 4923450

Uploaded bai-64 Mind!

Browse files
v1-BETA/analysis.py ADDED
@@ -0,0 +1,246 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import matplotlib.pyplot as plt
3
+ import seaborn as sns
4
+ from tensorflow import keras
5
+ import pandas as pd
6
+
7
+ class InnerSpeechAnalyzer:
8
+ def __init__(self, model_path='path/to/your/model.h5'):
9
+ try:
10
+ self.model = keras.models.load_model(model_path)
11
+ print(f"Model yüklendi / Model loaded: {model_path}")
12
+ except:
13
+ print(f"Model dosyası bulunamadı / Not found model file: {model_path}")
14
+ self.model = None
15
+
16
+ def analyze_model_architecture(self):
17
+ if self.model is None:
18
+ return
19
+
20
+ print("Model Mimarisi / Model Architecture:")
21
+ print("=" * 50)
22
+ self.model.summary()
23
+
24
+ # Model layer analizi / Model layer analysis
25
+ total_params = self.model.count_params()
26
+ trainable_params = sum([np.prod(v.shape) for v in self.model.trainable_variables])
27
+
28
+ print(f"\nToplam Parametre Sayısı / Total Parameter: {total_params:,}")
29
+ print(f"Eğitilebilir Parametre / Trainable Parameter: {trainable_params:,}")
30
+
31
+ layer_types = {}
32
+ for layer in self.model.layers:
33
+ layer_type = type(layer).__name__
34
+ layer_types[layer_type] = layer_types.get(layer_type, 0) + 1
35
+
36
+ print("\nLayer Türleri:")
37
+ for layer_type, count in layer_types.items():
38
+ print(f" {layer_type}: {count}")
39
+
40
+ def create_real_time_predictor(self):
41
+ if self.model is None:
42
+ print("Model yüklenmemiş! / Model not loaded!")
43
+ return
44
+
45
+ class RealTimePredictor:
46
+ def __init__(self, model):
47
+ self.model = model
48
+ self.classes = ['Up', 'Down', 'Left', 'Right']
49
+
50
+ def predict_thought(self, eeg_data):
51
+ """
52
+ EEG verisinden düşünceyi tahmin eder / Predicts thought from EEG data
53
+
54
+ Args:
55
+ eeg_data: (n_timepoints, n_channels) şeklinde EEG verisi / EEG data in shape (n_timepoints, n_channels)
56
+
57
+ Returns:
58
+ predicted_word: Tahmin edilen kelime / Predicted word
59
+ confidence: Güven skoru / Confidence score
60
+ """
61
+ eeg_batch = np.expand_dims(eeg_data, axis=0) # (1, n_timepoints, n_channels)
62
+
63
+ predictions = self.model.predict(eeg_batch, verbose=0)
64
+
65
+ predicted_class_idx = np.argmax(predictions[0])
66
+ confidence = predictions[0][predicted_class_idx]
67
+ predicted_word = self.classes[predicted_class_idx]
68
+
69
+ return predicted_word, confidence
70
+
71
+ def get_all_predictions(self, eeg_data):
72
+ eeg_batch = np.expand_dims(eeg_data, axis=0)
73
+ predictions = self.model.predict(eeg_batch, verbose=0)
74
+
75
+ results = {}
76
+ for i, class_name in enumerate(self.classes):
77
+ results[class_name] = predictions[0][i]
78
+
79
+ return results
80
+
81
+ predictor = RealTimePredictor(self.model)
82
+ print("Gerçek zamanlı tahminleyici hazır! / Real-time predictor is ready!")
83
+ print("Kullanım: predictor.predict_thought(eeg_data) / Usage: predictor.predict_thought(eeg_data)")
84
+
85
+ return predictor
86
+
87
+ def simulate_brain_computer_interface(self, n_tests=20):
88
+ """
89
+ Beyin-Bilgisayar Arayüzü simülasyonu / Simulates Brain-Computer Interface
90
+ """
91
+ if self.model is None:
92
+ print("Model yüklenmemiş! / Model not loaded!")
93
+ return
94
+
95
+ print("Beyin-Bilgisayar Arayüzü Simülasyonu / Brain-Computer Interface Simulation")
96
+ print("=" * 40)
97
+
98
+ predictor = self.create_real_time_predictor()
99
+ classes = ['Up', 'Down', 'Left', 'Right']
100
+
101
+ results = []
102
+
103
+ for test in range(n_tests):
104
+ # Rastgele gerçek sınıf seç / Randomly select true class
105
+ true_class = np.random.choice(classes)
106
+ true_idx = classes.index(true_class)
107
+
108
+ # Bu sınıf için sentetik EEG verisi oluştur / Generate synthetic EEG data for this class
109
+ n_channels, n_timepoints = 64, 250
110
+ eeg_signal = np.zeros((n_timepoints, n_channels))
111
+
112
+ for channel in range(n_channels):
113
+ t = np.linspace(0, 1, n_timepoints)
114
+
115
+ # Sınıfa özgü aktivasyon paternleri / Class-specific activation patterns
116
+ base_signal = np.sin(2 * np.pi * 10 * t)
117
+
118
+ if true_class == 'Up' and channel < n_channels // 4:
119
+ base_signal *= 2.0
120
+ elif true_class == 'Down' and channel >= 3 * n_channels // 4:
121
+ base_signal *= 2.0
122
+ elif true_class == 'Left' and channel % 2 == 0:
123
+ base_signal *= 1.5
124
+ elif true_class == 'Right' and channel % 2 == 1:
125
+ base_signal *= 1.5
126
+
127
+ # Gürültü ekle / Add noise
128
+ noise = 0.1 * np.random.randn(n_timepoints)
129
+ eeg_signal[:, channel] = base_signal + noise
130
+
131
+ # Tahmin yap / Make prediction
132
+ predicted_word, confidence = predictor.predict_thought(eeg_signal)
133
+
134
+ results.append({
135
+ 'test_no': test + 1,
136
+ 'true_class': true_class,
137
+ 'predicted_class': predicted_word,
138
+ 'confidence': confidence,
139
+ 'correct': true_class == predicted_word
140
+ })
141
+
142
+ print(f"Test {test+1:2d}: Gerçek / Real={true_class:>5}, Tahmin / Prediction={predicted_word:>5}, "
143
+ f"Güven / Confidence={confidence:.3f}, {'✓' if true_class == predicted_word else '✗'}")
144
+
145
+ df_results = pd.DataFrame(results)
146
+ accuracy = df_results['correct'].mean()
147
+ avg_confidence = df_results['confidence'].mean()
148
+
149
+ print(f"\nSonuçlar / Results:")
150
+ print(f"Doğruluk / Accuracy: {accuracy:.3f} ({accuracy*100:.1f}%)")
151
+ print(f"Ortalama Güven / Average Confidence: {avg_confidence:.3f}")
152
+
153
+ print(f"\nSınıf Bazlı Performans / Class Based Performance:")
154
+ for class_name in classes:
155
+ class_results = df_results[df_results['true_class'] == class_name]
156
+ class_accuracy = class_results['correct'].mean() if len(class_results) > 0 else 0
157
+ print(f" {class_name}: {class_accuracy:.3f}")
158
+
159
+ return df_results
160
+
161
+ def create_visualization_dashboard(self):
162
+ """
163
+ Model performansı için görselleştirme dashboard'u / Creates a visualization dashboard for model performance
164
+ """
165
+ print("Model Analiz Dashboard'u / Model Analysis Dashboard")
166
+ print("=" * 30)
167
+
168
+ results_df = self.simulate_brain_computer_interface(n_tests=100)
169
+
170
+ fig, axes = plt.subplots(2, 2, figsize=(15, 10))
171
+
172
+ # 1. Doğruluk Dağılımı / Accuracy Distribution
173
+ accuracy_by_class = results_df.groupby('true_class')['correct'].mean()
174
+ axes[0, 0].bar(accuracy_by_class.index, accuracy_by_class.values)
175
+ axes[0, 0].set_title('Sınıf Bazlı Doğruluk')
176
+ axes[0, 0].set_ylabel('Doğruluk')
177
+ axes[0, 0].set_ylim(0, 1)
178
+
179
+ # 2. Güven Skoru Dağılımı / Confidence Score Distribution
180
+ axes[0, 1].hist(results_df['confidence'], bins=20, alpha=0.7)
181
+ axes[0, 1].set_title('Güven Skoru Dağılımı / Confidence Score Distribution')
182
+ axes[0, 1].set_xlabel('Güven Skoru / Confidence Score')
183
+ axes[0, 1].set_ylabel('Frekans / Frequency')
184
+
185
+ # 3. Confusion Matrix
186
+ from sklearn.metrics import confusion_matrix
187
+ cm = confusion_matrix(results_df['true_class'], results_df['predicted_class'],
188
+ labels=['Up', 'Down', 'Left', 'Right'])
189
+
190
+ sns.heatmap(cm, annot=True, fmt='d', cmap='Blues',
191
+ xticklabels=['Up', 'Down', 'Left', 'Right'],
192
+ yticklabels=['Up', 'Down', 'Left', 'Right'],
193
+ ax=axes[1, 0])
194
+ axes[1, 0].set_title('Confusion Matrix')
195
+ axes[1, 0].set_ylabel('Gerçek / True Class')
196
+ axes[1, 0].set_xlabel('Tahmin / Predicted Class')
197
+
198
+ # 4. Güven vs Doğruluk / Confidence vs Accuracy
199
+ correct_confidences = results_df[results_df['correct'] == True]['confidence']
200
+ wrong_confidences = results_df[results_df['correct'] == False]['confidence']
201
+
202
+ axes[1, 1].hist([correct_confidences, wrong_confidences],
203
+ bins=15, alpha=0.7, label=['Doğru', 'Yanlış'])
204
+ axes[1, 1].set_title('Güven Skoru: Doğru vs Yanlış Tahminler / Confidence Score: Correct vs Incorrect Predictions')
205
+ axes[1, 1].set_xlabel('Güven Skoru / Confidence Score')
206
+ axes[1, 1].set_ylabel('Frekans / Frequency')
207
+ axes[1, 1].legend()
208
+
209
+ plt.tight_layout()
210
+ plt.savefig('dashboard.png', dpi=300, bbox_inches='tight')
211
+ plt.close()
212
+
213
+ print("Dashboard kaydedildi / Dashboard saved: dashboard.png")
214
+
215
+ return results_df
216
+
217
+ def main():
218
+ """
219
+ Ana analiz fonksiyonu / Main analysis function
220
+ """
221
+ print("bai-64 Mind Model Analizi / bai-64 Mind Model Analysis")
222
+ print("=" * 40)
223
+
224
+ analyzer = InnerSpeechAnalyzer('path/to/your/model.h5')
225
+
226
+ if analyzer.model is not None:
227
+ # Model mimarisini analiz et / Analyze model architecture
228
+ analyzer.analyze_model_architecture()
229
+
230
+ print("\n" + "="*50)
231
+
232
+ # Gerçek zamanlı tahminleyici oluştur / Create real-time predictor
233
+ predictor = analyzer.create_real_time_predictor()
234
+
235
+ print("\n" + "="*50)
236
+
237
+ # Beyin-bilgisayar arayüzü simülasyonu / Simulate brain-computer interface
238
+ analyzer.create_visualization_dashboard()
239
+
240
+ print("\nAnaliz tamamlandı! Görselleştirmeler kaydedildi. / Analysis completed! Visualizations saved.")
241
+
242
+ else:
243
+ print("Model dosyası bulunamadı. Önce modeli eğitin. / Model file not found. Train the model first.")
244
+
245
+ if __name__ == "__main__":
246
+ main()
v1-BETA/bai-64 Mind v1.h5 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:240e8cedce8ec49f5daca3e435ab69ba3587559a46edbfcf7155368663376652
3
+ size 5731672
v1-BETA/requirements.txt ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ tensorflow>=2.8.0,<3.0.0
2
+ scikit-learn>=1.0.0
3
+ numpy>=1.21.0
4
+ scipy>=1.7.0
5
+ pandas>=1.3.0
6
+ mne>=1.0.0
7
+ matplotlib>=3.5.0
8
+ seaborn>=0.11.0