简体   繁体   中英

How can I alternate tf.Session.run in TensorFlow2.0?

Hi I've started learning machine learning by TensorFlow. I've learned codes below and realized that these doesn't work anymore.

sess = tf.Session()

print(sess.run(hello))
print(sess.run([a, b, c]))

sess.close

It would be grateful someone can help me how to change these codes work. Since I'm not English native and this is my first question on Stack overflow, I'm sorry for if you feel any uncomfort

In Tensorflow 2.0, You can use tf.compat.v1.Session() instead of tf.session()

Please refer code in TF 1.X in below

%tensorflow_version 1.x

import tensorflow as tf
print(tf.__version__)

with tf.Session() as sess:
  output = tf.constant(""Hello, World"")

  print(sess.run(output).decode())

  sess.close()

Output:

1.15.2
Hello, World

Please refer code in TF 2.X in below

%tensorflow_version 2.x

import tensorflow as tf
print(tf.__version__)

with tf.compat.v1.Session() as sess:
  output = tf.constant(""Hello, World"")

  print(sess.run(output).decode())

  sess.close()

Output:

2.2.0-rc3
Hello, World

I probably believe that you might be using Tensorflow version2. Let me help you with your query:

x = tf.Variable("Hello")
y = tf.Variable(" World")

add = tf.add(x, y)
tf.print(add)

output: Hello World

Note: Make sure that you use the same data types, I have made use of string while initiating x , y .

In your case, I guess you might have used

x = tf.Variable("Hello")
y =tf.Variable([a,b,c])

your y should be y = tf.Variable(["a", "b", "c"])

This would give you the output:

"Hello" ["a" "b" "c"]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM