具体的网址在这里:

https://github.com/tensorflow/tensorflow/tree/r0.12/tensorflow/models

一个卷积神经网络用于股票分析的例子:  https://github.com/keon/deepstock,      https://github.com/keon/deepstock

  1. import argparse
  2. import gzip
  3. import os
  4. import sys
  5. import time
  6.  
  7. import numpy
  8. import tensorflow as tf
  9.  
  10. SOURCE_URL = 'http://yann.lecun.com/exdb/mnist/'
  11. WORK_DIRECTORY = '/home/hzh/tf'
  12. IMAGE_SIZE = 28
  13. NUM_CHANNELS = 1
  14. PIXEL_DEPTH = 255
  15. NUM_LABELS = 10
  16. VALIDATION_SIZE = 5000 # Size of the validation set.
  17. SEED = 66478 # Set to None for random seed.
  18. BATCH_SIZE = 64
  19. NUM_EPOCHS = 10
  20. EVAL_BATCH_SIZE = 64
  21. EVAL_FREQUENCY = 100 # Number of steps between evaluations.
  22.  
  23. FLAGS = None
  24.  
  25. def data_type():
  26. """Return the type of the activations, weights, and placeholder variables."""
  27. if FLAGS.use_fp16:
  28. return tf.float16
  29. else:
  30. return tf.float32
  31.  
  32. def maybe_download(filename):
  33. """Download the data from Yann's website, unless it's already here."""
  34. if not tf.gfile.Exists(WORK_DIRECTORY):
  35. tf.gfile.MakeDirs(WORK_DIRECTORY)
  36. filepath = os.path.join(WORK_DIRECTORY, filename)
  37. return filepath
  38.  
  39. def extract_data(filename, num_images):
  40. """Extract the images into a 4D tensor [image index, y, x, channels].
  41. Values are rescaled from [0, 255] down to [-0.5, 0.5].
  42. """
  43. print('Extracting', filename)
  44. with gzip.open(filename) as bytestream:
  45. bytestream.read(16)
  46. buf = bytestream.read(IMAGE_SIZE * IMAGE_SIZE * num_images * NUM_CHANNELS)
  47. data = numpy.frombuffer(buf, dtype=numpy.uint8).astype(numpy.float32)
  48. data = (data - (PIXEL_DEPTH / 2.0)) / PIXEL_DEPTH
  49. data = data.reshape(num_images, IMAGE_SIZE, IMAGE_SIZE, NUM_CHANNELS)
  50. return data
  51.  
  52. def extract_labels(filename, num_images):
  53. """Extract the labels into a vector of int64 label IDs."""
  54. print('Extracting', filename)
  55. with gzip.open(filename) as bytestream:
  56. bytestream.read(8)
  57. buf = bytestream.read(1 * num_images)
  58. labels = numpy.frombuffer(buf, dtype=numpy.uint8).astype(numpy.int64)
  59. return labels
  60.  
  61. def fake_data(num_images):
  62. """Generate a fake dataset that matches the dimensions of MNIST."""
  63. data = numpy.ndarray(
  64. shape=(num_images, IMAGE_SIZE, IMAGE_SIZE, NUM_CHANNELS),
  65. dtype=numpy.float32)
  66. labels = numpy.zeros(shape=(num_images,), dtype=numpy.int64)
  67. for image in range(num_images):
  68. label = image % 2
  69. data[image, :, :, 0] = label - 0.5
  70. labels[image] = label
  71. return data, labels
  72.  
  73. def error_rate(predictions, labels):
  74. """Return the error rate based on dense predictions and sparse labels."""
  75. return 100.0 - (
  76. 100.0 *
  77. numpy.sum(numpy.argmax(predictions, 1) == labels) / predictions.shape[0])
  78.  
  79. def main(_):
  80. if FLAGS.self_test:
  81. print('Running self-test.')
  82. train_data, train_labels = fake_data(256)
  83. validation_data, validation_labels = fake_data(EVAL_BATCH_SIZE)
  84. test_data, test_labels = fake_data(EVAL_BATCH_SIZE)
  85. num_epochs = 1
  86. else:
  87. # Get the data.
  88. train_data_filename = maybe_download('train-images-idx3-ubyte.gz')
  89. train_labels_filename = maybe_download('train-labels-idx1-ubyte.gz')
  90. test_data_filename = maybe_download('t10k-images-idx3-ubyte.gz')
  91. test_labels_filename = maybe_download('t10k-labels-idx1-ubyte.gz')
  92.  
  93. # Extract it into numpy arrays.
  94. train_data = extract_data(train_data_filename, 60000)
  95. train_labels = extract_labels(train_labels_filename, 60000)
  96. test_data = extract_data(test_data_filename, 10000)
  97. test_labels = extract_labels(test_labels_filename, 10000)
  98.  
  99. # Generate a validation set.
  100. validation_data = train_data[:VALIDATION_SIZE, ...]
  101. validation_labels = train_labels[:VALIDATION_SIZE]
  102. train_data = train_data[VALIDATION_SIZE:, ...]
  103. train_labels = train_labels[VALIDATION_SIZE:]
  104. num_epochs = NUM_EPOCHS
  105. train_size = train_labels.shape[0]
  106.  
  107. # This is where training samples and labels are fed to the graph.
  108. # These placeholder nodes will be fed a batch of training data at each
  109. # training step using the {feed_dict} argument to the Run() call below.
  110. train_data_node = tf.placeholder(
  111. data_type(),
  112. shape=(BATCH_SIZE, IMAGE_SIZE, IMAGE_SIZE, NUM_CHANNELS))
  113. train_labels_node = tf.placeholder(tf.int64, shape=(BATCH_SIZE,))
  114. eval_data = tf.placeholder(
  115. data_type(),
  116. shape=(EVAL_BATCH_SIZE, IMAGE_SIZE, IMAGE_SIZE, NUM_CHANNELS))
  117.  
  118. # The variables below hold all the trainable weights. They are passed an
  119. # initial value which will be assigned when we call:
  120. # {tf.global_variables_initializer().run()}
  121. conv1_weights = tf.Variable(
  122. tf.truncated_normal([5, 5, NUM_CHANNELS, 32], # 5x5 filter, depth 32.
  123. stddev=0.1,
  124. seed=SEED, dtype=data_type()))
  125. conv1_biases = tf.Variable(tf.zeros([32], dtype=data_type()))
  126. conv2_weights = tf.Variable(tf.truncated_normal(
  127. [5, 5, 32, 64], stddev=0.1,
  128. seed=SEED, dtype=data_type()))
  129. conv2_biases = tf.Variable(tf.constant(0.1, shape=[64], dtype=data_type()))
  130. fc1_weights = tf.Variable( # fully connected, depth 512.
  131. tf.truncated_normal([IMAGE_SIZE // 4 * IMAGE_SIZE // 4 * 64, 512],
  132. stddev=0.1,
  133. seed=SEED,
  134. dtype=data_type()))
  135. fc1_biases = tf.Variable(tf.constant(0.1, shape=[512], dtype=data_type()))
  136. fc2_weights = tf.Variable(tf.truncated_normal([512, NUM_LABELS],
  137. stddev=0.1,
  138. seed=SEED,
  139. dtype=data_type()))
  140. fc2_biases = tf.Variable(tf.constant(0.1, shape=[NUM_LABELS], dtype=data_type()))
  141.  
  142. # We will replicate the model structure for the training subgraph, as well
  143. # as the evaluation subgraphs, while sharing the trainable parameters.
  144. def model(data, train=False):
  145. """The Model definition."""
  146. # 2D convolution, with 'SAME' padding (i.e. the output feature map has
  147. # the same size as the input). Note that {strides} is a 4D array whose
  148. # shape matches the data layout: [image index, y, x, depth].
  149. conv = tf.nn.conv2d(data,
  150. conv1_weights,
  151. strides=[1, 1, 1, 1],
  152. padding='SAME')
  153. # Bias and rectified linear non-linearity.
  154. relu = tf.nn.relu(tf.nn.bias_add(conv, conv1_biases))
  155. # Max pooling. The kernel size spec {ksize} also follows the layout of
  156. # the data. Here we have a pooling window of 2, and a stride of 2.
  157. pool = tf.nn.max_pool(relu,
  158. ksize=[1, 2, 2, 1],
  159. strides=[1, 2, 2, 1],
  160. padding='SAME')
  161. conv = tf.nn.conv2d(pool,
  162. conv2_weights,
  163. strides=[1, 1, 1, 1],
  164. padding='SAME')
  165. relu = tf.nn.relu(tf.nn.bias_add(conv, conv2_biases))
  166. pool = tf.nn.max_pool(relu,
  167. ksize=[1, 2, 2, 1],
  168. strides=[1, 2, 2, 1],
  169. padding='SAME')
  170. # Reshape the feature map cuboid into a 2D matrix to feed it to the
  171. # fully connected layers.
  172. pool_shape = pool.get_shape().as_list()
  173. reshape = tf.reshape(
  174. pool,
  175. [pool_shape[0], pool_shape[1] * pool_shape[2] * pool_shape[3]])
  176. # Fully connected layer. Note that the '+' operation automatically
  177. # broadcasts the biases.
  178. hidden = tf.nn.relu(tf.matmul(reshape, fc1_weights) + fc1_biases)
  179. # Add a 50% dropout during training only. Dropout also scales
  180. # activations such that no rescaling is needed at evaluation time.
  181. if train:
  182. hidden = tf.nn.dropout(hidden, 0.5, seed=SEED)
  183. return tf.matmul(hidden, fc2_weights) + fc2_biases
  184.  
  185. # Training computation: logits + cross-entropy loss.
  186. logits = model(train_data_node, True)
  187. loss = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits, labels=train_labels_node))
  188.  
  189. # L2 regularization for the fully connected parameters.
  190. regularizers = (tf.nn.l2_loss(fc1_weights) + tf.nn.l2_loss(fc1_biases) +
  191. tf.nn.l2_loss(fc2_weights) + tf.nn.l2_loss(fc2_biases))
  192. # Add the regularization term to the loss.
  193. loss += 5e-4 * regularizers
  194.  
  195. # Optimizer: set up a variable that's incremented once per batch and
  196. # controls the learning rate decay.
  197. batch = tf.Variable(0, dtype=data_type())
  198. # Decay once per epoch, using an exponential schedule starting at 0.01.
  199. learning_rate = tf.train.exponential_decay(
  200. 0.01, # Base learning rate.
  201. batch * BATCH_SIZE, # Current index into the dataset.
  202. train_size, # Decay step.
  203. 0.95, # Decay rate.
  204. staircase=True)
  205. # Use simple momentum for the optimization.
  206. optimizer = tf.train.MomentumOptimizer(learning_rate,
  207. 0.9).minimize(loss,
  208. global_step=batch)
  209.  
  210. # Predictions for the current training minibatch.
  211. train_prediction = tf.nn.softmax(logits)
  212.  
  213. # Predictions for the test and validation, which we'll compute less often.
  214. eval_prediction = tf.nn.softmax(model(eval_data))
  215.  
  216. # Small utility function to evaluate a dataset by feeding batches of data to
  217. # {eval_data} and pulling the results from {eval_predictions}.
  218. # Saves memory and enables this to run on smaller GPUs.
  219. def eval_in_batches(data, sess):
  220. """Get all predictions for a dataset by running it in small batches."""
  221. size = data.shape[0]
  222. if size < EVAL_BATCH_SIZE:
  223. raise ValueError("batch size for evals larger than dataset: %d" % size)
  224. predictions = numpy.ndarray(shape=(size, NUM_LABELS), dtype=numpy.float32)
  225. for begin in range(0, size, EVAL_BATCH_SIZE):
  226. end = begin + EVAL_BATCH_SIZE
  227. if end <= size:
  228. predictions[begin:end, :] = sess.run(
  229. eval_prediction,
  230. feed_dict={eval_data: data[begin:end, ...]})
  231. else:
  232. batch_predictions = sess.run(
  233. eval_prediction,
  234. feed_dict={eval_data: data[-EVAL_BATCH_SIZE:, ...]})
  235. predictions[begin:, :] = batch_predictions[begin - size:, :]
  236. return predictions
  237.  
  238. # Create a local session to run the training.
  239. start_time = time.time()
  240. with tf.Session() as sess:
  241. # Run all the initializers to prepare the trainable parameters.
  242. tf.global_variables_initializer().run()
  243. print('Initialized!')
  244. # Loop through training steps.
  245. for step in range(int(num_epochs * train_size) // BATCH_SIZE):
  246. # Compute the offset of the current minibatch in the data.
  247. # Note that we could use better randomization across epochs.
  248. offset = (step * BATCH_SIZE) % (train_size - BATCH_SIZE)
  249. batch_data = train_data[offset:(offset + BATCH_SIZE), ...]
  250. batch_labels = train_labels[offset:(offset + BATCH_SIZE)]
  251. # This dictionary maps the batch data (as a numpy array) to the
  252. # node in the graph it should be fed to.
  253. feed_dict = {train_data_node: batch_data, train_labels_node: batch_labels}
  254. # Run the optimizer to update weights.
  255. sess.run(optimizer, feed_dict=feed_dict)
  256. # print some extra information once reach the evaluation frequency
  257. if step % EVAL_FREQUENCY == 0:
  258. # fetch some extra nodes' data
  259. l, lr, predictions = sess.run([loss, learning_rate, train_prediction], feed_dict=feed_dict)
  260. elapsed_time = time.time() - start_time
  261. start_time = time.time()
  262. print('Step %d (epoch %.2f), %.1f ms' %
  263. (step, float(step) * BATCH_SIZE / train_size,
  264. 1000 * elapsed_time / EVAL_FREQUENCY))
  265. print('Minibatch loss: %.3f, learning rate: %.6f' % (l, lr))
  266. print('Minibatch error: %.1f%%' % error_rate(predictions, batch_labels))
  267. print('Validation error: %.1f%%' % error_rate(eval_in_batches(validation_data, sess), validation_labels))
  268. sys.stdout.flush()
  269. # Finally print the result!
  270. test_error = error_rate(eval_in_batches(test_data, sess), test_labels)
  271. print('Test error: %.1f%%' % test_error)
  272. if FLAGS.self_test:
  273. print('test_error', test_error)
  274. assert test_error == 0.0, 'expected 0.0 test_error, got %.2f' % (test_error,)
  275.  
  276. if __name__ == '__main__':
  277. parser = argparse.ArgumentParser()
  278. parser.add_argument(
  279. '--use_fp16',
  280. default=False,
  281. help='Use half floats instead of full floats if True.',
  282. action='store_true')
  283. parser.add_argument(
  284. '--self_test',
  285. default=False,
  286. action='store_true',
  287. help='True if running a self test.')
  288.  
  289. FLAGS, unparsed = parser.parse_known_args()
  290. tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)

