Есть ли способ отладки кода TensorFlow?Кроме того, как я могу видеть, что находится в переменных или объектах, пока я интерпретирую код? - PullRequest
1 голос
/ 04 мая 2019

По-настоящему легко отлаживать и отслеживать значения переменных и объектов при запуске кода Python, но в тензорном потоке действительно трудно увидеть, что происходит за кулисами. Я знаю, что tennsflow работает в графиках, и вы должны запустить сеанс. Есть ли более простой способ увидеть значения при интерпретации кода? Я прикрепил скриншот ниже, где вы можете отслеживать каждое значение переменной, но в тензорном потоке я не могу этого сделать. Я устал, я использовал tf.print () и tf.eval () в сессии.

Pycharm Showing Variables Values Вот код тензорного потока, и я хочу, чтобы увидеть значения Z3 и Forext_op

def model(X_train, Y_train, X_test, Y_test, learning_rate=0.01,


ops.reset_default_graph()  # to be able to rerun the model without overwriting tf variables
tf.set_random_seed(1)  # to keep results consistent (tensorflow seed)
seed = 3  # to keep results consistent (numpy seed)
(m, n_H0, n_W0, n_C0) = X_train.shape
n_y = Y_train.shape[1]
costs = []  # To keep track of the cost

# Create Placeholders of the correct shape
X, Y = create_placeholders(n_H0, n_W0, n_C0, n_y)

# Initialize parameters
parameters = initialize_parameters()

# Forward propagation: Build the forward propagation in the tensorflow graph
Z3 = forward_propagation(X, parameters)

# Cost function: Add cost function to tensorflow graph
cost = compute_cost(Z3, Y)


# Backpropagation: Define the tensorflow optimizer. Use an AdamOptimizer that minimizes the cost.

optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)


# Initialize all the variables globally
init = tf.global_variables_initializer()

# Start the session to compute the tensorflow graph
with tf.Session() as sess:

    # Run the initialization
    sess.run(init)

    # Do the training loop
    for epoch in range(num_epochs):

        minibatch_cost = 0.
        num_minibatches = int(m / minibatch_size)  # number of minibatches of size minibatch_size in the train set
        seed = seed + 1
        minibatches = random_mini_batches(X_train, Y_train, minibatch_size, seed)

        for minibatch in minibatches:
            # Select a minibatch
            (minibatch_X, minibatch_Y) = minibatch
            # IMPORTANT: The line that runs the graph on a minibatch.
            # Run the session to execute the optimizer and the cost, the feedict should contain a minibatch for (X,Y).

            _, temp_cost = sess.run([optimizer, cost], feed_dict={X: minibatch_X, Y: minibatch_Y})


            minibatch_cost += temp_cost / num_minibatches

        # Print the cost every epoch
        if print_cost == True and epoch % 5 == 0:
            print("Cost after epoch %i: %f" % (epoch, minibatch_cost))
        if print_cost == True and epoch % 1 == 0:
            costs.append(minibatch_cost)



    # Calculate the correct predictions
    predict_op = tf.argmax(Z3, 1)
    correct_prediction = tf.equal(predict_op, tf.argmax(Y, 1))
    # Calculate accuracy on the test set
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
    print(accuracy)
    train_accuracy = accuracy.eval({X: X_train, Y: Y_train})
    test_accuracy = accuracy.eval({X: X_test, Y: Y_test})
    print("Train Accuracy:", train_accuracy)
    print("Test Accuracy:", test_accuracy)

    return train_accuracy, test_accuracy, parameters

1 Ответ

0 голосов
/ 04 мая 2019

Вы можете попробовать TensorFlow Eager Execution, которая позволяет запускать код TensorFlow напрямую, без необходимости строить график и запускать его во время сеанса. В описании даже сказано, что это облегчает отладку.

https://www.tensorflow.org/guide/eager

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...