【问题标题】:how to fix the error ValueError: could not convert string to float in a NLP project in python?如何修复错误 ValueError: could not convert string to float in a NLP project in python?
【发布时间】:2021-08-24 09:48:43
【问题描述】:

我正在使用 jupyter notebook 编写 Python 代码,用于训练和测试数据集以返回正确的情绪。

当我尝试预测短语的情绪时系统崩溃并显示以下错误的问题:

ValueError: 无法将字符串转换为浮点数:'这本书是如此 激怒它让我不开心'

注意我有一个不平衡的数据集,所以我使用 SMOTE 来对数据集进行过度采样

代码:

import pandas as pd
import numpy as np
from imblearn.over_sampling import SMOTE# for inbalance dataset
from sklearn.linear_model import LogisticRegression
from sklearn.feature_extraction.text import TfidfTransformer,TfidfVectorizer
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score,classification_report,confusion_matrix
from sklearn.pipeline import Pipeline

df = pd.read_csv("data/Apple-Twitter-Sentiment-DFE.csv",encoding="ISO-8859-1")

df
# data is cleaned using preprocessing functions

# Solving inbalanced dataset using SMOTE 

vectorizer = TfidfVectorizer()
vect_df =vectorizer.fit_transform(df["clean_text"])
oversample = SMOTE(random_state = 42)
x_smote,y_smote = oversample.fit_resample(vect_df, df["sentiment"])
print("shape x before SMOTE: {}".format(vect_df.shape))
print("shape x after SMOTE: {}".format(x_smote.shape))
print("balance of targets feild %")
y_smote.value_counts(normalize = True)*100


# split the dataset into train and test 
x_train,x_test,y_train,y_test = train_test_split(x_smote,y_smote,test_size = 0.2,random_state =42)


logreg = Pipeline([
                ('tfidf', TfidfTransformer()),
                ('clf', LogisticRegression(n_jobs=1, C=1e5)),
               ])
logreg.fit(x_train, y_train)

y_pred = logreg.predict(x_test)

print('accuracy %s' % accuracy_score(y_pred, y_test))
print(classification_report(y_test, y_pred))

# Make prediction 
exl = "this book was so interstening it made me not happy"

logreg.predict(exl)

【问题讨论】:

    标签: python pandas nlp logistic-regression sentiment-analysis


    【解决方案1】:

    您应该将变量exl 定义如下:

    exl = vectorizer.transform(["this book was so interstening it made me not happy"])
    

    然后进行预测。

    首先,将测试数据放在一个列表中,然后使用vectorizer 使用从您的训练数据中提取的特征进行预测。

    【讨论】:

    • 你的答案是正确的,但你能解释一下这个过程以及为什么我需要对新数据进行矢量化吗?听起来我不太了解 vectorizer 我在 CountVectorizer 之前使用的过程并且我可以工作,但是当我使用 TfidfVectorizer 这个错误开始出现跨度>
    • 文本数据需要特别准备才能开始使用它进行预测建模。单词需要编码为整数或浮点值,以用作机器学习算法的输入,称为特征提取(或矢量化)。这就是sklearnTfidfVectorizer() 发挥作用的地方。您的逻辑回归不会理解字符串;相反,它将理解矢量化数据,它只是表示将字符串转换为 TF-IDF 特征矩阵。
    猜你喜欢
    • 2020-12-11
    • 1970-01-01
    • 1970-01-01
    • 2019-12-18
    • 2018-02-13
    • 2019-05-22
    • 1970-01-01
    • 1970-01-01
    • 2019-11-10
    相关资源
    最近更新 更多