我是tensorflow的新手,基本上我将示例复制到了某个地方但无法编译。
import tensorflow as tf
from tensorflow.keras import datasets, layers, optimizers, Sequential, metrics
(xs, ys),_ = datasets.mnist.load_data()
print('datasets:', xs.shape, ys.shape, xs.min(), xs.max())
xs = tf.convert_to_tensor(xs, dtype=tf.float32) / 255.
db = tf.data.Dataset.from_tensor_slices((xs,ys))
db = db.batch(32).repeat(10)
network = Sequential([layers.Dense(256, activation='relu'),
layers.Dense(256, activation='relu'),
layers.Dense(256, activation='relu'),
layers.Dense(10)])
network.build(input_shape=(None, 28*28))
network.summary()
optimizer = optimizers.SGD(lr=0.01)
acc_meter = metrics.Accuracy()
for step, (x,y) in enumerate(db):
with tf.GradientTape() as tape:
x = tf.reshape(x, (-1, 28*28))
out = network(x)
y_onehot = tf.one_hot(y, depth=10)
loss = tf.square(out-y_onehot)
loss = tf.reduce_sum(loss) / 32
acc_meter.update_state(tf.argmax(out, axis=1), y)
grads = tape.gradient(loss, network.trainable_variables)
optimizer.apply_gradients(zip(grads, network.trainable_variables))
if step % 200==0:
print(float(loss))
exit()
这给出了错误:
TypeError: float() argument must be a string or a number, not 'Tensor'
倒数第二行。
但是我尝试过loss.eval()
,它表示No default session is registered.
,但是如果我写
tf.Session() as sess:
print(sess.run(loss))
它会导致一些非常复杂的错误。
如果我写print(loss.numpy())
,它说AttributeError: 'Tensor' object has no attribute 'numpy'
我在Internet上搜索的所有解决方案都要求代码运行tf.Session()
,而在此示例中却没有。如何打印loss
变量的值?
答案 0 :(得分:1)
如果您使用的是tf-1.x,则应首先放置tf.enable_eager_execution()
。我只添加了这一行,代码就起作用了。