我有一个图像,我想分类为A或B.为此,我加载并调整它们的大小以160x160大小,然后转换二维阵至1D,将它们添加到一个大熊猫数据帧:用于sklearn管道中分类的图像数组 - ValueError:用序列设置数组元素
我想有不仅仅是用于分类后的图像更(作为一个例子,产品描述),所以我使用与管道FeatureUnion(即使它现在只有图像)。 ItemSelector就是从这里取:
http://scikit-learn.org/stable/auto_examples/hetero_feature_union.html
它需要在“图像”列中的值。或者,可以做train_X = df.iloc[train_indices]["image"].values
,但我想稍后添加其他列。
def randomforest_image_pipeline():
"""Returns a RandomForest pipeline."""
return Pipeline([
("union", FeatureUnion(
transformer_list=[
("image", Pipeline([
("selector", ItemSelector(key="image")),
]))
],
transformer_weights={
"image": 1.0
},
)),
("classifier", RandomForestClassifier()),
])
然后用KFold分类:
from sklearn.model_selection import KFold
kfold(tested_pipeline=randomforest_image_pipeline(), df=df)
def kfold(tested_pipeline=None, df=None, splits=6):
k_fold = KFold(n_splits=splits)
for train_indices, test_indices in k_fold.split(df):
# training set
train_X = df.iloc[train_indices]
train_y = df.iloc[train_indices]['class'].values
# test set
test_X = df.iloc[test_indices]
test_y = df.iloc[test_indices]['class'].values
for val in train_X["image"]:
print(len(val), val.dtype, val.shape)
# 76800 uint8 (76800,) for all
tested_pipeline.fit(train_X, train_y) # crashes in this call
pipeline_predictions = tested_pipeline.predict(test_X)
...
然而,对于.fit
我收到以下错误:
Traceback (most recent call last):
File "<path>/project/classifier/classify.py", line 362, in <module>
best = best_pipeline(dataframe=data, f1_scores=f1_dict, get_fp=True)
File "<path>/project/classifier/classify.py", line 351, in best_pipeline
confusion_list=confusion_list, get_fp=get_fp)
File "<path>/project/classifier/classify.py", line 65, in kfold
tested_pipeline.fit(train_X, train_y)
File "/usr/local/lib/python3.5/dist-packages/sklearn/pipeline.py", line 270, in fit
self._final_estimator.fit(Xt, y, **fit_params)
File "/usr/local/lib/python3.5/dist-packages/sklearn/ensemble/forest.py", line 247, in fit
X = check_array(X, accept_sparse="csc", dtype=DTYPE)
File "/usr/local/lib/python3.5/dist-packages/sklearn/utils/validation.py", line 382, in check_array
array = np.array(array, dtype=dtype, order=order, copy=copy)
ValueError: setting an array element with a sequence.
我发现其他人有同样的问题,他们的问题是他们的行不一样长。这似乎并没有对我的情况下,所有的行都是一维长度为76800:
for val in train_X["image"]:
print(len(val), val.dtype, val.shape)
# 76800 uint8 (76800,) for all
在崩溃行array
看起来像这样(从调试器复制):
[array([ 255., 255., 255., ..., 255., 255., 255.])
array([ 255., 255., 255., ..., 255., 255., 255.])
array([ 255., 255., 255., ..., 255., 255., 255.]) ...,
array([ 255., 255., 255., ..., 255., 255., 255.])
array([ 255., 255., 255.
我该怎么做才能解决这个问题?
不可思议,非常感谢你!有用! – Lomtrur
@Lomtrur太棒了!现在确保您在FeatureUnion中添加的其他变形器也返回一个二维数组。只有这样他们才能正确结合。 –