Kevin Kim
Kevin Kim

Reputation: 31

Can't print the output of the neural network in tensorflow

import numpy as np
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior


class DQNagent:

    def __init__(self, session, structure, input_dim, output_dim):
        self.session = session
        self.structure = structure
        self.input_dim = input_dim
        self.output_dim = output_dim
        self.input_vec = tf.placeholder(tf.float32, shape=[None, self.input_dim])
        self.network = self.create_model()

    def create_model(self):

        for i in range(0, len(self.structure)-1):
            if i == 0:
                network = tf.layers.Dense(self.structure[i], tf.keras.activations.relu)(self.input_vec)
                network = tf.layers.BatchNormalization()(network)
            else:
                network = tf.layers.Dense(self.structure[i], tf.keras.activations.relu)(network)
                network = tf.layers.BatchNormalization()(network)

        network = tf.layers.Dense(self.output_dim, tf.keras.activations.linear)(network)

        return network

    def temp_func(self, input_data):
        temp_input_data = np.expand_dims(input_data, 0)
        output_vec = self.session.run(self.network, feed_dict={self.input_vec: temp_input_data})
        print(output_vec)

So for the above code, I implemented a simple, sequential, fully connected NN and temp_func is meant to print the output of the NN given an np array

So I tested it by creating an artificial example with an np array via

data = []
for _ in range(10):
    data.append(np.random.normal(0.0,1.0))

NNstructure = []
for _ in range(2):
    NNstructure.append(10)

So the NNstructure[i] represents the number of neurons at i'th layer Then I created a session,

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    dqn = DQNagent(sess, NNstructure, len(data), 5)
    dqn.temp_func(data)

and in theory, it should print out the output of the NN with this artificially generated "data" and if I code all these without using the concept of classes, it runs well.

The error message I'm getting is

tensorflow.python.framework.errors_impl.FailedPreconditionError: Attempting to use uninitialized value dense_1/kernel
 [[{{node dense_1/kernel/read}}]]

Upvotes: 0

Views: 123

Answers (1)

thushv89
thushv89

Reputation: 11333

You are creating your variables after doing variable initialization (so there's nothing being initialized). Need to change the order of the of the following lines.

sess.run(tf.global_variables_initializer())
dqn = DQNagent(sess, NNstructure, len(data), 5)

to

dqn = DQNagent(sess, NNstructure, len(data), 5)
sess.run(tf.global_variables_initializer())


Upvotes: 1

Related Questions