Python: "could not convert string to float" 将 np 数组拟合到模型中时出错

Python: "could not convert string to float" error when fitting np arrays into model

我正在尝试做一个假新闻分类模型,因此作为预处理的一部分,我进行了停用词删除、词干提取和词形还原。之后我使用 Doc2Vec 将文本转换为向量。 x 和 y 是 FER2013 数据集的矢量化文本和标题列,看起来像这样:

array(['[-0.78902    -1.3584563  -1.2094668   1.2671869  -0.505878   -0.46793452 -0.05335827 -0.3953245   0.64238095  0.29936427  0.64882624 -0.9903825 -0.16372935 -0.5240088  -0.8061704   0.94803816  0.49816552  1.0211618 -0.3891333  -0.53825814]',
   '[ 1.3473806  -2.2537904  -0.01150447  1.0409713  -0.17815335 -0.92815816  0.01454325 -1.78424    -1.2680324   0.39823842 -0.3313817  -0.7288629 -2.3424263   0.50622666 -0.1096359   0.6213235  -0.18285985  1.0153825  0.12197232 -0.31061244]',
   '[-0.21220133 -0.94656384 -0.31035122 -0.20017953 -0.04308065 -0.2723616  0.13090962 -0.51174223 -0.63989     0.9296897  -1.516201    0.90435594  0.19001946 -0.60641354  1.2848449  -0.9736119   0.05583194 -0.55788654 -1.2701703   1.361641  ]',
   ...,
   '[ 0.07217433 -0.01937062 -0.6813549   0.9267837   0.8567494   0.11055075 -0.49166957  0.05391011 -0.4867952   0.68353873 -0.34195983  0.11552304  0.07995445 -0.68140924  0.14169812  0.05574211  0.85227823  0.28077438  0.08299595 -0.93785906]',
   '[-0.03407184  1.0156128  -0.3216298   0.38381922  0.41431156 -0.22601238 -0.45248717 -0.918599   -0.16802132  0.1707096  -0.9931418  -0.62819743 -0.22415633 -2.451051   -0.26168516 -0.04228298  0.71497554 -0.27817437 -1.0023195  -0.43352002]',
   '[-0.60217994  0.1949403   0.29088852 -0.5941371   0.5181151  -0.789163  0.887305   -1.6515299  -0.8250909   0.11755247  0.08880343 -0.23532224  0.52777374  0.31153452 -0.39013034 -0.08209435  1.7401134   1.4870292 -0.18821365  1.1624134 ]'],
  dtype=object)

这是我用于 train-test 拆分和拟合的代码:

xtrain, xtest, ytrain, ytest = train_test_split(x, y, test_size=0.2, random_state=42)
model = MultinomialNB()
model.fit(xtrain, ytrain)
print(model.score(xtest, ytest))

但是这里出现了向量元素换行的问题。因此,结果,当我将其转换为 np 数组以适合模型时,最后生成了一个“\n”字符。 我用空值替换了“\n”来解决这个问题,但同样的错误仍然存​​在。

ValueError: could not convert string to float: '[ 0.3060216   0.04662842  0.44954425  1.4223956   1.3165258   0.7194798  1.2665545  -0.4921699  -0.01131658  0.02519435 -0.6978444  -1.2564504 -0.6709047   0.02319291  0.05263066 -0.1006538   1.3066514  -0.9096088  0.3219977   0.31393617]'

当我检查这些数组的数据类型时,它显示为 object,即使在错误中,它被指定为字符串。

请从标签中删除 机器学习 这是一个 python 错误!

错误 明确 您正在尝试将字符串转换为浮点数,并且该字符串包含 '[' 字符并包含 空格 ...无法转换 你需要清理那个字符串:

def check_float(element) :
    try:
        float(element)
        return(True)
    except ValueError : 
        return False

new_List_floats=[]
for st in that_array : 
    List_of_string = st.split(" ")
    for element in List_of_string :
        el = element.split(" ")[0]
        el =element.split("]")[0]
        el = element.split("[")[0]
        if check_float(el) :
            new_List_floats +=[float(el)]

现在您可以使用新的列表来完成您的过程只要注意数组的形状并在需要时对代码进行一些更改。