我正在尝试在Keras中构建语义分割模型。由于我使用了自定义数据,因此我决定编写一个自定义生成器将其馈送到keras函数_.fit_generator
,并且在求解此发电机错误时达到了一个死端,该错误说
UnboundLocalError: local variable 'zipped' referenced before assignment
经过一些Github和Stackover的研究,我发现" https://github.com/keras-team/keras/keras/sissues/1638#issuecomment-182139908" ANS ANS" ANS与我的问题相似,即使是该解决方案也不是没有工作再次扔同样的错误
def image_segmentation_generator( PROC_DATA, target_size,
batch_size , gen, do_augment=False):
if gen=='train':
images_path = PROC_DATA+'/train_images/images'
segs_path = PROC_DATA+'/train_labels/labels'
elif 'val':
images_path = PROC_DATA+'/val_images/images'
segs_path = PROC_DATA+'/val_labels/labels'
img_seg_pairs = get_pairs_from_paths( images_path , segs_path)
random.shuffle( img_seg_pairs )
zipped = itertools.cycle( img_seg_pairs )
while True:
X = []
Y = []
for _ in range( batch_size) :
im , seg = next(zipped)
im = cv2.imread(im , 1 )
im = cv2.resize(im,(target_size[0],target_size[1]))
seg = cv2.imread(seg , 0 )
seg = ia.imresize_single_image(seg, (target_size),
interpolation='nearest')
if do_augment:
img , seg[:,:,0] = augment_seg( img , seg[:,:,0] )
X.append( get_image_arr(im ) )
Y.append( get_segmentation_arr( seg ) )
yield np.array(X) , np.array(Y)
my_gen = image_segmentation_generator(...)
my_gen.next()
应该给我给定批量大小的图像和标签框架。
堆栈跟踪:im,seg = next(zpipped(unboundlocalerror:分配前引用的本地变量'
我该如何解决?
供将来参考。我为此找到了解决方法。当创建为生成器时,该功能对象看起来应该是自我维护的,而不必依赖额外的参数。因此,应沿函数传递带有地址的迭代器对象。
zipped =在调用image_sementation_generator_1
之前创建的对象=创建对象def image_segmentation_generator_1(zipped = zipped,target_size =(1242,378(,batch_size = 4,do_augment = false(: 而真:
image_list = []
label_list = []
_image_list = []
_label_list = []
for _ in range((batch_size/2)) :
im , seg = next(zipped)
im = cv2.imread(im , 1 )
im = cv2.resize(im,(target_size[0],target_size[1]))
seg = cv2.imread(seg , 0 )
seg = ia.imresize_single_image(seg, (target_size[0],target_size[1]), interpolation='nearest')
if do_augment:
_image_list , _label_list = augment_seg( im , seg)
else :
_image_list = im
_label_list = seg
_image_list = get_image_arr(_image_list)
image_list = image_list + _image_list
label_list = label_list + _label_list
yield np.array(image_list) , np.array(label_list)