存在类型错误,但类型已经是字节。请帮帮我。感谢。
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
代码如下。但我不知道哪里出错了,我自己也无法弄明白。
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()
答案 0 :(得分:0)
您正在使用_bytes_feature
,您应该在第29行使用_int64_feature
。
我怎么知道这个?它出现在错误信息中。
TypeError: 71 has type int, but expected one of: bytes
您正在提供int
,因此您需要使用int
功能。我猜测_int64_feature
可能会这样做,因为它就在那里。
错误消息不仅仅是出现问题&#34;当你是一名程序员时。一旦你知道如何阅读它们,它们就是解决问题的宝贵工具。
答案 1 :(得分:0)
发生错误的原因是tf.train.BytesList(value)
需要一个 list 个字节对象。如果仅将字节对象作为value
传递,则如下所示:
tf.train.Feature(bytes_list=tf.train.BytesList(value=b'GAME'))
然后它将解释为列表,其中包含字节的值;因此b'GAME'
将被解释为[71, 65, 77, 69]
,然后它会抱怨71
是int
而不是bytes
对象。
解决方案是将value
转换为列表,因此(在_bytes_feature()
函数中)是这样的:
tf.train.Feature(bytes_list=tf.train.BytesList(value=[b'GAME']))
请注意bytes
周围的方括号。这是长度为1的列表。当然,您可以传递value
而不是硬编码的b'GAME'
:tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))
还要注意,您已经在_int64_feature()
函数中执行了此操作,该函数的工作方式相同。