piccolo
piccolo

Reputation: 2227

Tensorflow variables do not initialise

I am trying to work out why in the two methods below, Method 2 throws an error when I try to initialise a variable in Tensorflow

import tensorflow as tf
sess = tf.InteractiveSession()

Method 1

This method works fine returning the correct output

with tf.variable_scope('layer_1'):
    W1 = tf.get_variable(name="weights1", shape=[3, 10], initializer=tf.zeros_initializer())

sess.run(tf.global_variables_initializer())

print(sess.run(W1))

Method 2

This method throws an error.

with tf.variable_scope('layer_2'):
    W2 = tf.get_variable(tf.zeros(shape=[3, 10], name="weights2"))

sess.run(tf.global_variables_initializer())

print(sess.run(W2))

The error message I receive for method 2 is:

TypeError: Expected float32, got 'layer_2/' of type 'str' instead.

Upvotes: 1

Views: 49

Answers (1)

Jonas Adler
Jonas Adler

Reputation: 10810

The first (positional) argument to tf.get_variable is the name of the variable. So your second code is equivalent to

tf.get_variable(name=tf.zeros(shape=[3, 10], name="weights2"))

Trying to use a tf.Tensor as the name of a variable does not work (I'm amazed it does not give an error earlier).

You perhaps want to instead do

tf.Variable(tf.zeros(shape=[3, 10]), name="weights2")

Upvotes: 1

Related Questions