Keras mixed with TensorFlow Keras and TensorFlow using tensorfow Fly Keras
Recently, TensorFlow has updated its new version to 1.4. Many updates have been made, and it is of course important to add Tf.keras. After all, Keras for the convenience of the model building everyone is obvious to all.
Likes the Keras style model constructs but does not like the TensorFlow way.
But the individual feels that TensorFlow's flexibility for the definition of loss function is very convenient, so the idea of putting the advantages together is a study of how to mix the process.
As we all know, Keras build a model in two ways, sequential and function (. These two ways, and the function of building each layer returned is the tensor result, which is tensorflow inside the pair. So do the following:
Import TensorFlow as TF from tensorflow.examples.tutorials.mnist import input_data # Build Module img = Tf.placeholder (Tf.float32, shape= (None, 784)) labels = Tf.placeholder (Tf.float32, shape= (none)) x = tf. Keras.layers.Dense (activation= ' Relu ') (img) x = tf.keras.layers.Dense (+, activation= ' Relu ') (x) prediction = TF.K Eras.layers.Dense (activation= ' Softmax ') (x) loss = Tf.reduce_mean (Tf.nn.sigmoid_cross_entropy_with_logits ( Logits=prediction, labels=labels)) Train_optim = Tf.train.AdamOptimizer (). Minimize (loss) Mnist_data = Input_da Ta.read_data_sets (' mnist_data/', one_hot=true) with TF. Session () as Sess:init = Tf.global_variables_initializer () sess.run (init) for _ in range: Batch_x, BATC h_y = Mnist_data.train.next_batch (Sess.run) (Train_optim, feed_dict={img:batch_x, labels:batch_y}) acc_pred = Tf.keras.metrics.categorical_accuracy (labels, prediction) pred = Sess.run (acc_pred, feEd_dict={labels:mnist_data.test.labels, img:mnist_data.test.images}) print (' accuracy:%.3f '% (sum (pred)/len (mnist
_data.test.labels)))