import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import datasets, layers, optimizers, Sequential, metrics
import os
os.environ ['TF_CPP_MIN_LOG_LEVEL'] = "2"
os.environ ['CUDA_VISIBLE_DEVICES'] = '0'
def preprocess (x, y):
x = tf.cast (x, dtype=tf.float32)/255.0
y = tf.cast (y, dtype=tf.int32)
return x, y
(x, y), (x_test, y_test) = tf.keras.datasets.fashion_mnist.load_data ()
print (x.shape, y.shape, x_test.shape, y_test.shape)
batchsize = 128
db = tf.data.Dataset.from_tensor_slices ((x,y))
db = db.map (preprocess).shuffle (10000).batch (batchsize)
db_test = tf.data.Dataset.from_tensor_slices ((x_test,y_test))
db_test = db_test.map (preprocess).batch (batchsize)
db_iter = iter (db)
sample = next (db_iter)
print (sample [0].shape, sample [1].shape)
model = keras.Sequential ([
layers.Dense (256, activation=tf.nn.relu),
layers.Dense (128, activation=tf.nn.relu),
layers.Dense (64, activation=tf.nn.relu),
layers.Dense (32, activation=tf.nn.relu),
layers.Dense (10)
])
model.build (input_shape=[None, 28*28])
model.summary ()
optimizer = optimizers.Adam (lr=1e-3)
def main ():
for epoch in range (30):
for step, (x, y) in enumerate (db):
x = tf.reshape (x, [-1, 28*28])
with tf.GradientTape () as tape:
y_onehot = tf.one_hot (y,depth=10)
logits = model (x)
loss1 = tf.reduce_mean (tf.losses.MSE (y_onehot, logits))
loss2 = tf.reduce_mean (tf.losses.categorical_crossentropy (y_onehot, logits, from_logits=True))
grads = tape.gradient (loss1, model.trainable_variables)
optimizer.apply_gradients (zip (grads,model.trainable_variables))
if step % 100 == 0:
print (epoch, step, "loss:", float (loss1), float (loss2))
total_correct = 0
total_num = 0
for x,y in db_test:
x = tf.reshape (x, [-1, 28 * 28])
logits = model (x)
prob = tf.nn.softmax (logits, axis=1)
pred = tf.argmax (prob, axis=1)
pred = tf.cast (pred, dtype=tf.int32)
correct = tf.equal (pred, y)
correct = tf.reduce_sum (tf.cast (correct, dtype=tf.int32))
total_correct += int (correct)
total_num +=x.shape [0]
acc = total_correct / total_num
print (epoch, "acc:", acc)
if __name__ == '__main__':
main ()
Traceback (most recent call last):
File "E:/Python_code/test/FashionMnist_layer", line 30, in <module>
model = keras.Sequential ([
File "D:\Program\Python\lib\site-packages\tensorflow\python\training\tracking\base.py", line 457, in _method_wrapper
result = method (self, *args, **kwargs)
File "D:\Program\Python\lib\site-packages\tensorflow\python\keras\engine\sequential.py", line 116, in __init__
super (functional.Functional, self).__init__( # pylint: disable=bad-super-call
File "D:\Program\Python\lib\site-packages\tensorflow\python\training\tracking\base.py", line 457, in _method_wrapper
result = method (self, *args, **kwargs)
File "D:\Program\Python\lib\site-packages\tensorflow\python\keras\engine\training.py", line 308, in __init__
self._init_batch_counters ()
File "D:\Program\Python\lib\site-packages\tensorflow\python\training\tracking\base.py", line 457, in _method_wrapper
result = method (self, *args, **kwargs)
File "D:\Program\Python\lib\site-packages\tensorflow\python\keras\engine\training.py", line 317, in _init_batch_counters
self._train_counter = variables.Variable (0, dtype='int64', aggregation=agg)
File "D:\Program\Python\lib\site-packages\tensorflow\python\ops\variables.py", line 262, in __call__
return cls._variable_v2_call (*args, **kwargs)
File "D:\Program\Python\lib\site-packages\tensorflow\python\ops\variables.py", line 244, in _variable_v2_call
return previous_getter (
File "D:\Program\Python\lib\site-packages\tensorflow\python\ops\variables.py", line 237, in <lambda>
previous_getter = lambda **kws: default_variable_creator_v2 (None, **kws)
File "D:\Program\Python\lib\site-packages\tensorflow\python\ops\variable_scope.py", line 2633, in default_variable_creator_v2
return resource_variable_ops.ResourceVariable (
File "D:\Program\Python\lib\site-packages\tensorflow\python\ops\variables.py", line 264, in __call__
return super (VariableMetaclass, cls).__call__(*args, **kwargs)
File "D:\Program\Python\lib\site-packages\tensorflow\python\ops\resource_variable_ops.py", line 1507, in __init__
self._init_from_args (
File "D:\Program\Python\lib\site-packages\tensorflow\python\ops\resource_variable_ops.py", line 1661, in _init_from_args
handle = eager_safe_variable_handle (
File "D:\Program\Python\lib\site-packages\tensorflow\python\ops\resource_variable_ops.py", line 242, in eager_safe_variable_handle
return _variable_handle_from_shape_and_dtype (
File "D:\Program\Python\lib\site-packages\tensorflow\python\ops\resource_variable_ops.py", line 174, in _variable_handle_from_shape_and_dtype
gen_logging_ops._assert ( # pylint: disable=protected-access
File "D:\Program\Python\lib\site-packages\tensorflow\python\ops\gen_logging_ops.py", line 49, in _assert
_ops.raise_from_not_ok_status (e, name)
File "D:\Program\Python\lib\site-packages\tensorflow\python\framework\ops.py", line 6843, in raise_from_not_ok_status
six.raise_from (core._status_to_exception (e.code, message), None)
File "<string>", line 3, in raise_from
tensorflow.python.framework.errors_impl.InvalidArgumentError: assertion failed: [0] [Op:Assert] name: EagerVariableNameReuse