首页 > 解决方案 > Python 生成器:产量字典

问题描述

我是生成器的新手,必须编写以下生成器:

“现在创建一个生成器,它产生一个图像文件名以及该图像的所有 AnnotationRects 的 numpy 表示,即生成器返回的元素应该如下所示: (”dataset mmp/train/imagexyz.jpg“, [[32,28,98,102], [67,56,228,110]])

目前我已经写了这个函数:

def data_gen(self):
    names = fo.get_filenames(self.path_to_data)
    for dictionary in fo.create_dictionary(names):
        yield dictionary

get_filenames应该清楚。create_dictionary使用给定的文件名和注释矩形创建一个字典,这些文件被引用到相应的图片。根据任务要求。

def create_dictionary(names):
    dict = {}
    for name in names:
        dict.update({name: read_annotation_file(name)})
    return dict

但是现在我多次收到以下错误消息:

Traceback (most recent call last):

  File "C:\Users\Marco\AppData\Roaming\Python\Python37\site-packages\tensorflow\python\ops\script_ops.py", line 249, in __call__
    ret = func(*args)

  File "C:\Users\Marco\AppData\Roaming\Python\Python37\site-packages\tensorflow\python\autograph\impl\api.py", line 620, in wrapper
    return func(*args, **kwargs)

  File "C:\Users\Marco\AppData\Roaming\Python\Python37\site-packages\tensorflow\python\data\ops\dataset_ops.py", line 905, in generator_py_func
    sys.exc_info()[2])

  File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\site-packages\six.py", line 702, in reraise
    raise value.with_traceback(tb)

  File "C:\Users\Marco\AppData\Roaming\Python\Python37\site-packages\tensorflow\python\data\ops\dataset_ops.py", line 897, in generator_py_func
    flattened_values = nest.flatten_up_to(output_types, values)

  File "C:\Users\Marco\AppData\Roaming\Python\Python37\site-packages\tensorflow\python\data\util\nest.py", line 396, in flatten_up_to
    assert_shallow_structure(shallow_tree, input_tree)

  File "C:\Users\Marco\AppData\Roaming\Python\Python37\site-packages\tensorflow\python\data\util\nest.py", line 299, in assert_shallow_structure
    "Input has type: %s." % type(input_tree))

TypeError: `generator` yielded an element that did not match the expected structure. The expected structure was (tf.string, tf.int32), but the yielded element was dataset_mmp/train/00005256.

现在我的问题是:create_dictionary 只返回一个字符串而不是字典,这怎么可能发生?无需使用 yield 语句即可创建字典。

还有我的另一个问题:我该如何解决?^^

标签: pythondictionarygeneratoryield

解决方案


推荐阅读