网址里面还有很多其它的示例,这些示例代码是最全的,比google网站上的还全,也比 github 上最新的 tensorflow 的库的例子要全要好 。

tensorflow 的 tutorial 的卷积神经网络的例子 convolutional.py的更多相关文章

  1. 使用TensorFlow v2.0构建卷积神经网络

    使用TensorFlow v2.0构建卷积神经网络. 这个例子使用低级方法来更好地理解构建卷积神经网络和训练过程背后的所有机制. CNN 概述 MNIST 数据集概述 此示例使用手写数字的MNIST数 ...

  2. 【深度学习与TensorFlow 2.0】卷积神经网络(CNN)

    注:在很长一段时间,MNIST数据集都是机器学习界很多分类算法的benchmark.初学深度学习,在这个数据集上训练一个有效的卷积神经网络就相当于学习编程的时候打印出一行“Hello World!”. ...

  3. TensorFlow 深度学习笔记 卷积神经网络

    Convolutional Networks 转载请注明作者:梦里风林 Github工程地址:https://github.com/ahangchen/GDLnotes 欢迎star,有问题可以到Is ...

  4. TensorFlow 实战之实现卷积神经网络

    本文根据最近学习TensorFlow书籍网络文章的情况,特将一些学习心得做了总结,详情如下.如有不当之处,请各位大拿多多指点,在此谢过. 一.相关性概念 1.卷积神经网络(ConvolutionNeu ...

  5. 机器学习与Tensorflow(4)——卷积神经网络与tensorflow实现

    1.标准卷积神经网络 标准的卷积神经网络由输入层.卷积层(convolutional layer).下采样层(downsampling layer).全连接层(fully—connected laye ...

  6. tensorflow学习笔记七----------卷积神经网络

    卷积神经网络比神经网络稍微复杂一些,因为其多了一个卷积层(convolutional layer)和池化层(pooling layer). 使用mnist数据集,n个数据,每个数据的像素为28*28* ...

  7. tensorflow学习之路-----卷积神经网络个人总结

    卷积神经网络大总结(个人理解) 神经网络 1.概念:从功能他们模仿真实数据 2.结构:输入层.隐藏层.输出层.其中隐藏层要有的参数:权重.偏置.激励函数.过拟合 3.功能:能通过模仿,从而学到事件 其 ...

  8. tensorflow文本分类实战——卷积神经网络CNN

    首先说明使用的工具和环境:python3.6.8   tensorflow1.14.0   centos7.0(最好用Ubuntu) 关于环境的搭建只做简单说明,我这边是使用pip搭建了python的 ...

  9. Tensorflow学习教程------利用卷积神经网络对mnist数据集进行分类_利用训练好的模型进行分类

    #coding:utf-8 import tensorflow as tf from PIL import Image,ImageFilter from tensorflow.examples.tut ...

随机推荐

  1. PHP从千千静听服务器获取lrc歌词

    <?php //转载请注明出处 uenucom function SingleDecToHex($dec)  {  $tmp="";  $dec=$dec%16;  if($ ...

  2. VM下redhat9.0不能上网

    近期本人在学习linux时,安装Red Hat Linux9后,可是上不了网,弄得查资料还得切换到虚拟机上去,特耗时间.还好没有疯掉! 首先,测试下你的linux看是否是这类问题,输入ping www ...

  3. C#中的事件介绍

    什么是事件?事件有哪些?怎么用事件? 一.什么是事件? 事件(Event) 基本上说是一个用户操作,如按键.点击.鼠标移动.输入值改变等等,或者是一些出现,如系统生成的通知.应用程序需要在事件发生时响 ...

  4. a5调试

    1 generating rsa key...[    4.452000] mmc0: error -110 whilst initialising SD card[    5.602000] mmc ...

  5. 开发高性能的MongoDB应用—浅谈MongoDB性能优化

    关联文章索引: 大数据时代的数据存储,非关系型数据库MongoDB 性能与用户量 “如何能让软件拥有更高的性能?”,我想这是一个大部分开发者都思考过的问题.性能往往决定了一个软件的质量,如果你开发的是 ...

  6. easy UI树形复选框

    首先,展示一下结果 这个是使用easyui的combotree控件来实现的,具体的代码如下: 1,声明一个复选框 <select id="rolePer" name=&quo ...

  7. vb 定时执行php程序

    托盘模块 Option Explicit Public Const NIF_ICON = &H2 Public Const NIF_MESSAGE = &H1 Public Const ...

  8. 第一百四十六节,JavaScript,百度分享保持居中--下拉菜单

    JavaScript,百度分享保持居中--下拉菜单 百度分享保持居中 效果图 html代码 <div id="share"> <h2>分享到</h2& ...

  9. 【python】获取网页中中文内容并分词

    # -*- coding: utf-8 -*- import urllib2 import re import time import jieba url="http://www.baidu ...

  10. .NET中的枚举用法浅析

    本文简单分析了.NET中的枚举用法.分享给大家供大家参考.具体分析如下: 我理解的枚举就是编程中约定的一个“可选值”:例如QQ的在线状态,分别有    在线,Q我吧,隐身,忙碌等等...我觉得这就是一 ...