tensorflow2.1的一次由numpy数据集引起的内存溢出

x与y都是numpy数据,x,y都是由1千张图片组成
采用下面这条代码创建数据集。
train_dataset=tf.data.Dataset.from_tensor_slices((x,y))
在训练的过程中程序内存占用一直在增长,直到程序因为内存溢出而崩溃。
官方教程的解释是上述这种由numpy创建数据集的方法只适用于小型数据,因为这种数据集被植入TensorFlow graph中,且数据会被复制多次。

解决方法:
使用map()创建数据集,让map里面的函数直接把图片转为tensor而不是numpy类型。

#load是map()使用的函数,要确保load()返回的是tensor数据
@tf.function #加入这行代码可以提高速度
def load(image_file):
image = tf.io.read_file(image_file)
image = tf.image.decode_jpeg(image)

添加对图片处理的代码

return image1,image2

train_dataset = tf.data.Dataset.list_files(’/文件路径/*.jpg’)
train_dataset = train_dataset.map(load, num_parallel_calls=tf.data.experimental.AUTOTUNE)

#num_parallel这个参数与图片并行读取有关。上面的设置可以并行读取图片。

官方对由numpy数据和tf.data.Dataset.from_tensor_slices((x, y))创建数据集的提醒:
Note: The above code snippet will embed the features and labels arrays in your TensorFlow graph as tf.constant() operations. This works well for a small dataset, but wastes memory—because the contents of the array will be copied multiple times—and can run into the 2GB limit for the tf.GraphDef protocol buffer.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值