Skip to main content
 首页 » 编程设计

python之为什么我的 Tensorflow 神经网络在我开始训练后运行如此缓慢

2024年09月03日28unruledboy

我的 Tensorflow 神经网络 在训练时变得越来越慢。每次我训练网络时,它的 Action 都越来越慢。

在第 30 次左右的训练迭代之后,它变得慢得无法忍受,并且几乎无法使用。到第 60 次左右的迭代时,程序停止响应。

我没想到这个神经网络这么复杂。这是一个简单的三层网络,与 Tensorflow 组合在一起。

你们知道如何解决这个问题吗?

import tensorflow as tf 
 
hidden_1_layer = {'weights': tf.Variable(tf.random_normal([37500, 500])), 
                  'biases': tf.Variable(tf.random_normal([500]))} 
hidden_2_layer = {'weights': tf.Variable(tf.random_normal([500, 250])), 
                  'biases': tf.Variable(tf.random_normal([250]))} 
hidden_3_layer = {'weights': tf.Variable(tf.random_normal([250, 125])), 
                  'biases': tf.Variable(tf.random_normal([125]))} 
output_layer = {'weights': tf.Variable(tf.random_normal([125, 1])), 
                'biases': tf.Variable(tf.random_normal([1]))} 
 
class ImageNN(): 
    def train(self, array, target): 
        x = tf.placeholder('float', name='x') 
        l1 = tf.add(tf.matmul(x, hidden_1_layer['weights']), hidden_1_layer['biases']) 
        l1 = tf.nn.relu(l1) 
        l2 = tf.add(tf.matmul(l1, hidden_2_layer['weights']), hidden_2_layer['biases']) 
        l2 = tf.nn.relu(l2) 
        l3 = tf.add(tf.matmul(l2, hidden_3_layer['weights']), hidden_3_layer['biases']) 
        l3 = tf.nn.relu(l3) 
        output = tf.add(tf.matmul(l3, output_layer['weights']), output_layer['biases']) 
        output = tf.nn.sigmoid(output) 
        cost = tf.square(output-target) 
        optimizer = tf.train.AdamOptimizer().minimize(cost) 
        array = array.reshape(1, 37500) 
        with tf.Session() as sess: 
            sess.run(tf.global_variables_initializer()) 
            sess.run(optimizer, feed_dict={x: array}) 
            sess.close() 
        del x, l1, l2, output, cost, optimizer 
 
    #Do computations with our artificial nueral network 
    def predict(self, data):          #Input data is of size (37500,) 
        x = tf.placeholder('float', name='x')    #get data into the right rank (dimensions), this is just a placeholder, it has no values 
        l1 = tf.add(tf.matmul(x, hidden_1_layer['weights']), hidden_1_layer['biases']) 
        l1 = tf.nn.relu(l1) 
        l2 = tf.add(tf.matmul(l1, hidden_2_layer['weights']), hidden_2_layer['biases']) 
        l2 = tf.nn.relu(l2) 
        l3 = tf.add(tf.matmul(l2, hidden_3_layer['weights']), hidden_3_layer['biases']) 
        l3 = tf.nn.relu(l3) 
        output = tf.add(tf.matmul(l3, output_layer['weights']), output_layer['biases']) 
        output = tf.nn.sigmoid(output) 
        data = data.reshape(1, 37500) 
        with tf.Session() as sess: 
            sess.run(tf.global_variables_initializer()) 
            theOutput = sess.run(output, feed_dict={x: data}) 
            sess.close() 
        del x, l1, l2, output, data 
        return theOutput 

请您参考如下方法:

这听起来像是内存问题。您没有删除 train 方法中的 l3 或 array ,也没有删除 predict 方法中的 l3 。我不认为这是问题的原因,因为无论如何我相信它应该被 Python 解释器丢弃。

你如何称呼这个类?可能是您在内存中保留输出并且它变得非常大。