Keras程序占用了太多内存

时间:2018-05-14 20:05:35

标签: python tensorflow keras tensor

我一直在尝试构建一个输出图像二进制哈希的网络。 为此,我并排使用两个Vgg-19网络,并通过两个图像进行训练,使得如果图像相似则最终散列更接近,反之亦然。我正在使用带有12 GB RAM的Geforce GTX 1080 这是一个用于训练模型的代码片段:

#positive images
prim_model.fit(data[index][0], temp_label, epochs=1, verbose=0)
sec_model.fit(data[index][i], temp_label, epochs=1, verbose=0) 
model_vars._calculate_binary([prim_model, sec_model], [index, 0, index, i])

#negative images
prim_model.fit(data[index][0], temp_label, epochs=1, verbose=0)
sec_model.fit(data[index][i], temp_label, epochs=1, verbose=0) 
model_vars._calculate_binary([prim_model, sec_model], [index, 0, index, i])

这里model_vars是一个包含模型所有重要变量的对象,如

U = a tensor of shape (64, 3200) where 64 is binary bits of output and 3200 is number of images and U represents the output of all the images from prim_model(first model)
V = a tensor of same shape which holds output of sec_model
B = a tensor of shape(16, 3200) storing the final binary values of output

现在在每次拟合操作之后(即图像作为成对传递,我们将生成散列,其他包括一个相似的图像和一个负像图像[索引] [0]是目标图像和一个拟合数据[ index] [i]将包含相似的图像,在另一个拟合中它将包含不同的图像)。这里Kbit值是64 在通过一对后,我使用calculate_binary函数计算B张量,该函数为

for index in xrange(3200):

        Q = some_calculations (a 2-d tenor of shape(16, 3200)


        Q_star_c =  tf.reshape(tf.transpose(Q)[:, (index)], [self.kbit, 1] )    #extracting a column from Q
        U_star_c =  #A column extracted from U
        V_star_c =  #A column extracted from V

        self.U_1 = tf.concat( [ self.U[:, 0:index], self.U[:, index+1: self.total_images]] , axis=1) #Removing the column extracted above from the original now the size of U_1 is (16, 3199)
        self.V_1 = #same as above
        self.B = #slicing the original B tensor


        #Now doing some calcultion to calculate B_star_c (binary value of index'th image
        B_star_c =  tf.scalar_mul(-1, \
                    tf.sign(tf.add(tf.matmul(tf.scalar_mul(2, self.B), \
                    tf.add(tf.matmul(self.U_1, U_star_c, transpose_a=True), tf.matmul(self.V_1, V_star_c, transpose_a=True)) ) , Q_star_c)) )

        #Now combining the final generated binary column to the original Binary tensor making the size of B to be (16, 3200) again
        self.B = tf.concat( [ self.B[:, 0:index], tf.concat( [B_star_c, self.B[:, index:self.total_images]], axis=1)], axis=1)

现在,在完成超过100/3200的图像后,我的代码内存不足。它是由calculate_binary函数引起的(因为每当我停止使用它时问题就解决了)当我使用htop查看内存状态时,它显示完全消耗32GB / 32GB甚至使用交换空间。如何减少增加的内存问题。(我也试过将代码转移到numpy数组仍然出现同样的问题)

1 个答案:

答案 0 :(得分:0)

我猜它是self.B的tf.concat ......

因为每次函数运行时它都会连接self.B越来越大。您可以通过在每次迭代时打印其大小来检查哪个张量导致内存错误。