Mixed use of Keras and TensorFlow

Source: Internet
Author: User
Tags mixed keras

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)))

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.