我在TensorFlow中实现了计算均方误差的损失函数。所有用于计算目标的张量都是float64类型,因此损失函数本身是dtype float64。特别是,tensorflow损失最小化类型错误
print cost
==> Tensor("add_5:0", shape=TensorShape([]), dtype=float64)
然而,当我试图尽量减少我得到一个值误差相对于类型的张量:
GradientDescentOptimizer(learning_rate=0.1).minimize(cost)
==> ValueError: Invalid type <dtype: 'float64'> for add_5:0, expected: [tf.float32].
我不明白为什么张的预期是D型当所有导致计算的变量都是float64类型时,为单精度浮点型。我已经确认,当我强制所有变量为float32时,计算正确执行。
有没有人有任何见识,为什么会发生这种情况?我的电脑是一台64位机器。
这里是再现行为
import tensorflow as tf
import numpy as np
# Make 100 phony data points in NumPy.
x_data = np.random.rand(2, 100) # Random input
y_data = np.dot([0.100, 0.200], x_data) + 0.300
# Construct a linear model.
b = tf.Variable(tf.zeros([1], dtype=np.float64))
W = tf.Variable(tf.random_uniform([1, 2], minval=-1.0, maxval=1.0, dtype=np.float64))
y = tf.matmul(W, x_data) + b
# Minimize the squared errors.
loss = tf.reduce_mean(tf.square(y - y_data))
optimizer = tf.train.GradientDescentOptimizer(0.5)
train = optimizer.minimize(loss)
# For initializing the variables.
init = tf.initialize_all_variables()
# Launch the graph
sess = tf.Session()
sess.run(init)
# Fit the plane.
for step in xrange(0, 201):
sess.run(train)
if step % 20 == 0:
print step, sess.run(W), sess.run(b)
了解!谢谢! – user1936768
Doens't似乎现在工作(tf v0.6)。 'TypeError:输入'ApplyGradientDescent'的'alpha'Op的类型为float32,与参数'var'的类型float64不匹配。 – colinfang
感谢您指出。我修正了答案。 – mrry