tensorflow中的类型dtype与numpy中的类型一致可以互用,但是写程序时最好不要互用。
DType
定义了以下对象:
tf.float16
:16位半精度浮点。tf.float32
:32位单精度浮点。tf.float64
:64位双精度浮点。tf.bfloat16
:16位截断浮点。tf.complex64
:64位单精度复合体。tf.complex128
:128位双精度复合体。tf.int8
:8位有符号整数。tf.uint8
:8位无符号整数。tf.uint16
:16位无符号整数。tf.uint32
:32位无符号整数。tf.uint64
:64位无符号整数。tf.int16
:16位有符号整数。tf.int32
:32位有符号整数。tf.int64
:64位有符号整数。tf.bool
:布尔值。tf.string
:字符串。tf.qint8
:量化的8位有符号整数。tf.quint8
:量化的8位无符号整数。tf.qint16
:量化的16位有符号整数。tf.quint16
:量化的16位无符号整数。tf.qint32
:量化的32位有符号整数。tf.resource
:处理一个可变资源。tf.variant
:任意类型的值。
在项目训练时,对于生成和读取tfrecord文件时编码译码过程中出现了,没有考虑到传递变量的默认属性。
对于图片向量和标签向量先前作此处理:
# 读取图片
image_data = Image.open(filename)# type : Image
# 灰度化
image_data=image_data.convert('L')
image_data = np.array(image_data)
# 将图片转化为bytes
image = image_data.tobytes()
list=np.zeros(shape=[CaptchaNumber*AlphabetNumber])
for i,num in enumerate(label):
list[i*AlphabetNumber+num]=1
list=list.tobytes()
example = tf.train.Example(features=tf.train.Features(feature={
'image': tf.train.Feature(bytes_list=tf.train.BytesList(value=[image])),
'label': tf.train.Feature(bytes_list=tf.train.BytesList(value=[list])),
}))
tfrecord_writer.write(example.SerializeToString())
而在另一个读取程序中核心代码是
features = tf.parse_single_example(serialized_example,
features={
'image': tf.FixedLenFeature([], tf.string),
'label': tf.FixedLenFeature([], tf.string),
})
# 获取图片数据
image = tf.decode_raw(features['image'], tf.uint8)
#获取标签数据
label = tf.decode_raw(features['label'], tf.float64)
tf.decode_raw需要指定使用何种数据类型翻译出字节字符串,先前存入tfrecord的数据类型是什么,那么这里也要填入什么类型。
先前的语句 image_data = np.array(image_data) 好像没有指定类型,numpy对于np.array()未指定类型的操作方式是默认最小能支持
image_data的类型,这里image_data的数据大小是0-255,所以默认选择tf.uint8
对于label,先前语句是list=np.zeros(shape=[CaptchaNumber*AlphabetNumber])这里数据默认是np.float64,也就是tf.float64。