Reputation: 384
I'm new to tensorflow and basically I copied the example somewhere but cannot compile it.
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()
This gives the error :
TypeError: float() argument must be a string or a number, not 'Tensor'
on the second-last line.
However I've tried loss.eval()
, which says No default session is registered.
But if I write
tf.Session() as sess:
print(sess.run(loss))
it leads to some really complicated error.
If I write print(loss.numpy())
, it says AttributeError: 'Tensor' object has no attribute 'numpy'
Everything solution I searched on the internet required the code to have a tf.Session()
running, which in this example there isn't. How do I print out the value of the loss
variable?
Upvotes: 0
Views: 66
Reputation: 4475
If you're using tf-1.x, you should put tf.enable_eager_execution()
at first. I only add this line and the code works.
Upvotes: 1