我写了一个简单的TensorFlow代码,但不断遇到TypeError错误。我试图编写一个简单的对数回归代码。错误出现在这一行:logits = tf.matmul(img,w) + b,错误如下:
Traceback (most recent call last): File "test.py", line 22, in <module> logits = tf.matmul(img,w) + b File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/math_ops.py", line 2122, in matmul a, b, transpose_a=transpose_a, transpose_b=transpose_b, name=name) File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/gen_math_ops.py", line 4279, in mat_mul name=name) File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/op_def_library.py", line 546, in _apply_op_helper inferred_from[input_arg.type_attr])) TypeError: Input 'b' of 'MatMul' Op has type float32 that does not match type float64 of argument 'a'
请帮助我解决这个问题。以下是我的代码:
import tensorflow as tfimport numpy as np#制作虚拟数据集并将其转换为张量对象x = (np.random.sample((100,2)), np.random.sample((100,1)))train_data = tf.data.Dataset.from_tensor_slices(x)y = (np.random.sample((10,2)), np.random.sample((10,1)))test_data = tf.data.Dataset.from_tensor_slices(y)#创建迭代器以访问数据集train_iterator = train_data.make_initializable_iterator()img, label = train_iterator.get_next()#定义权重和偏置w = tf.get_variable("weight", initializer=tf.constant((0.0)))b = tf.get_variable("bias", initializer=tf.constant((0.0)))tf.cast(img, tf.float64)tf.cast(w, tf.float64)tf.cast(b, tf.float64)#模型 logits = tf.matmul(img,w) + b#损失entropy = tf.nn.softmax_cross_entropy_with_logits(labels=label, logits=logits)loss = tf.reduce_mean(entropy)#优化器optimizer = tf.train.AdamOptimizer(learning_rate=0.01).minimize(loss)#创建会话with tf.Session() as sess: sess.run(train_iterator.initializer) for i in range(100): sess.run([optimizer,loss]) print(optimizer,loss)
回答:
您没有将tf.cast()
的结果保存回变量中。尝试以下方法来修复它。
img = tf.cast(img, tf.float64) w = tf.cast(w, tf.float64)b = tf.cast(b, tf.float64)