【发布时间】:2021-05-14 10:13:00
【问题描述】:
我想知道是否有人可以帮助我理解这个错误。
---> 83 return array(a, dtype, copy=False, order=order)
84
85
ValueError: setting an array element with a sequence.
这似乎源于下面列出的另一个错误。
TypeError: only size-1 arrays can be converted to Python scalars
我正在尝试拟合 Pandas 数据框中的训练数据,每行包含一个 numpy 数组。相关的标签也是 pandas 数据框中的整数值。请在下面找到导致错误的步骤。
for target in targetList:
criterion_opts = np.array(['entropy', 'gini'])
n_estimators_opts = [50, 100, 150, 200, 400, 500]
param_grid = dict(criterion = criterion_opts, n_estimators = n_estimators_opts)
cv = ShuffleSplit(n_splits=5, test_size=0.3, random_state=42)
grid = GridSearchCV(RandomForestClassifier(), param_grid=param_grid, scoring='roc_auc')
X_train = pd.DataFrame({'Morgan Fingerprints':Xtrain[f"{target}"]})
y_train = ytrain[f"{target}"]
grid.fit(np.array(X_train), y_train)
#print(f"The best params for {target} are: " + grid.best_params_)
请在下面找到存储在实例和标签数据框中的项目的一些示例。
Morgan Fingerprints
435 [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, ...
1830 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ...
[2284 rows x 1 columns]
435 1
1830 0
Name: activity_class, Length: 2284, dtype: object
编辑:所以当我重新创建一些代码来重现错误时,似乎我已经找到了错误的来源。当我将 Xtrain 作为 numpy 数组列表传入时,GridSearchCV.fit() 没有问题。但是,当我将 Xtrain 转换为 Pandas 数据框然后将其传递给 fit 时,问题就会弹出。
下面的代码应该会重现该错误。如果您删除 Xtrain 到数据框的转换,则应该删除该问题。谁能解释这是为什么?我知道 fit 需要一个数组,但我认为传递一个包含数组的数据框应该没问题?
import pandas as pd
import numpy as np
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import ShuffleSplit
from sklearn.model_selection import GridSearchCV
X_train = pd.DataFrame({'Morgan Fingerprints':[np.array([1, 0, 0, 0, 0,
1]), np.array([1, 0, 0, 0, 1, 1]), np.array([1, 0, 0, 1, 0, 0]),
np.array([1, 0, 1, 1, 0, 0]), np.array([1, 1, 0, 0, 0, 0]), np.array([1,
0,1, 1, 0, 1])]})
y_train = [1, 0, 1, 0, 1, 1]
criterion_opts = np.array(['entropy', 'gini'])
n_estimators_opts = [50, 100, 150, 200, 400, 500]
param_grid = dict(criterion = criterion_opts, n_estimators =
n_estimators_opts)
cv = ShuffleSplit(n_splits=2, test_size=0.3, random_state=42)
grid = GridSearchCV(RandomForestClassifier(), param_grid=param_grid,
cv=cv, scoring='roc_auc')
grid.fit(np.array(X_train), y_train)
#print(f"The best params for {target} are: " + grid.best_params_)
编辑#2:看来我终于设法解决了这个问题。首先,我将数据框的值附加到列表中。但是,这提出了一个问题,其中 fit 期望一个 dim 2 的数组并得到 dim 3 (我认为这是因为各个数组嵌套在一个列表中?)。然后通过创建一个“最终”Xtrain 来解决这个问题,我只是从嵌套列表中提取数组并将它们用作模型的单独训练实例。
【问题讨论】:
-
请使用完整错误跟踪更新您的问题 - 了解如何创建minimal reproducible example。
标签: python pandas numpy scikit-learn