Akiiino
Akiiino

Reputation: 1100

Why do the Variables not update in this program?

So, I have this bit of code:

graph = tf.Graph()

with graph.as_default():
    res  = tf.Variable(
        np.zeros((100, 100), dtype=np.float32)
    )

    mask = tf.placeholder(np.float32, (100, 100))
    res = tf.add(res, mask)

    init = tf.global_variables_initializer()

with tf.Session(graph=graph) as sess:
    sess.run(init)
    for i in range(100):
        x1, x2, y1, y2 = np.random.randint(0, 100, 4)
        x1, x2 = sorted((x1, x2))
        y1, y2 = sorted((y1, y2))

        c_mask = np.zeros((100, 100))
        c_mask[x1:x2, y1:y2] = 255

        new_pic = sess.run([res], feed_dict={mask:c_mask})[0]

fig = plt.figure()
ax = fig.add_subplot(111)

ax.imshow(new_pic.astype('uint8'), cmap='gray')
fig.show()

Basically, it (at least is supposed to) draws 100 random white rectangles on a black field. But what I get is this:

WTF

I do not understand. It looks like every iteration res just resets to bing a black slate again (the rectangle on the picture is the last one drawn, judging by the coordinates). Am I not saving it somehow, or what is it that I'm doing wrong?

Upvotes: 0

Views: 54

Answers (1)

weitang114
weitang114

Reputation: 1303

Change these two lines:

res = tf.add(res, mask)
##
new_pic = sess.run([res], feed_dict={mask:c_mask})[0]

to

update_op = res.assign(tf.add(res, mask))
##
new_pic = sess.run([res, update_op], feed_dict={mask:c_mask})[0]

A tensor should me modified with Variable.assign().

While you intended to update the tensor "res", the first line doesn't update it but only creates another tensor, and the name "res" is assigned to the new tensor. Hence the original res is never updated.

Upvotes: 1

Related Questions