Johnny Lam
Johnny Lam

Reputation: 53

tensorflow placeholder in function

Now, I have a bit of code like below:

import tensorflow as tf

x = tf.placeholder(tf.float32, [1, 3])
y = x * 2

with tf.Session() as sess:
    result = sess.run(y, feed_dict={x: [2, 4, 6]})
    print(result)

I want to feed values to a function.

Below is an obvious wrong. How do I suppose to do that?

import tensorflow as tf

def place_func():
    x = tf.placeholder(tf.float32, [1, 3])
    y = x * 2

with tf.Session() as sess:
    result = sess.run(y, feed_dict={x: [2, 4, 6]})
    print(result)

Upvotes: 1

Views: 1727

Answers (1)

Dmytro Danevskyi
Dmytro Danevskyi

Reputation: 3159

One option is to run a session inside of function just as follows:

import tensorflow as tf

def my_func(data):
    x = tf.placeholder(tf.float32, [1, 3])
    y = x * 2
    return sess.run(y, feed_dict = {x: data})

with tf.Session() as sess:
    result = my_func([[2, 4, 6]])
    print(result)

You could also create a class and let x to be a field of that class.

Upvotes: 2

Related Questions