TensorFlow1.14运行高版本代码报Tensor无len()错误适配求助
报错原因
TensorFlow 1.14默认关闭eager execution,tf.random.shuffle()返回的是计算图中的Tensor对象,并非Python原生列表,无法直接调用Python内置的len()函数获取长度。
适配TensorFlow 1.14的修改后代码
import tensorflow as tf # tf.io.gfile.glob返回Python原生字符串列表,先统计总样本量再做shuffle filenames = tf.io.gfile.glob(str(data_dir) + '/*/*') num_samples = len(filenames) # 生成shuffle后的文件名Tensor filenames_shuffled = tf.random.shuffle(filenames) print('Number of total examples:', num_samples) print('Number of examples per label:', len(tf.io.gfile.listdir(str(data_dir/commands[0])))) # TF1.x默认需要通过会话执行Tensor,获取实际的文件名取值 with tf.Session() as sess: first_file = sess.run(filenames_shuffled[0]) print('Example file tensor:', first_file)
改动说明
- 调整了统计总样本量的时机:在shuffle操作前直接从
glob返回的Python列表中取值,避免对Tensor调用len()报错 - 拆分了shuffle操作和取值逻辑:TF1.x默认是计算图模式,Tensor的实际值需要在会话中执行后才能获取,因此单独加了会话逻辑读取首个样例文件名
- 原有标签样本量统计逻辑无需改动:
tf.io.gfile.listdir本身返回的就是Python列表,可直接调用len()统计
内容的提问来源于stack exchange,提问作者shivashankari
相关产品推荐
相关产品推荐

