Python sklearn pipeline中分类的图像数组-ValueError:使用序列设置数组元素
我有一个图像,我想将其分类为a或B。为此,我加载并调整其大小为160x160,然后将2D数组转换为1D,并将其添加到数据帧:Python sklearn pipeline中分类的图像数组-ValueError:使用序列设置数组元素,python,pandas,numpy,scikit-learn,Python,Pandas,Numpy,Scikit Learn,我有一个图像,我想将其分类为a或B。为此,我加载并调整其大小为160x160,然后将2D数组转换为1D,并将其添加到数据帧: from pandas import DataFrame from scipy.misc import imread, imresize rows = [] for product in products: try: relevant = product.categoryrelevant.all()[0].relevant except I
from pandas import DataFrame
from scipy.misc import imread, imresize
rows = []
for product in products:
try:
relevant = product.categoryrelevant.all()[0].relevant
except IndexError:
relevant = False
if relevant:
relevant = "A"
else:
relevant = "B"
# this exists for all pictures
image_array = imread("{}/{}".format(MEDIA_ROOT, product.picture_file.url))
image_array = imresize(image_array, (160, 160))
image_array = image_array.reshape(-1)
print(image_array)
# [254 254 252 ..., 255 255 253]
print(image_array.shape)
# (76800,)
rows.append({"id": product.pk, "image": image_array, "class": relevant})
index.append(product)
df = DataFrame(rows, index=index)
我想要的不仅仅是用于以后分类的图像(例如,产品描述),因此我使用了一个带有FeatureUnion的管道(即使它现在只有图像)。ItemSelector取自此处:
它接受“图像”列中的值。或者,可以执行train_X=df.iloc[train_index][“image”].值
,但我想稍后添加其他列
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个特征)保存在列表中,而该列表保存在数据框的一列中 因此,当您使用ItemSelector选择该列时,该列的输出将是形状
(Train_len,)
的一维数组。76800的内部尺寸对于FeatureUnion或后续估计器不可见
更改ItemSelector的transform()
函数,以返回正确的具有形状的二维数据数组(Train_len,76800)。只有到那时它才会起作用
改为:
def transform(self, data_dict):
return np.array([np.array(x) for x in data_dict[self.key]])
如果您不懂任何东西,请随时提问。@Lomtrur太棒了!现在确保您在FeatureUnion中添加的其他变压器也返回一个二维阵列。只有这样,它们才能正确组合。
[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.
def transform(self, data_dict):
return np.array([np.array(x) for x in data_dict[self.key]])