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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import pandas as pd
3
+ import numpy as np
4
+ import seaborn as sns
5
+ import matplotlib.pyplot as plt
6
+ from sklearn.preprocessing import LabelEncoder, OneHotEncoder, StandardScaler, MinMaxScaler, RobustScaler
7
+ from sklearn.impute import KNNImputer
8
+ from scipy import stats
9
+ import plotly.express as px
10
+ import plotly.graph_objects as go
11
+ from plotly.subplots import make_subplots
12
+ import warnings
13
+ import io
14
+ import base64
15
+ from datetime import datetime
16
+ import json
17
+ import statsmodels.api as sm
18
+ from statsmodels.stats.outliers_influence import variance_inflation_factor
19
+ from scipy.stats import chi2_contingency
20
+
21
+ warnings.filterwarnings('ignore')
22
+
23
+
24
+ class DataAnalyzer:
25
+ def __init__(self):
26
+ self.df = None
27
+ self.numeric_columns = None
28
+ self.categorical_columns = None
29
+
30
+ def load_data(self, file):
31
+ try:
32
+ self.df = pd.read_csv(file.name)
33
+ self._identify_column_types()
34
+ return "Veri başarıyla yüklendi!"
35
+ except Exception as e:
36
+ return f"Hata: {str(e)}"
37
+
38
+ def _identify_column_types(self):
39
+ self.numeric_columns = self.df.select_dtypes(include=[np.number]).columns
40
+ self.categorical_columns = self.df.select_dtypes(include=['object']).columns
41
+
42
+ def get_basic_info(self):
43
+ if self.df is None:
44
+ return "Önce veri yükleyin!"
45
+
46
+ info = []
47
+ info.append("### 1. Temel Veri Bilgileri")
48
+ info.append(f"Satır Sayısı: {self.df.shape[0]}")
49
+ info.append(f"Sütun Sayısı: {self.df.shape[1]}")
50
+
51
+ memory_usage = self.df.memory_usage(deep=True).sum()
52
+ info.append(f"Bellek Kullanımı: {memory_usage / 1024:.2f} KB")
53
+
54
+ # Veri tipleri
55
+ info.append("\n### 2. Veri Tipleri ve Örnekler")
56
+ for column in self.df.columns:
57
+ unique_count = self.df[column].nunique()
58
+ info.append(f"\n{column}:")
59
+ info.append(f" - Tip: {self.df[column].dtype}")
60
+ info.append(f" - Benzersiz Değer Sayısı: {unique_count}")
61
+ info.append(f" - İlk 3 Örnek: {', '.join(map(str, self.df[column].head(3)))}")
62
+
63
+ return "\n".join(info)
64
+
65
+ def analyze_missing_values(self):
66
+ if self.df is None:
67
+ return "Önce veri yükleyin!"
68
+
69
+ missing = pd.DataFrame({
70
+ 'Eksik Sayı': self.df.isnull().sum(),
71
+ 'Eksik Yüzde': (self.df.isnull().sum() / len(self.df) * 100).round(2)
72
+ })
73
+
74
+ # Eksik değer pattern analizi
75
+ missing_patterns = self.df.isnull().value_counts().head()
76
+
77
+ result = "### Eksik Değer Analizi\n\n"
78
+ result += missing.to_string()
79
+ result += "\n\n### Eksik Değer Örüntüleri (İlk 5)\n\n"
80
+ result += missing_patterns.to_string()
81
+
82
+ return result
83
+
84
+ def analyze_outliers(self, method='zscore', threshold=3):
85
+ if self.df is None:
86
+ return "Önce veri yükleyin!"
87
+
88
+ results = []
89
+ results.append("### Aykırı Değer Analizi\n")
90
+
91
+ for column in self.numeric_columns:
92
+ results.append(f"\n{column} analizi:")
93
+
94
+ if method == 'zscore':
95
+ z_scores = np.abs(stats.zscore(self.df[column].dropna()))
96
+ outliers = np.where(z_scores > threshold)[0]
97
+ results.append(f"Z-score metodu ile {len(outliers)} aykırı değer bulundu")
98
+ if len(outliers) > 0:
99
+ results.append(f"Aykırı değerler: {self.df[column].iloc[outliers].values[:5]}...")
100
+
101
+ elif method == 'iqr':
102
+ Q1 = self.df[column].quantile(0.25)
103
+ Q3 = self.df[column].quantile(0.75)
104
+ IQR = Q3 - Q1
105
+ outliers = self.df[(self.df[column] < (Q1 - 1.5 * IQR)) |
106
+ (self.df[column] > (Q3 + 1.5 * IQR))][column]
107
+ results.append(f"IQR metodu ile {len(outliers)} aykırı değer bulundu")
108
+ if len(outliers) > 0:
109
+ results.append(f"Aykırı değerler: {outliers.values[:5]}...")
110
+
111
+ # Temel istatistikler
112
+ stats_data = self.df[column].describe()
113
+ results.append("\nTemel İstatistikler:")
114
+ results.append(stats_data.to_string())
115
+
116
+ return "\n".join(results)
117
+
118
+ def analyze_correlations(self):
119
+ if self.df is None:
120
+ return "Önce veri yükleyin!"
121
+
122
+ # Sayısal değişkenler için korelasyon
123
+ numeric_corr = self.df[self.numeric_columns].corr()
124
+
125
+ # Kategorik değişkenler için Cramer's V
126
+ cat_correlations = []
127
+ for col1 in self.categorical_columns:
128
+ for col2 in self.categorical_columns:
129
+ if col1 < col2:
130
+ contingency = pd.crosstab(self.df[col1], self.df[col2])
131
+ chi2, _, _, _ = chi2_contingency(contingency)
132
+ n = contingency.sum().sum()
133
+ v = np.sqrt(chi2 / (n * min(contingency.shape[0] - 1, contingency.shape[1] - 1)))
134
+ cat_correlations.append(f"{col1} - {col2}: {v:.3f}")
135
+
136
+ result = "### Sayısal Değişkenler Arası Korelasyonlar\n\n"
137
+ result += numeric_corr.round(3).to_string()
138
+
139
+ if cat_correlations:
140
+ result += "\n\n### Kategorik Değişkenler Arası İlişkiler (Cramer's V)\n\n"
141
+ result += "\n".join(cat_correlations)
142
+
143
+ return result
144
+
145
+ def create_visualization(self, plot_type, x_col, y_col=None, color_col=None):
146
+ if self.df is None:
147
+ return None
148
+
149
+ plt.figure(figsize=(10, 6))
150
+
151
+ try:
152
+ if plot_type == 'histogram':
153
+ fig = px.histogram(self.df, x=x_col, color=color_col,
154
+ title=f'{x_col} Histogram')
155
+
156
+ elif plot_type == 'box':
157
+ fig = px.box(self.df, x=x_col, y=y_col, color=color_col,
158
+ title=f'{x_col} - {y_col} Box Plot')
159
+
160
+ elif plot_type == 'scatter':
161
+ fig = px.scatter(self.df, x=x_col, y=y_col, color=color_col,
162
+ title=f'{x_col} vs {y_col} Scatter Plot')
163
+
164
+ elif plot_type == 'bar':
165
+ fig = px.bar(self.df, x=x_col, y=y_col, color=color_col,
166
+ title=f'{x_col} - {y_col} Bar Plot')
167
+
168
+ elif plot_type == 'violin':
169
+ fig = px.violin(self.df, x=x_col, y=y_col, color=color_col,
170
+ title=f'{x_col} - {y_col} Violin Plot')
171
+
172
+ elif plot_type == 'line':
173
+ fig = px.line(self.df, x=x_col, y=y_col, color=color_col,
174
+ title=f'{x_col} - {y_col} Line Plot')
175
+
176
+ elif plot_type == 'heatmap':
177
+ corr = self.df[[x_col, y_col]].corr()
178
+ fig = px.imshow(corr, title='Correlation Heatmap')
179
+
180
+ return fig
181
+
182
+ except Exception as e:
183
+ return f"Görselleştirme oluşturulurken hata: {str(e)}"
184
+
185
+ def feature_importance(self, target_col):
186
+ if self.df is None:
187
+ return "Önce veri yükleyin!"
188
+
189
+ try:
190
+ # Sayısal değişkenler için VIF hesaplama
191
+ X = self.df[self.numeric_columns].drop(columns=[target_col], errors='ignore')
192
+ vif_data = pd.DataFrame()
193
+ vif_data["Feature"] = X.columns
194
+ vif_data["VIF"] = [variance_inflation_factor(X.values, i)
195
+ for i in range(X.shape[1])]
196
+
197
+ result = "### Özellik Önem Analizi\n\n"
198
+ result += "VIF (Variance Inflation Factor) Değerleri:\n"
199
+ result += vif_data.sort_values('VIF', ascending=False).to_string()
200
+
201
+ # Korelasyon bazlı özellik önemi
202
+ if target_col in self.df.columns:
203
+ correlations = self.df[self.numeric_columns].corrwith(self.df[target_col])
204
+ result += "\n\nHedef Değişken ile Korelasyonlar:\n"
205
+ result += correlations.sort_values(ascending=False).to_string()
206
+
207
+ return result
208
+
209
+ except Exception as e:
210
+ return f"Özellik önem analizi sırasında hata: {str(e)}"
211
+
212
+ def statistical_tests(self, column1, column2=None):
213
+ if self.df is None:
214
+ return "Önce veri yükleyin!"
215
+
216
+ results = []
217
+ results.append("### İstatistiksel Test Sonuçları\n")
218
+
219
+ try:
220
+ # Tek değişkenli testler
221
+ if column2 is None:
222
+ # Normallik testi
223
+ stat, p_value = stats.normaltest(self.df[column1].dropna())
224
+ results.append(f"Normallik Testi (D'Agostino and Pearson's):")
225
+ results.append(f"Stat: {stat:.4f}, p-value: {p_value:.4f}")
226
+ results.append(f"Sonuç: {'Normal dağılım' if p_value > 0.05 else 'Normal dağılım değil'}\n")
227
+
228
+ # Temel istatistikler
229
+ desc = self.df[column1].describe()
230
+ results.append("Temel İstatistikler:")
231
+ results.append(desc.to_string())
232
+
233
+ # İki değişkenli testler
234
+ else:
235
+ if column1 in self.numeric_columns and column2 in self.numeric_columns:
236
+ # Pearson korelasyon
237
+ corr, p_value = stats.pearsonr(self.df[column1].dropna(),
238
+ self.df[column2].dropna())
239
+ results.append(f"Pearson Korelasyon:")
240
+ results.append(f"Correlation: {corr:.4f}, p-value: {p_value:.4f}\n")
241
+
242
+ # T-test
243
+ t_stat, p_value = stats.ttest_ind(self.df[column1].dropna(),
244
+ self.df[column2].dropna())
245
+ results.append(f"Bağımsız T-test:")
246
+ results.append(f"T-stat: {t_stat:.4f}, p-value: {p_value:.4f}\n")
247
+
248
+ elif column1 in self.categorical_columns and column2 in self.categorical_columns:
249
+ # Chi-square test
250
+ contingency = pd.crosstab(self.df[column1], self.df[column2])
251
+ chi2, p_value, dof, expected = chi2_contingency(contingency)
252
+ results.append(f"Chi-square Bağımsızlık Testi:")
253
+ results.append(f"Chi2: {chi2:.4f}, p-value: {p_value:.4f}")
254
+
255
+ return "\n".join(results)
256
+
257
+ except Exception as e:
258
+ return f"İstatistiksel testler sırasında hata: {str(e)}"
259
+
260
+
261
+ def create_interface():
262
+ analyzer = DataAnalyzer()
263
+
264
+ with gr.Blocks() as demo:
265
+ gr.Markdown("# Gelişmiş Veri Analiz Aracı")
266
+
267
+ with gr.Tab("Veri Yükleme ve Temel Bilgiler"):
268
+ file_input = gr.File(label="CSV Dosyası Yükleyin")
269
+ load_button = gr.Button("Veri Yükle")
270
+ info_button = gr.Button("Temel Bilgileri Göster")
271
+ output_text = gr.Textbox(label="Sonuçlar", lines=20)
272
+
273
+ load_button.click(analyzer.load_data, inputs=[file_input], outputs=[output_text])
274
+ info_button.click(analyzer.get_basic_info, outputs=[output_text])
275
+
276
+ with gr.Tab("Eksik Değer Analizi"):
277
+ missing_button = gr.Button("Eksik Değerleri Analiz Et")
278
+ missing_output = gr.Textbox(label="Eksik Değer Analizi", lines=15)
279
+
280
+ missing_button.click(analyzer.analyze_missing_values, outputs=[missing_output])
281
+
282
+ with gr.Tab("Aykırı Değer Analizi"):
283
+ with gr.Row():
284
+ outlier_method = gr.Radio(["zscore", "iqr"], label="Analiz Metodu", value="zscore")
285
+ outlier_threshold = gr.Slider(minimum=1, maximum=5, value=3, label="Eşik Değeri")
286
+ outlier_button = gr.Button("Aykırı Değerleri Analiz Et")
287
+ outlier_output = gr.Textbox(label="Aykırı Değer Analizi", lines=15)
288
+
289
+ outlier_button.click(
290
+ analyzer.analyze_outliers,
291
+ inputs=[outlier_method, outlier_threshold],
292
+ outputs=[outlier_output]
293
+ )
294
+
295
+ with gr.Tab("Korelasyon Analizi"):
296
+ corr_button = gr.Button("Korelasyonları Analiz Et")
297
+ corr_output = gr.Textbox(label="Korelasyon Analizi", lines=15)
298
+
299
+ corr_button.click(analyzer.analyze_correlations, outputs=[corr_output])
300
+
301
+ with gr.Tab("Görselleştirme"):
302
+ with gr.Row():
303
+ plot_type = gr.Dropdown(
304
+ choices=[
305
+ "histogram", "box", "scatter", "bar",
306
+ "violin", "line", "heatmap"
307
+ ],
308
+ label="Grafik Tipi",
309
+ value="histogram"
310
+ )
311
+ x_col = gr.Dropdown(label="X Ekseni")
312
+ y_col = gr.Dropdown(label="Y Ekseni")
313
+ color_col = gr.Dropdown(label="Renk Değişkeni (Opsiyonel)")
314
+
315
+ plot_button = gr.Button("Grafik Oluştur")
316
+ plot_output = gr.Plot(label="Görselleştirme")
317
+
318
+ def update_columns(file):
319
+ if file is not None:
320
+ df = pd.read_csv(file.name)
321
+ return gr.Dropdown(choices=df.columns.tolist()), \
322
+ gr.Dropdown(choices=df.columns.tolist()), \
323
+ gr.Dropdown(choices=['None'] + df.columns.tolist())
324
+ return gr.Dropdown(), gr.Dropdown(), gr.Dropdown()
325
+
326
+ file_input.change(
327
+ update_columns,
328
+ inputs=[file_input],
329
+ outputs=[x_col, y_col, color_col]
330
+ )
331
+
332
+ plot_button.click(
333
+ analyzer.create_visualization,
334
+ inputs=[plot_type, x_col, y_col, color_col],
335
+ outputs=[plot_output]
336
+ )
337
+
338
+ with gr.Tab("İstatistiksel Analizler"):
339
+ with gr.Row():
340
+ stat_col1 = gr.Dropdown(label="Birinci Değişken")
341
+ stat_col2 = gr.Dropdown(label="İkinci Değişken (Opsiyonel)")
342
+
343
+ stat_button = gr.Button("İstatistiksel Testleri Çalıştır")
344
+ stat_output = gr.Textbox(label="Test Sonuçları", lines=15)
345
+
346
+ file_input.change(
347
+ lambda file: (
348
+ gr.Dropdown(choices=pd.read_csv(file.name).columns.tolist()),
349
+ gr.Dropdown(choices=['None'] + pd.read_csv(file.name).columns.tolist())
350
+ ) if file else (gr.Dropdown(), gr.Dropdown()),
351
+ inputs=[file_input],
352
+ outputs=[stat_col1, stat_col2]
353
+ )
354
+
355
+ stat_button.click(
356
+ analyzer.statistical_tests,
357
+ inputs=[stat_col1, stat_col2],
358
+ outputs=[stat_output]
359
+ )
360
+
361
+ with gr.Tab("Özellik Önem Analizi"):
362
+ target_col = gr.Dropdown(label="Hedef Değişken")
363
+ importance_button = gr.Button("Özellik Önemini Analiz Et")
364
+ importance_output = gr.Textbox(label="Özellik Önem Analizi", lines=15)
365
+
366
+ file_input.change(
367
+ lambda file: gr.Dropdown(
368
+ choices=pd.read_csv(file.name).columns.tolist()) if file else gr.Dropdown(),
369
+ inputs=[file_input],
370
+ outputs=[target_col]
371
+ )
372
+
373
+ importance_button.click(
374
+ analyzer.feature_importance,
375
+ inputs=[target_col],
376
+ outputs=[importance_output]
377
+ )
378
+
379
+ with gr.Tab("Veri Ön İşleme"):
380
+ with gr.Row():
381
+ preprocess_method = gr.Radio(
382
+ choices=["standardization", "minmax", "robust", "log"],
383
+ label="Ölçeklendirme Metodu",
384
+ value="standardization"
385
+ )
386
+ columns_to_process = gr.Dropdown(
387
+ label="İşlenecek Sütunlar",
388
+ multiselect=True
389
+ )
390
+
391
+ def preprocess_data(file, method, columns):
392
+ if file is None:
393
+ return "Önce veri yükleyin!"
394
+
395
+ try:
396
+ df = pd.read_csv(file.name)
397
+ processed_df = df.copy()
398
+
399
+ if method == "standardization":
400
+ scaler = StandardScaler()
401
+ elif method == "minmax":
402
+ scaler = MinMaxScaler()
403
+ elif method == "robust":
404
+ scaler = RobustScaler()
405
+ elif method == "log":
406
+ for col in columns:
407
+ processed_df[col] = np.log1p(df[col])
408
+ return processed_df
409
+
410
+ if method != "log":
411
+ processed_df[columns] = scaler.fit_transform(df[columns])
412
+
413
+ output_path = "preprocessed_data.csv"
414
+ processed_df.to_csv(output_path, index=False)
415
+ return output_path
416
+
417
+ except Exception as e:
418
+ return f"Ön işleme sırasında hata: {str(e)}"
419
+
420
+ preprocess_button = gr.Button("Ön İşleme Uygula")
421
+ preprocess_output = gr.File(label="İşlenmiş Veri")
422
+
423
+ file_input.change(
424
+ lambda file: gr.Dropdown(
425
+ choices=pd.read_csv(file.name).select_dtypes(include=[np.number]).columns.tolist(),
426
+ multiselect=True
427
+ ) if file else gr.Dropdown(),
428
+ inputs=[file_input],
429
+ outputs=[columns_to_process]
430
+ )
431
+
432
+ preprocess_button.click(
433
+ preprocess_data,
434
+ inputs=[file_input, preprocess_method, columns_to_process],
435
+ outputs=[preprocess_output]
436
+ )
437
+
438
+ with gr.Tab("Rapor Oluşturma"):
439
+ report_button = gr.Button("Kapsamlı Rapor Oluştur")
440
+
441
+ def generate_report(file):
442
+ if file is None:
443
+ return "Önce veri yükleyin!"
444
+
445
+ try:
446
+ analyzer.load_data(file)
447
+
448
+ report = []
449
+ report.append("# Veri Analiz Raporu")
450
+ report.append(f"Oluşturma Tarihi: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n")
451
+
452
+ report.append("## 1. Temel Bilgiler")
453
+ report.append(analyzer.get_basic_info())
454
+
455
+ report.append("\n## 2. Eksik Değer Analizi")
456
+ report.append(analyzer.analyze_missing_values())
457
+
458
+ report.append("\n## 3. Aykırı Değer Analizi")
459
+ report.append(analyzer.analyze_outliers())
460
+
461
+ report.append("\n## 4. Korelasyon Analizi")
462
+ report.append(analyzer.analyze_correlations())
463
+
464
+ # Raporu kaydet
465
+ report_text = "\n".join(report)
466
+ with open("data_analysis_report.txt", "w", encoding="utf-8") as f:
467
+ f.write(report_text)
468
+
469
+ return "data_analysis_report.txt"
470
+
471
+ except Exception as e:
472
+ return f"Rapor oluşturma sırasında hata: {str(e)}"
473
+
474
+ report_output = gr.File(label="Oluşturulan Rapor")
475
+
476
+ report_button.click(
477
+ generate_report,
478
+ inputs=[file_input],
479
+ outputs=[report_output]
480
+ )
481
+
482
+ return demo
483
+
484
+ # Arayüzü oluştur ve başlat
485
+ if __name__ == "__main__":
486
+ demo = create_interface()
487
+ demo.launch()