import pandas as pd from sklearn.modelselection import traintestsplit from…
- User
import pandas as pd from sklearn.model_selection import train_test_split from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Embedding, LSTM, Dense, Dropout, Bidirectional, GlobalMaxPooling1D from tensorflow.keras.preprocessing.text import Tokenizer from tensorflow.keras.preprocessing.sequence import pad_sequences from sklearn.metrics import classification_report, roc_auc_score
data['v1'] = data['v1'].astype(str)
data['v1'] = data['v1'].map({'ham': 0, 'spam': 1})
data = data.dropna(subset=['v1', 'v2'])
X_text = data['v2'].values.tolist() y = data['v1'].values
X_train_text, X_test_text, y_train, y_test = train_test_split( X_text, y, test_size=0.2, random_state=42 )
tokenizer = Tokenizer() tokenizer.fit_on_texts(X_train_text)
X_train_seq = tokenizer.texts_to_sequences(X_train_text) X_test_seq = tokenizer.texts_to_sequences(X_test_text)
max_length = 200 X_train_padded = pad_sequences(X_train_seq, maxlen=max_length, padding='post') X_test_padded = pad_sequences(X_test_seq, maxlen=max_length, padding='post')
model = Sequential() model.add(Embedding(input_dim=len(tokenizer.word_index) + 1, output_dim=128, input_length=max_length))
model.add(Bidirectional(LSTM(64, return_sequences=True))) model.add(Dropout(0.5)) model.add(LSTM(32, return_sequences=True)) model.add(Dropout(0.5)) model.add(GlobalMaxPooling1D()) model.add(Dense(1, activation='sigmoid'))
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
history = model.fit( X_train_padded, y_train, validation_split=0.2, epochs=10, batch_size=32 )
test_loss, test_accuracy = model.evaluate(X_test_padded, y_test) print(f'Test Loss: {test_loss:.4f}, Test Accuracy: {test_accuracy:.4f}')
y_pred = model.predict(X_test_padded)
print(classification_report(y_test, y_pred))
почему матрица не строится? ошибка:
ValueError Traceback (most recent call last) Cell In[46], line 57 53 print(f'Test Loss: {test_loss:.4f}, Test Accuracy: {test_accuracy:.4f}') 55 y_pred = model.predict(X_test_padded) ---> 57 print(classification_report(y_test, y_pred))
File c:\Users\usicc\AppData\Local\Programs\Python\Python311\Lib\site-packages\sklearn\utils_param_validation.py:213, in validate_params..decorator..wrapper(*args, **kwargs) 207 try: 208 with config_context( 209 skip_parameter_validation=( 210 prefer_skip_nested_validation or global_skip_validation 211 ) 212 ): --> 213 return func(*args, **kwargs) 214 except InvalidParameterError as e: 215 # When the function is just a wrapper around an estimator, we allow 216 # the function to delegate validation to the estimator, but we replace 217 # the name of the estimator by the name of the function in the error 218 # message to avoid confusion. 219 msg = re.sub( 220 r"parameter of \w+ must be", 221 f"parameter of {func.} must be", 222 str(e), 223 )
- Assistant
Ошибка, которую вы получаете, связана с тем, что
y_pred, который вы получаете из модели, является массивом вероятностей (значений от 0 до 1), аy_test- это массив меток (0 или 1). Функцияclassification_reportожидает сравнения между двумя массивами одинакового типа (в вашем случае, бинарными метками).Чтобы исправить эту ошибку, вам нужно преобразовать вероятности в бинарные метки. Это можно сделать, установив порог, например 0.5. Если вероятность больше или равна 0.5, назначьте метку 1, в противном случае - 0.
Вот как можно это реализовать:
python# Преобразуем вероятности в бинарные метки y_pred_classes = (y_pred >= 0.5).astype(int) print(classification_report(y_test, y_pred_classes))Полный код с изменением будет выглядеть так:
python