[Python] I am getting error while running this line of code gnb.fit(df_train, y_train)

Discussão em 'Python' iniciado por Stack, Janeiro 25, 2025.

  1. Stack

    Stack Membro Participativo

    Title: ValueError: could not convert string to float when training GaussianNB for SMS Spam Detection

    Body:
    I'm building an SMS spam detection tool and encountering an error while predicting with a GaussianNB model. Here's the error message:

    UserWarning: X has feature names, but GaussianNB was fitted without feature names
    warnings.warn(
    ---------------------------------------------------------------------------
    ValueError: could not convert string to float: 'Dear i am not denying your words please'


    Here’s the relevant part of my code:

    from sklearn.naive_bayes import GaussianNB
    from sklearn.metrics import accuracy_score, confusion_matrix, precision_score

    # Training the model
    gnb = GaussianNB()
    gnb.fit(df_train, y_train)

    # Making predictions
    y_pred1 = gnb.predict(df_test) # Error occurs here

    # Evaluating the model
    print(accuracy_score(y_test, y_pred1))
    print(confusion_matrix(y_test, y_pred1))
    print(precision_score(y_test, y_pred1))


    I suspect the issue is related to the input data format. df_train and df_test contain a column with SMS text, but GaussianNB requires numeric input.

    I suspect the issue is related to the input data format. df_train and df_test contain a column with SMS text, but GaussianNB requires numeric input.

    Questions:


    1. How can I preprocess the text data so that GaussianNB can handle it?


    2. How do I address the warning about feature names (X has feature names, but GaussianNB was fitted without feature names)?

    Here’s what I’ve tried so far:


    • Converting the text data to numeric using TfidfVectorizer. However, I’m not sure if I implemented it correctly.


    • Ensuring no missing values in the dataset using .isnull().sum().

    Any guidance or suggestions to fix this issue would be greatly appreciated. Thanks in advance!

    Continue reading...

Compartilhe esta Página