【问题标题】:Only size-1 arrays can be converted to Python scalars Scikit Learn只有 size-1 的数组可以转换为 Python 标量 Scikit Learn
【发布时间】:2021-12-24 16:41:14
【问题描述】:

我正在尝试使用 Scikit Learn 的 SGCD 模型,但出现错误。我认为这是我的数组形状的问题,但我不明白如何解决。

我确实调整了图像的大小,使它们的形状都相同。

Here is my X

Here is my y

import cv2

def pixel_grayscale(file):
  file = file.split()
  if len(file) == 2 :
    image = imread("chi/"+file[0], as_gray=True)
  else :
    image = imread("muf/"+file[0], as_gray=True)
  image = cv2.resize(image,(128,128), interpolation=cv2.INTER_CUBIC)
  return np.reshape(image,(128*128))

extract["pixel_grayscale"] = extract.apply(lambda row:
  pixel_grayscale(row.file) if row.category == 0 else pixel_grayscale(row.file+" chi"), axis=1)

features = ["pixel_grayscale"]

X = extract[features]

y = extract["category"]

from sklearn.model_selection import train_test_split

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.30, random_state=42)

from sklearn.linear_model import SGDClassifier

sgdc = SGDClassifier(max_iter=1000, tol=0.01)

sgdc.fit(X_train, y_train)

这是错误:

SGDClassifier(alpha=0.0001, average=False, class_weight=None,
          early_stopping=False, epsilon=0.1, eta0=0.0, fit_intercept=True,
          l1_ratio=0.15, learning_rate='optimal', loss='hinge',
          max_iter=1000, n_iter_no_change=5, n_jobs=None, penalty='l2',
          power_t=0.5, random_state=None, shuffle=True, tol=0.01,
          validation_fraction=0.1, verbose=0, warm_start=False)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
TypeError: only size-1 arrays can be converted to Python scalars

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

ValueError                                Traceback (most recent call last)
<ipython-input-250-8d4e62f2d3f6> in <module>()
      4 print(sgdc)
      5 
----> 6 sgdc.fit(X_train, y_train)

6 frames
/usr/local/lib/python3.7/dist-packages/numpy/core/_asarray.py in asarray(a, dtype, order)
     81 
     82     """
---> 83     return array(a, dtype, copy=False, order=order)
     84 
     85 

ValueError: setting an array element with a sequence.

【问题讨论】:

  • 也许先用print()看看你在变量中有什么以及它们有什么形状。
  • 跳过的帧可能有助于缩小范围,但显然它在从 X_trainy_train 生成数字 dtype 数组时遇到问题。很可能是因为它是一个列表或对象 dtype 数组,具有多种元素大小。

标签: python arrays numpy machine-learning scikit-learn


【解决方案1】:

从图像中,您可以为 'pixel_grayscale' 中的每个值嵌入一个数组。这不能用于拟合模型。

因此假设每个数组的长度相同,您可以将列扩展为具有正确列数的数据框。例如,这看起来像您的数据框:

X = pd.DataFrame({'pixel_grayscale':[np.random.uniform(0,1,5) for i in range(20)]})
y = pd.Series(np.random.binomial(1,0.5,20))

X.head(5)

                                     pixel_grayscale
0  [0.6434161648260968, 0.017854434974394873, 0.4...
1  [0.26917214129827793, 0.09492344774577577, 0.3...
2  [0.22517655723236796, 0.8571416063239798, 0.50...
3  [0.5969653146755568, 0.060240887971164, 0.3594...
4  [0.25819470145953516, 0.9541893368409663, 0.98...

如果我运行你的代码,我会得到同样的错误:

from sklearn.model_selection import train_test_split

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.30, random_state=42)

from sklearn.linear_model import SGDClassifier

sgdc = SGDClassifier(max_iter=1000, tol=0.01)
sgdc.fit(X_train, y_train)

ValueError: setting an array element with a sequence.

检查每个条目的长度是否相同,你应该只得到 1 个值:

X['pixel_grayscale'].apply(len).value_counts()

5    20

现在我们将条目展开为列,这样就可以了:

X_expanded = pd.DataFrame(X['pixel_grayscale'].tolist())
sgdc = SGDClassifier(max_iter=1000, tol=0.01)
sgdc.fit(X_expanded, y)

【讨论】:

  • 有效!如果我想添加一个特征,例如 extract["pixel_color"] 到这个形状相同的新数据框,我该怎么做?
  • X_expanded = extract["pixel_color"] ,假设您的 extract["pixel_color"] 不是嵌入式列表
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-25
  • 1970-01-01
  • 2021-12-01
  • 1970-01-01
  • 2020-11-03
  • 1970-01-01
相关资源
最近更新 更多