CountVectorizer per la classificazione del testo
È il momento di iniziare a costruire il tuo classificatore di testo! I dati sono stati caricati in un DataFrame chiamato df. Esploralo nell'IPython Shell per vedere quali colonne puoi usare. Il metodo .head() è particolarmente utile.
In questo esercizio userai pandas insieme a scikit-learn per creare un vettorizzatore testuale sparso con cui addestrare e testare un semplice modello supervisionato. Per cominciare, imposterai un CountVectorizer e ne esplorerai alcune funzionalità.
Questo esercizio fa parte del corso
Introduzione al Natural Language Processing in Python
Istruzioni dell'esercizio
- Importa
CountVectorizerdasklearn.feature_extraction.textetrain_test_splitdasklearn.model_selection. - Crea una Series
yda usare come etichette assegnando l'attributo.labeldidfay. - Usando
df["text"](feature) ey(etichette), crea i set di training e test contrain_test_split(). Usatest_size=0.33erandom_state=53. - Crea un oggetto
CountVectorizerchiamatocount_vectorizer. Assicurati di specificare l'argomentostop_words="english"per rimuovere le stop word. - Esegui fit e transform dei dati di training
X_trainusando il metodo.fit_transform()del tuo oggettoCountVectorizer. Fai lo stesso con i dati di testX_test, ma usando il metodo.transform(). - Stampa le prime 10 feature di
count_vectorizerusando il suo metodo.get_feature_names().
Esercizio pratico interattivo
Prova a risolvere questo esercizio completando il codice di esempio.
# Import the necessary modules
____
____
# Print the head of df
print(df.head())
# Create a series to store the labels: y
y = ____
# Create training and test sets
X_train, X_test, y_train, y_test = ____
# Initialize a CountVectorizer object: count_vectorizer
count_vectorizer = ____
# Transform the training data using only the 'text' column values: count_train
count_train = ____
# Transform the test data using only the 'text' column values: count_test
count_test = ____
# Print the first 10 features of the count_vectorizer
print(____[:10])