zoukankan      html  css  js  c++  java
  • keras 与tensorflow 混合使用

    keras 与tensorflow 混合使用

    keras 与tensorflow 混合使用

    最近tensorflow更新了新版本,到1.4了。做了许多更新,当然重要的是增加了tf.keras. 毕竟keras对于模型搭建的方便大家都是有目共睹的。

    喜欢keras风格的模型搭建而不喜欢tensorflow的方式。
    但是个人觉得tensorflow的对于loss function定义的灵活性,还是非常便捷的,所以秉承着将二者的优势放在一起的想法,研究了一下如何混合的过程。

    众所周知,keras搭建模型有两种方式,Sequential 和 function(?)这两种方式,而函数式搭建每一层返回的都是tensor结果,这就和tensorflow里面的对上了。所以做了如下初探:

    
     	 
     	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, 10))
     	 
     	x = tf.keras.layers.Dense(128, activation='relu')(img)
     	x = tf.keras.layers.Dense(128, activation='relu')(x)
     	prediction = tf.keras.layers.Dense(10, 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_data.read_data_sets('MNIST_data/', one_hot=True)
     	 
     	 
     	with tf.Session() as sess:
     	init = tf.global_variables_initializer()
     	sess.run(init)
     	 
     	for _ in range(1000):
     	batch_x, batch_y = mnist_data.train.next_batch(50)
     	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)))
     	 
     	 
     	 
     	
  • 相关阅读:
    MQTT学习笔记——Yeelink MQTT维修 采用mqtt.js和paho-mqtt
    ubuntu 14.04设备OVS虚拟OpenFlow交换机配置汇总
    于iOS跳转到应用程序AppStore
    C++学习笔记33 转换操作符
    Win32 Windows规划 三
    [2014 Regional]牡丹江 H Hierarchical Notation 做题记录
    序言树,为了,序后,(递归)
    Visual Studio Code尝试体验
    2015第40周二Node学习
    2015第40周一Node学习
  • 原文地址:https://www.cnblogs.com/flyu6/p/7978456.html
Copyright © 2011-2022 走看看