import tensorflow as tf ## create a graph g = tf.Graph() # 此处替换掉placeholder,是因为 "placeholder" 不再是 TensorFlow 的一部分了。在 TensorFlow 2.0 中, # 它已被弃用,并被 tf.compat.v1.placeholder 替换。在新版本中建议使用tf.function和tf.Tensor来完成相同的功能. with g.as_default(): # x = tf.placeholder(dtype=tf.float32, # shape=(None), name='x') x = tf.Tensor(dtype=tf.float32, shape=(None), name='x') w = tf.Variable(2.0, name='weight') b = tf.Variable(0.7, name='bias') z = w*x + b init = tf.global_variables_initializer() ## create a session and pass in graph g with tf.Session(graph=g) as sess: ## initialize w and b: sess.run(init) ## evaluate z: for t in [1.0, 0.6, -1.8]: print('x=%4.1f --> z=%4.1f'%( t, sess.run(z, feed_dict={x:t})))
时间: 2024-04-01 10:33:59 浏览: 17
This code creates a TensorFlow graph that defines a linear regression model and evaluates it for different values of the input variable `x`.
The graph is defined using the `tf.Graph()` context manager, which creates a new graph and sets it as the default graph for all subsequent operations inside the context.
Inside the graph, a TensorFlow `Tensor` object is created to represent the input variable `x`. Note that the `tf.placeholder()` function is replaced with `tf.Tensor()` because `tf.placeholder()` is deprecated in TensorFlow 2.0.
Two TensorFlow `Variable` objects are also created to represent the model parameters `w` and `b`, which are initialized to 2.0 and 0.7, respectively.
Finally, a TensorFlow operation is defined to compute the output `z` of the linear regression model, which is simply the product of `w` and `x`, plus `b`.
A TensorFlow `Session` object is created to run the graph. The `global_variables_initializer()` function is used to initialize the variables `w` and `b`. Then, the `z` operation is evaluated for three different values of `x` (1.0, 0.6, and -1.8), and the results are printed to the console.