【问题标题】:TypeError: only size-1 arrays can be converted to Python scalars during SVM trainingTypeError:在 SVM 训练期间,只能将 size-1 数组转换为 Python 标量
【发布时间】:2020-12-29 23:23:45
【问题描述】:

我在使用 SVM 时遇到了一个奇怪的错误

我的标签如下:

labels: [1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0
 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]

嵌入是这样的:

data["embeddings"]:
[array([ 0.05140932,  0.05402263, ... ,  0.02575628], dtype=float32), array([ 0.05858443, -0.05192663, ... , 0.01924052, 0.1784615 ,  -0.12531035, -0.04654732], dtype=float32)]

标签和嵌入​​的长度相同。以上嵌入只是整体的 [0:2] 一部分

recognizer = SVC(C=1.0, kernel="linear", probability=True)
recognizer.fit(data["embeddings"],labels)

recognizer.fit() 产生以下错误:

TypeError: only size-1 arrays can be converted to Python scalars

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "train_embeddings.py", line 52, in <module>
    recognizer.fit(data["features"],labels)
  File "/usr/local/lib/python3.8/dist-packages/sklearn/svm/_base.py", line 146, in fit
    X, y = check_X_y(X, y, dtype=np.float64,
  File "/usr/local/lib/python3.8/dist-packages/sklearn/utils/validation.py", line 747, in check_X_y
    X = check_array(X, accept_sparse=accept_sparse,
  File "/usr/local/lib/python3.8/dist-packages/sklearn/utils/validation.py", line 531, in check_array
    array = np.asarray(array, order=order, dtype=dtype)
  File "/muho/.local/lib/python3.8/site-packages/numpy/core/_asarray.py", line 83, in asarray
    return array(a, dtype, copy=False, order=order)
ValueError: setting an array element with a sequence.

我也试过把标签改成这个:

labels: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

但它也没有帮助。我不知道这里的任何东西或为什么应该是标量。

【问题讨论】:

  • data['embeddings'] 需要是一个 numpy 数组(数字 dtype),或者它可以变成这样的东西,

标签: python-3.x numpy machine-learning svm


【解决方案1】:

您的变量data["embeddings"] 似乎是问题所在。它的元素是长度为 1 的数组,因为您不能将值作为列表访问,而是作为元组 (values, dtype) 使用:

data_2 = [x[0] for x in data["embeddings"]]
recognizer.fit(data_2, labels)

【讨论】:

    猜你喜欢
    • 2021-01-07
    • 2023-03-25
    • 2021-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多