chetyre/app.py

84 lines
2.8 KiB
Python

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
from sklearn.metrics import classification_report, ConfusionMatrixDisplay
# -----------------------------
# 1. Загрузка данных
# -----------------------------
# Попробуем определить, есть ли заголовки
try:
df = pd.read_csv('A_Z_HandwrittenLetters.csv')
if 'label' in df.columns:
print("Заголовки найдены, используется столбец 'label'")
else:
raise Exception("Столбец 'label' не найден")
except Exception as e:
print(f"Ошибка: {e}, попытка чтения без заголовков")
df = pd.read_csv('A_Z_HandwrittenLetters.csv', header=None)
# Разделение на признаки и метки
if 'label' in df.columns:
y = df['label'].values
X = df.drop('label', axis=1).values
else:
y = df[0].values
X = df.drop(0, axis=1).values
# -----------------------------
# 2. Нормализация
# -----------------------------
X = X / 255.0
# -----------------------------
# 3. Визуализация первых изображений
# -----------------------------
_, axes = plt.subplots(1, 4, figsize=(10, 5))
for ax, image, label in zip(axes, X[:4], y[:4]):
ax.imshow(image.reshape(28, 28), cmap='gray')
ax.axis('off')
ax.set_title(f"Label: {label}\n({chr(label + ord('A'))})")
plt.suptitle("Sample Training Images")
plt.show()
# -----------------------------
# 4. Разделение выборки
# -----------------------------
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.3, random_state=42, shuffle=True
)
# -----------------------------
# 5. Обучение модели
# -----------------------------
print("Обучение модели...")
clf = SVC(gamma=0.001)
clf.fit(X_train, y_train)
# -----------------------------
# 6. Предсказание
# -----------------------------
y_pred = clf.predict(X_test)
# -----------------------------
# 7. Визуализация предсказаний
# -----------------------------
_, axes = plt.subplots(1, 4, figsize=(10, 5))
for ax, image, prediction in zip(axes, X_test, y_pred):
ax.imshow(image.reshape(28, 28), cmap='gray')
ax.axis('off')
ax.set_title(f"Prediction: {prediction}\n({chr(prediction + ord('A'))})")
plt.suptitle("Predicted Letters")
plt.show()
# -----------------------------
# 8. Отчеты и матрица ошибок
# -----------------------------
print("\nClassification Report:")
print(classification_report(y_test, y_pred))
disp = ConfusionMatrixDisplay.from_predictions(y_test, y_pred)
disp.figure_.suptitle("Confusion Matrix")
plt.show()