为什么这个python生成器根据keras没有输出?

问题描述:

编辑:更新所有的代码来组织这个问题,虽然相同的问题和问题。为什么这个python生成器根据keras没有输出?

def extract_hypercolumn(model, layer_indexes, instance): 
    layers = [model.layers[li].output for li in layer_indexes] 
    get_feature = K.function([model.layers[0].input],layers) 
    assert instance.shape == (1,3,224,224) 
    feature_maps = get_feature([instance]) 
    hypercolumns = [] 
    for convmap in feature_maps: 
     for fmap in convmap[0]: 
      upscaled = sp.misc.imresize(fmap, size=(224, 224), 
             mode="F", interp='bilinear') 
      hypercolumns.append(upscaled) 

    return np.asarray(hypercolumns) 

def get_arrays(each_file): 
    img = color.rgb2lab(io.imread(each_file)[..., :3]) 
    X = img[:,:,:1] 
    y = img[:,:,1:] 
    X_rows,X_columns,X_channels=X.shape 
    y_rows,y_columns,y_channels=y.shape 
    X_channels_first = np.transpose(X,(2,0,1)) 
    X_sample = np.expand_dims(X_channels_first,axis=0) 
    X_3d = np.tile(X_sample,(1,3,1,1)) 
    hc = extract_hypercolumn(model,[3,8],X_3d) 
    hc_expand_dims = np.expand_dims(hc,axis=0) 
    y_reshaped = np.reshape(y,(y_rows*y_columns,y_channels)) 
    classed_pixels_first = KNN.predict_proba(y_reshaped) 
    classed_classes_first = np.transpose(classed_pixels_first,(1,0)) 
    classed_expand_dims = np.expand_dims(classed_classes_first,axis=0) 
    print "hypercolumn shape: ",hc_expand_dims.shape,"classified output color shape: ",classed_expand_dims.shape 
    return hc_expand_dims,classed_expand_dims 


def generate_batch(): 
    files = glob.glob('../manga-resized/sliced/*.png') 
    while True: 
     random.shuffle(files) 
     for fl in files: 
      yield get_arrays(fl) 

colorize = Colorize() 
colorize.compile(optimizer=sgd,loss='categorical_crossentropy',metrics=["accuracy"]) 


colorize.fit_generator(generate_batch(),samples_per_epoch=1,nb_epoch=5) 

这里是(使用Tensorflow)回溯:

Using TensorFlow backend. 
output shape: (None, 112, 228, 228) 
output_shape after reshaped: (None, 112, 51984) 
Epoch 1/5 
Traceback (most recent call last): 
    File "load.py", line 152, in <module> 
    colorize.fit_generator(generate_batch(),samples_per_epoch=1,nb_epoch=5) 
    File "/Users/alex/anaconda2/lib/python2.7/site-packages/keras/models.py", line 651, in fit_generator 
    max_q_size=max_q_size) 
    File "/Users/alex/anaconda2/lib/python2.7/site-packages/keras/engine/training.py", line 1358, in fit_generator 
    'or (x, y). Found: ' + str(generator_output)) 
Exception: output of generator should be a tuple (x, y, sample_weight) or (x, y). Found: None 
Exception in thread Thread-1: 
Traceback (most recent call last): 
    File "/Users/alex/anaconda2/lib/python2.7/threading.py", line 801, in __bootstrap_inner 
    self.run() 
    File "/Users/alex/anaconda2/lib/python2.7/threading.py", line 754, in run 
    self.__target(*self.__args, **self.__kwargs) 
    File "/Users/alex/anaconda2/lib/python2.7/site-packages/keras/engine/training.py", line 404, in data_generator_task 
    generator_output = next(generator) 
StopIteration 

并采用theano - 注意这里超柱和入级标签打印成功 - 好像这是接近的工作:

更新:它使用theano!我很满意。然而,问题仍然与张量流代表我猜

现在,当我尝试:

for a, b in generate_batch(): print(a, b) 

print list(islice(generate_batch(), 3)) 

编辑:新发展 - 他们的工作!

这个工作完美,至少打印出numpy数组而不是错误。然而,Keras问题仍然存在

这让我想知道我是否仅仅遇到了keras的限制 - 因为数据有太多的预处理 - 将图像提供给VGG,提取超列,执行KNN分类标签等。适配发生器试图获得批次,但要做很多工作。也许它太多了,所以它只是将返回值视为空,因为它占用了很多内存/带宽。

我知道张量流例如有一个完整的排队系统为这个确切的问题构建出来。知道这是我所经历的 - 而不是执行错误,这将是非常棒的。在那里的任何keras专家都在乎重量? :)

+0

空的生成器仍然可迭代,如空列表,但不是无。 –

+0

(1)在第一个代码中的for循环中是否执行了任何操作? (2)你从'list(islice(generate_batch_from_hdf5(),3))'得到了什么? (3)你是否显示了'generate_batch_from_hdf5'的完整代码? –

+0

1.是的,在第一次迭代时,它会打印出像(100,1,224,224)(100,112,50176),然后是Epoch 1/5那样的形状,然后是回溯,将这些形状添加到问题中。 2.这似乎是行得通的 - 如果加上它也是一样3.还有问题。 – BigBoy1337

发电机在fit_generator中应该是无限的(通过数据循环)。

c.f. keras documentation on fit_generator

The generator is expected to loop over its data indefinitely.

试着改变你的函数generate_batch到:

def generate_batch(): 
    files = glob.glob('../manga-resized/sliced/*.png') 
    while True: 
     random.shuffle(files) 
     for fl in files: 
      yield get_arrays(fl) 

另外:

我觉得你的代码的问题来自于线

y_reshaped = (y,(y_rows*y_columns,y_channels)) 

此行没有按”似乎完全没有重塑。它只是创建一个包含2个元素的元组:numpy数组y和元组(y_rows*y_columns,y_channels)

我想你应该写类似

y_reshaped = np.reshape(y,(y_rows*y_columns,y_channels)) 
+0

很好找!然而,上述相同的问题仍然存在:( – BigBoy1337

+0

哇!另一个好的发现!现在我的打印列表(islice(generate_batch(),3))声明响起切片 - 因此它被放弃。但是,keras错误仍然存​​在:(我开始怀疑它是否是keras的限制 - 我意识到有很多预处理 - 正在发生 - 它通过VGG运行图像,在提供标签之前在标签上执行KNN分类器。例如,Tensorflow为这个问题建立了一个排队系统,知道这是否是我遇到的具体问题真是太棒了 – BigBoy1337

+0

Personnally我在Theano后端使用keras,它的功能就像一个魅力(我使用'fit_generator',产量,CPU/GPU ...)你是否改变过你的函数'generate_batch'?你能更新你的代码和trackback输出吗?'get_arrays'返回的'hc'和'classed_classes_first'的形状是什么? – sytrus

我遇到了正好与theano后端同样的问题。 我通过发现当我更多地增加“max_q_size”来解决这个问题时,这个错误来得更早。这意味着它是一个队列问题,并与排队操作有关!实际上,在我的情况下,在batch_generator中缺少“while True”引发了这个bug:当在一个时代训练接近发生器中所有可用训练样本全部加载到队列中时,生成器必须将“None”作为“next_sample”排入队列,并且fit_generator将最终满足此“None”并报告您提到的错误。