我编写了一个简单的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 tf
import numpy as np
#making dummy dataset and converting that in tensor object
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)
#making iteration to access the dataset
train_iterator = train_data.make_initializable_iterator()
img, label = train_iterator.get_next()
#define weights & biases
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)
#model
logits = tf.matmul(img,w) + b
#loss
entropy = tf.nn.softmax_cross_entropy_with_logits(labels=label, logits=logits)
loss = tf.reduce_mean(entropy)
#optimizer
optimizer = tf.train.AdamOptimizer(learning_rate=0.01).minimize(loss)
#create the session
with tf.Session() as sess:
sess.run(train_iterator.initializer)
for i in range(100):
sess.run([optimizer,loss])
print(optimizer,loss)
答案 0 :(得分:0)
您没有将tf.cast()
结果保存回变量。请尝试以下修复它。
img = tf.cast(img, tf.float64)
w = tf.cast(w, tf.float64)
b = tf.cast(b, tf.float64)