【问题标题】:Why does this python generator have no output according to keras?为什么这个python生成器根据keras没有输出?
【发布时间】:2016-06-13 20:16:50
【问题描述】:

编辑:更新所有代码以组织这个问题,但同样的问题和问题。

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 分类等。 fit 生成器正在尝试批量处理,但要完成大量工作。也许它太多了,所以它只是将返回值视为空,因为它占用了太多的内存/带宽。

例如,我知道张量流有一个完整的排队系统来解决这个确切的问题。很高兴知道这是否是我正在经历的——而不是实施错误。那里有任何 keras 专家关心体重吗??? :)

【问题讨论】:

  • 一个空的生成器仍然是可迭代的,就像一个空列表,但不是 None。
  • (1) 在您的第一个代码的 for 循环中是否打印了任何内容? (2) 你从list(islice(generate_batch_from_hdf5(), 3)) 得到什么? (3)你有没有出示generate_batch_from_hdf5的完整代码?
  • 1.是的,在第一次迭代中,它会打印出像 (100, 1, 224, 224) (100, 112, 50176) 这样的形状,然后是 Epoch 1/5,然后是回溯,我会把它添加到问题中。 2. 这似乎有效 - 我也添加它 3. 也添加到问题中。
  • 你的程序是在用sys.path 做奇怪的事情,还是只是奇怪的事情?您的回溯中的第二个例外似乎表明sys.pathNone,这没有多大意义。如果整个解释器出现问题(例如,因为在关闭过程中你有单独的线程在做一些事情),它也可能解释生成器坏了。
  • 直接调用生成器会得到什么:for a, b in generate_batch_from_hdf5(): print(a, b)?

标签: python keras


【解决方案1】:

generator 在 fit_generator 中应该是无限的(循环数据)。

参考keras documentation on fit_generator

生成器应无限期地循环其数据。

尝试将您的函数 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))

【讨论】:

  • 好发现!但是,仍然会出现上述相同的问题:(
  • 哇!另一个好发现!现在我的 print list(islice(generate_batch(), 3)) 语句返回切片 - 所以它正在被产生。但是,keras 错误仍然存​​在 :(。我开始怀疑这是否是 keras 的限制 - 我意识到有很多预处理 - 正在发生 - 它通过 VGG 运行图像,在喂食之前对标签执行 KNN 分类器例如,Tensorflow 为这个问题构建了一个排队系统。知道这是否是我遇到的具体问题会很棒
  • 我个人将 keras 与 Theano 后端一起使用,这就像一个魅力。 (我使用fit_generator,产量,CPU/GPU ...)你改变了你的功能generate_batch吗?你能更新你的代码和引用输出吗? get_arrays返回的hcclassed_classes_first的形状是什么?
  • 我确实更新了生成批处理 - 检查有问题的更新代码。张量流和理论的不同结果..
  • 我自己从未使用过 Tensorflow。既然您说代码适用于 Theano 但不适用于 Tensorflow,您可能需要检查一下:由于您使用具有 CNN 层的 VGG 预训练模型,您可能需要将卷积核从 Theano 转换为 Tensorflow,请参阅this Keras wiki 了解更多信息详情。
【解决方案2】:

我在 theano 后端遇到了完全相同的问题。 我通过发现当我更多地增加“max_q_size”来探索这个问题时,这个错误出现得更早。那就是队列问题,和入队操作有关!!!

事实上,在我的例子中,batch_generator 中缺少“while True”会导致这个错误:当在一个 epoch 中训练接近生成器中所有可用的训练样本都加载到队列中的点时,然后生成器必须将“None”作为“next_sample”排入队列,fit_generator 最终会遇到这个“None”并报告您提到的错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-04-05
    • 2018-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多