代码
import tensorflow as tf
tf.compat.v1.disable_eager_execution()
x_train = [1.0, 2.0, 3.0, 4.0]
y_train = [-1.0, -2.0, -3.0, -4.0]
W = tf.Variable(initial_value=[1.0], dtype=tf.float32)
b = tf.Variable(initial_value=[1.0], dtype=tf.float32)
x = tf.compat.v1.placeholder(dtype=tf.float32)
y_input = tf.compat.v1.placeholder(dtype=tf.float32)
y_output = W * x + b
loss = tf.reduce_sum(input_tensor=tf.square(x=y_output - y_input))
optimizer = tf.compat.v1.train.GradientDescentOptimizer(learning_rate=0.01)
train_step = optimizer.minimize(loss=loss)
session = tf.compat.v1.Session()
session.run(tf.compat.v1.variables_initializer())
print(session.run(fetches=loss, feed_dict={x: x_train, y_input: y_train}))
for _ in range(1000):
session.run(fetches=train_step, feed_dict={x: x_train, y_input: y_train})
print(session.run(fetches=[loss, W, b], feed_dict={x: x_train, y_input: y_train}))
print(session.run(fetches=y_output, feed_dict={x: [5.0, 10.0, 15.0]}))
错误
Traceback (most recent call last):
File "D:/phycarm projects/linearRegression.py", line 20, in <module>
session.run(tf.compat.v1.variables_initializer())
TypeError: variables_initializer() missing 1 required positional argument: 'var_list'
Process finished with exit code 1
好,只需在变量initailizer中添加var_list,如下所示
你只需要键入你在变量列表中定义的变量
session.run(tf.compat.v1.variables_initializer(var_list=[W,b])
这是正确的代码:-
import tensorflow as tf
tf.compat.v1.disable_eager_execution()
x_train = [1.0, 2.0, 3.0, 4.0]
y_train = [-1.0, -2.0, -3.0, -4.0]
W = tf.Variable(initial_value=[1.0], dtype=tf.float32)
b = tf.Variable(initial_value=[1.0], dtype=tf.float32)
x = tf.compat.v1.placeholder(dtype=tf.float32)
y_input = tf.compat.v1.placeholder(dtype=tf.float32)
y_output = W * x + b
loss = tf.reduce_sum(input_tensor=tf.square(x=y_output - y_input))
optimizer = tf.compat.v1.train.GradientDescentOptimizer(learning_rate=0.01)
train_step = optimizer.minimize(loss=loss)
session = tf.compat.v1.Session()
session.run(tf.compat.v1.variables_initializer(var_list=[W, b]))
print(session.run(fetches=loss, feed_dict={x: x_train, y_input: y_train}))
for _ in range(1000):
session.run(fetches=train_step, feed_dict={x: x_train, y_input: y_train})
print(session.run(fetches=[loss, W, b], feed_dict={x: x_train, y_input: y_train}))
print(session.run(fetches=y_output, feed_dict={x: [5.0, 10.0, 15.0]}))