在执行 tf.train.example 时,出现 TypeError: 71 has type int, but Expected one of: bytes

Tri*_*ang 2 python tensorflow

存在类型错误,但类型已经是字节。请帮我解决一下。谢谢。

Traceback (most recent call last):
   File "toTFRECORDS_1.py", line 29, in <module>
      feature = {'train/image': _bytes_feature(img_data),
   File "toTFRECORDS_1.py", line 10, in _bytes_feature
      return tf.train.Feature(bytes_list=tf.train.BytesList(value=value))
TypeError: 71 has type int, but expected one of: bytes
Run Code Online (Sandbox Code Playgroud)

代码如下。但我不知道哪里出了问题,我自己也无法弄清楚。

def _int64_feature(value):
    return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))

def _bytes_feature(value):
    return tf.train.Feature(bytes_list=tf.train.BytesList(value=value))

images = os.listdir('D:\python_64\Training_Set')


train_filename = 'train.tfrecords'
with tf.python_io.TFRecordWriter(train_filename) as tfrecord_writer: 
    for i in range(len(images)):
        # read in image data by tf
        img_data = tf.gfile.FastGFile(os.path.join('D:\python_64\Training_Set',images[i]), 'rb').read()  # image data type is string
        # get width and height of image
        image_shape = plt.imread(os.path.join('D:\python_64\Training_Set',images[i])).shape
        width = image_shape[1]
        height = image_shape[0]

        # create features
        feature = {'train/image': _bytes_feature(img_data),
                       'train/label': _int64_feature(i),  # label: integer from 0-N
                       'train/height': _int64_feature(height), 
                       'train/width': _int64_feature(width)}
        # create example protocol buffer
        example = tf.train.Example(features=tf.train.Features(feature=feature))
        # serialize protocol buffer to string
        tfrecord_writer.write(example.SerializeToString())
    tfrecord_writer.close()
Run Code Online (Sandbox Code Playgroud)

Cip*_*agă 6

您的错误原因是tf.train.BytesList(value)需要一个字节对象列表。如果您仅将 bytes 对象传递为value,如下所示:

tf.train.Feature(bytes_list=tf.train.BytesList(value=b'GAME'))
Run Code Online (Sandbox Code Playgroud)

然后它将把它解释为一个列表,其中包含字节的值;sob'GAME'将被解释为[71, 65, 77, 69],然后它会抱怨71is anint而不是一个bytes对象。

解决方案是将您转换value为列表,因此请执行以下操作(在您的_bytes_feature()函数中):

tf.train.Feature(bytes_list=tf.train.BytesList(value=[b'GAME']))
Run Code Online (Sandbox Code Playgroud)

请注意 周围的方括号bytes。这是一个长度为一的列表。当然,您可以传递value而不是硬编码b'GAME'tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))

另请注意,您已经在_int64_feature()函数中执行了此操作,其工作方式相同。