TensorFlow&Theano&Kerash环境测试代码
2017-09-12 20:49
381 查看
TensorFlow环境测试代码:
Theano环境测试代码:
Keras环境测试代码:
#-*- coding:utf-8 -*- from tensorflow.examples.tutorials.mnist import input_data import tensorflow as tf global mnist #远程下载MNIST数据,建议先下载好并保存在MNIST_data目录下 def DownloadData(): global mnist mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) #编码格式:one-hot print(mnist.train.images.shape, mnist.train.labels.shape) print(mnist.test.images.shape, mnist.test.labels.shape) print(mnist.validation.images.shape, mnist.validation.labels.shape) def Train(): sess = tf.InteractiveSession() #Step 1 #定义算法公式Softmax Regression x = tf.placeholder(tf.float32, [None, 784]) #构建占位符,代表输入的图像,None表示样本的数量可以是任意的 W = tf.Variable(tf.zeros([784,10])) #构建一个变量,代表训练目标weights,初始化为0 b = tf.Variable(tf.zeros([10])) #构建一个变量,代表训练目标biases,初始化为0 y = tf.nn.softmax(tf.matmul(x, W) + b) #构建了一个softmax的模型:y = softmax(Wx + b),y指样本标签的预测值 #Step 2 #定义损失函数,选定优化器,并指定优化器优化损失函数 y_ = tf.placeholder(tf.float32, [None, 10]) # 构建占位符,代表样本标签的真实值 # 交叉熵损失函数 cross_entropy = -tf.reduce_sum(y_ * tf.log(y)) #y = tf.matmul(x, W) + b #cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y)) # 使用梯度下降法(0.01的学习率)来最小化这个交叉熵损失函数 train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy) #Step 3 #使用随机梯度下降训练数据 tf.global_variables_initializer().run() for i in range(1000): #迭代次数为1000 batch_xs, batch_ys = mnist.train.next_batch(100) #使用minibatch的训练数据,一个batch的大小为100 sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys}) #用训练数据替代占位符来执行训练 #Step 4 #在测试集上对准确率进行评测 correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1)) #tf.argmax()返回的是某一维度上其数据最大所在的索引值,在这里即代表预测值和真值 accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) #用平均值来统计测试准确率 print(sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels})) #打印测试信息 sess.close() if __name__ == '__main__': DownloadData(); Train();
Theano环境测试代码:
from theano import function,config,shared,sandbox import theano.tensor as T import numpy import time vlen = 10 * 30 * 768 # 10 x #cores x # threads per core iters = 1000 rng = numpy.random.RandomState(22) x = shared(numpy.asarray(rng.rand(vlen), config.floatX)) f = function([], T.exp(x)) print f.maker.fgraph.toposort() t0 = time.time() for i in xrange(iters): r = f() t1 = time.time() print 'Looping %d times took' % iters, t1 - t0, 'seconds' print 'Result is', r if numpy.any([isinstance(x.op, T.Elemwise) for x in f.maker.fgraph.toposort()]): print 'Used the cpu' else: print 'Used the gpu'
Keras环境测试代码:
# encoding: utf-8 """ @version: 1.0 @license: Apache Licence @file: test_keras2.py @time: 2016/8/17 16:51 """ import numpy as np from keras.models import Sequential from keras.layers.core import Dense, Activation from keras.optimizers import SGD from keras.utils import np_utils from keras.utils.vis_utils import plot_model def run(): # 构建神经网络 model = Sequential() model.add(Dense(4, input_dim=2, init='uniform')) model.add(Activation('relu')) model.add(Dense(2, init='uniform')) model.add(Activation('sigmoid')) sgd = SGD(lr=0.05, decay=1e-6, momentum=0.9, nesterov=True) model.compile(loss='binary_crossentropy', optimizer=sgd, metrics=['accuracy']) # 神经网络可视化 plot_model(model, to_file='model.png') if __name__ == '__main__': run()
相关文章推荐
- Ubuntu14.04 & CUDA8.0 & Theano & Tensorflow & TensorLayer & Cudnn安装血泪史
- 【环境配置】Win10+Python3.5+Keras+Theano/TensorFlow
- windows系统下的keras(Theano/Tensorflow后端)CPU以及GPU加速环境搭建
- 在U盘里配置好主流深度学习框架及GPU环境theano\tensorflow\keras\caffe\cuda7.5
- Anaconda+Tensorflow+Theano+Keras安装
- 如何选择深度学习框架 TensorFlow/Torch/Mxnet/Theano
- Ubuntu16.04 +cuda8.0+cudnn+opencv+caffe+theano+tensorflow配置明细
- 深度学习python库安装经验,Windows下安装Anaconda3 pycharm tensorflow keras theano中遇到的问题
- ubuntu 14.04 server搭建+NVIDIA+CUDA+CUDNN+caffe+theano+tensorflow+keras+matlab
- 在线配置caffe+Tensorflow+Theano+Torch+Mxnet
- windows 四行命令安装 theano tensorflow keras
- 深度学习框架keras安装(后端基于Tensorflow/theano)
- linux install Theano+Tensorflow+Keras
- Deeplearning4j 实战(8) : Keras为媒介导入Tensorflow/Theano等其他深度学习库的模型
- 翻译 | Keras : Deep Learning library for Tensorflow and Theano
- 对比Caff/Torch/Theano/TensorFlow
- TensorFlowOnSpark HDP环境搭建及Mnist部署测试过程
- Ubuntu16.04 +cuda8.0+cudnn+caffe+theano+tensorflow配置明细
- Ubuntu16.04 +cuda8.0+cudnn+caffe+theano+tensorflow配置明细
- 深度工具合集安装(Nvidia+CUDA+cuDNN+Tensorflow+OpenBLAS+Caffe+Theano+Keras+Torch+Mxnet+X2Go)