altervisi0n

Untitled

Dec 20th, 2025
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.26 KB | None | 0 0
  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. from tensorflow.keras.datasets import imdb
  4. from tensorflow.keras.preprocessing.sequence import pad_sequences
  5. from tensorflow.keras.models import Sequential
  6. from tensorflow.keras.layers import Embedding, SimpleRNN, GRU, LSTM, Dense, Dropout
  7. from tensorflow.keras.optimizers import Adam
  8. from sklearn.metrics import classification_report, confusion_matrix
  9.  
  10. # --- 1. Загрузка и предобработка данных ---
  11.  
  12. # Гиперпараметры
  13. VOCAB_SIZE = 10000 # Размер словаря (10,000 наиболее частых слов)
  14. MAX_LEN = 256 # Максимальная длина последовательности
  15. EMBEDDING_DIM = 128 # Размерность векторных представлений слов
  16. BATCH_SIZE = 64
  17. EPOCHS = 5
  18.  
  19. # Загрузка датасета IMDB
  20. print("Загрузка данных...")
  21. (x_train, y_train), (x_test, y_test) = imdb.load_data(num_words=VOCAB_SIZE)
  22. print(f"Обучающая выборка: {len(x_train)} отзывов")
  23. print(f"Тестовая выборка: {len(x_test)} отзывов")
  24.  
  25. # Приведение последовательностей к одной длине
  26. print(f"Паддинг/обрезка последовательностей до длины {MAX_LEN}...")
  27. x_train_padded = pad_sequences(x_train, maxlen=MAX_LEN, padding='post', truncating='post')
  28. x_test_padded = pad_sequences(x_test, maxlen=MAX_LEN, padding='post', truncating='post')
  29. print(f"Размер обучающей выборки после паддинга: {x_train_padded.shape}")
  30. print(f"Размер тестовой выборки после паддинга: {x_test_padded.shape}")
  31.  
  32.  
  33.  
  34. # --- 2. Создание модели RNN ---
  35.  
  36. def build_model(rnn_type='LSTM', embedding_dim=128, rnn_units=64, learning_rate=0.001):
  37. """
  38. Функция для построения модели с выбором типа RNN слоя.
  39. """
  40. print(f"\nСоздание модели с {rnn_type} слоем...")
  41. model = Sequential()
  42.  
  43. # Слой эмбеддингов
  44. model.add(Embedding(input_dim=VOCAB_SIZE, output_dim=embedding_dim, input_length=MAX_LEN))
  45.  
  46. # Слой Dropout для регуляризации эмбеддингов
  47. model.add(Dropout(0.5))
  48.  
  49. # RNN слой (SimpleRNN, GRU или LSTM)
  50. if rnn_type == 'SimpleRNN':
  51. model.add(SimpleRNN(rnn_units))
  52. elif rnn_type == 'GRU':
  53. model.add(GRU(rnn_units))
  54. else: # LSTM по умолчанию
  55. model.add(LSTM(rnn_units))
  56.  
  57. # Слой Dropout для регуляризации RNN слоя
  58. model.add(Dropout(0.5))
  59.  
  60. # Выходной слой для бинарной классификации
  61. model.add(Dense(1, activation='sigmoid'))
  62.  
  63. # Компиляция модели
  64. optimizer = Adam(learning_rate=learning_rate)
  65. model.compile(optimizer=optimizer, loss='binary_crossentropy', metrics=['accuracy'])
  66.  
  67. return model
  68.  
  69.  
  70. # Создадим модель (например, с LSTM)
  71. model = build_model(rnn_type='LSTM', embedding_dim=EMBEDDING_DIM)
  72. model.summary()
  73.  
  74. # --- 3. Обучение модели ---
  75.  
  76. print("\nНачало обучения модели...")
  77. history = model.fit(
  78. x_train_padded, y_train,
  79. epochs=EPOCHS,
  80. batch_size=BATCH_SIZE,
  81. validation_split=0.2 # Используем 20% обучающих данных для валидации
  82. )
  83.  
  84. # --- 4. Оценка качества ---
  85.  
  86. # Оценка на тестовых данных
  87. print("\nОценка модели на тестовых данных...")
  88. loss, accuracy = model.evaluate(x_test_padded, y_test, verbose=0)
  89. print(f"Точность (Accuracy) на тесте: {accuracy:.4f}")
  90. print(f"Потери (Loss) на тесте: {loss:.4f}")
  91.  
  92. # Получение предсказаний
  93. y_pred_prob = model.predict(x_test_padded)
  94. y_pred = (y_pred_prob > 0.5).astype("int32")
  95.  
  96. # Расчет Precision, Recall, F1-score
  97. print("\nОтчет по классификации:")
  98. print(classification_report(y_test, y_pred, target_names=['Negative', 'Positive']))
  99.  
  100.  
  101. # Построение графиков loss и accuracy
  102. def plot_history(history):
  103. acc = history.history['accuracy']
  104. val_acc = history.history['val_accuracy']
  105. loss = history.history['loss']
  106. val_loss = history.history['val_loss']
  107. epochs_range = range(1, len(acc) + 1)
  108.  
  109. plt.figure(figsize=(12, 5))
  110.  
  111. plt.subplot(1, 2, 1)
  112. plt.plot(epochs_range, acc, 'bo-', label='Training Acc')
  113. plt.plot(epochs_range, val_acc, 'ro-', label='Validation Acc')
  114. plt.title('Точность (Accuracy) на обучении и валидации')
  115. plt.xlabel('Эпохи')
  116. plt.ylabel('Точность')
  117. plt.legend()
  118.  
  119. plt.subplot(1, 2, 2)
  120. plt.plot(epochs_range, loss, 'bo-', label='Training Loss')
  121. plt.plot(epochs_range, val_loss, 'ro-', label='Validation Loss')
  122. plt.title('Потери (Loss) на обучении и валидации')
  123. plt.xlabel('Эпохи')
  124. plt.ylabel('Потери')
  125. plt.legend()
  126.  
  127. plt.show()
  128.  
  129.  
  130. plot_history(history)
  131.  
  132.  
  133. # Анализ ошибок
  134. def analyze_errors():
  135. # Загружаем словарь для декодирования
  136. word_index = imdb.get_word_index()
  137. reverse_word_index = {v: k for k, v in word_index.items()}
  138.  
  139. def decode_review(text_indices):
  140. # Смещения стандартные для датасета Keras
  141. return ' '.join([reverse_word_index.get(i - 3, '?') for i in text_indices])
  142.  
  143. print("\nАнализ неверно классифицированных отзывов:")
  144. misclassified_indices = np.where(y_pred.flatten() != y_test)[0]
  145.  
  146. for i in range(5): # Посмотрим на 5 случайных ошибок
  147. if i < len(misclassified_indices):
  148. idx = misclassified_indices[i]
  149. print(f"\n--- Отзыв #{idx} ---")
  150. print(f"Текст: {decode_review(x_test[idx])}")
  151. print(f"Настоящая метка: {'Positive' if y_test[idx] == 1 else 'Negative'}")
  152. print(f"Предсказанная метка: {'Positive' if y_pred[idx] == 1 else 'Negative'}")
  153.  
  154.  
  155. analyze_errors()
Advertisement
Add Comment
Please, Sign In to add comment