1. 程式人生 > >tensorflow學習筆記之使用tensorflow進行MNIST分類(2)

tensorflow學習筆記之使用tensorflow進行MNIST分類(2)

接著上一篇:http://blog.csdn.net/IEEE_FELLOW/article/details/53012351

本文參考Yann LeCun的LeNet5經典架構,稍加ps得到下面適用於本手寫識別的cnn結構,構造一個兩層卷積神經網路,神經網路的結構如下圖所示:

輸入-卷積-pooling-卷積-pooling-全連線層-Dropout-Softmax輸出


第一層卷積利用5*5的patch,32個卷積核,可以計算出32個特徵。然後進行maxpooling。第二層卷積利用5*5的patch,64個卷積核,可以計算出64個特徵。然後進行max pooling。卷積核的個數是我們自己設定,可以增加捲積核數目提高分類精度,但是那樣會增加更大引數,提高計算成本。

這樣輸入是解析度為28*28的圖片。利用5*5的patch進行卷積。我們的卷積使用1步長(stride size),0填充模組(zero padded),這樣得到的輸出和輸入是同一個大小。經過第一層卷積之後,卷積特徵大小為28*28。然後通過ReLU函式啟用。我們的pooling用簡單傳統的2x2大小的模板做max pooling,這樣pooling後得到14*14大小的特徵。經過第二層卷積後,卷積特徵大小為14*14,然後通過ReLU函式啟用,再經過pooling後得到特徵大小為7*7。

現在,圖片尺寸減小到7x7,我們加入一個有1024個神經元的全連線層,用於處理整個圖片。我們把池化層輸出的張量展開成一些向量,乘上權重矩陣,加上偏置,然後對其使用ReLU。

為了避免過擬合,在全連線層輸出接上dropout層。Dropout層在訓練時遮蔽一半的神經元。


DropOut Network

最後輸出端為一個Softmax層用於分類。

以上是本教程的模型整體結構,下面將依次講解該模型的tensorflow實現流程。

1         程式說明

1.1    載入MNIST資料集

用下面的程式碼將下載後的資料匯入到你的專案裡面,也可以直接複製貼上到你的程式碼檔案裡面:

1.	from tensorflow.examples.tutorials.mnist import input_data  
2.	mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) 

這裡,mnist是一個輕量級的類。它以Numpy陣列的形式儲存著訓練、校驗和測試資料集。

1.2   執行TensorFlow的InteractiveSession

Tensorflow依賴於一個高效的C++後端來進行計算。與後端的這個連線叫做session。一般而言,使用TensorFlow 程式的流程是先建立一個圖,然後在session中啟動它。

這裡,我們使用更加方便的InteractiveSession類。通過它,你可以更加靈活地構建你的程式碼。它能讓你在執行圖的時候,插入一些計算圖,這些計算圖是由某些操作(operations)構成的。這對於工作在互動式環境中的人們來說非常便利,比如使用IPython。如果你沒有使用InteractiveSession,那麼你需要在啟動session之前構建整個計算圖,然後啟動該計算圖。

1.	import tensorflow as tf  
2.	sess = tf.InteractiveSession()  

1.3   構建Softmax 迴歸模型

佔位符

我們通過為輸入影象和目標輸出類別建立節點,來開始構建計算圖。

1.	x = tf.placeholder("float", shape=[None, 784])  
2.	y_ = tf.placeholder("float", shape=[None, 10])  

這裡的x和y並不是特定的值,相反,他們都只是一個佔位符,可以在TensorFlow執行某一計算時根據該佔位符輸入具體的值。

輸入圖片x是一個2維的浮點數張量。這裡,分配給它的shape為[None, 784],其中784是一張展平的MNIST圖片的維度。None表示其值大小不定,在這裡作為第一個維度值,用以指代batch的大小,意即x的數量不定。輸出類別值y_也是一個2維張量,其中每一行為一個10維的one-hot向量,用於代表對應某一MNIST圖片的類別。

雖然placeholder的shape引數是可選的,但有了它,TensorFlow能夠自動捕捉因資料維度不一致導致的錯誤。

1.4    權重初始化

變數

我們現在為模型定義權重W和偏置b。可以將它們當作額外的輸入量,但是TensorFlow有一個更好的處理方式:變數。一個變數代表著TensorFlow計算圖中的一個值,能夠在計算過程中使用,甚至進行修改。在機器學習的應用過程中,模型引數一般用Variable來表示。

我們在呼叫tf.Variable的時候傳入初始值。

為了建立這個模型,我們需要建立大量的權重和偏置項。這個模型中的權重在初始化時應該加入少量的噪聲來打破對稱性以及避免0梯度。由於我們使用的是ReLU神經元,因此比較好的做法是用一個較小的正數來初始化偏置項,以避免神經元節點輸出恆為0的問題(deadneurons)。為了不在建立模型的時候反覆做初始化操作,我們定義兩個函式用於初始化。

1.	def weight_variable(shape):  
2.	  initial = tf.truncated_normal(shape, stddev=0.1)  
3.	  return tf.Variable(initial)  
4.	  
5.	def bias_variable(shape):  
6.	  initial = tf.constant(0.1, shape=shape)  
7.	  return tf.Variable(initial)  

變數需要通過seesion初始化後,才能在session中使用。這一初始化步驟為,為初始值指定具體值(本例當中是全為零),並將其分配給每個變數,可以一次性為所有變數完成此操作。

1.	sess.run(tf.initialize_all_variables()) 

1.5    卷積和Pooling

TensorFlow在卷積和Pooling上有很強的靈活性。我們怎麼處理邊界?步長應該設多大?在這個例項裡,我們的卷積使用1步長(stride size),0填充模組(zero padded),保證輸出和輸入是同一個大小。我們的pooling用簡單傳統的2x2大小的模板做maxpooling。為了程式碼更簡潔,我們把這部分抽象成一個函式。

1.	def conv2d(x, W):  
2.	  return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')  
3.	  
4.	def max_pool_2x2(x):  
5.	  return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],  
6.	                        strides=[1, 2, 2, 1], padding='SAME')  

1.6    第一層卷積

現在我們可以開始實現第一層了。它由一個卷積接一個max pooling完成。卷積在每個5x5的patch中算出32個特徵。卷積的權重張量形狀是[5, 5, 1, 32],前兩個維度是patch的大小,接著是輸入的通道數目,最後是輸出的通道數目。 而對於每一個輸出通道都有一個對應的偏置量。

1.	W_conv1 = weight_variable([5, 5, 1, 32])  
2.	b_conv1 = bias_variable([32]) 

為了用這一層,我們把x變成一個4d向量,其第2、第3維對應圖片的寬、高,最後一維代表圖片的顏色通道數(因為是灰度圖所以這裡的通道數為1,如果是rgb彩色圖,則為3)。

1.	x_image = tf.reshape(x, [-1,28,28,1])  

我們把x_image和權值向量進行卷積,加上偏置項,然後應用ReLU啟用函式,最後進行maxpooling。

1.	h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)  
2.	h_pool1 = max_pool_2x2(h_conv1)  

1.7    第二層卷積

為了構建一個更深的網路,我們會把幾個類似的層堆疊起來。第二層中,每個5x5的patch會得到64個特徵。

1.	W_conv2 = weight_variable([5, 5, 32, 64])  
2.	b_conv2 = bias_variable([64])  
3.	  
4.	h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)  
5.	h_pool2 = max_pool_2x2(h_conv2)  

1.8   全連線層(fully-connectedlayer)

現在,圖片尺寸減小到7x7,我們加入一個有1024個神經元的全連線層,用於處理整個圖片。我們把池化層輸出的張量reshape成一些向量,乘上權重矩陣,加上偏置,然後對其使用ReLU。

1.	W_fc1 = weight_variable([7 * 7 * 64, 1024])  
2.	b_fc1 = bias_variable([1024])  
3.	  
4.	h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64])  
5.	h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)  

1.9    Dropout

為了減少過擬合,我們在輸出層之前加入dropout。我們用一個placeholder來代表一個神經元的輸出在dropout中保持不變的概率。這樣我們可以在訓練過程中啟用dropout,在測試過程中關閉dropout。 TensorFlow的tf.nn.dropout操作除了可以遮蔽神經元的輸出外,還會自動處理神經元輸出值的scale。所以用dropout的時候可以不用考慮scale。

1.	keep_prob = tf.placeholder("float")  
2.	h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob) 

對於本教程所搭建的小型卷積網路,實際上有沒有dropout層效能幾乎相同。dropout通常能夠很好的減少過擬合,特別適用於訓練非常大型的神經網路。

1.10    輸出層

最後,我們新增一個softmax層,就像前面的單層softmax regression一樣。

1.	W_fc2 = weight_variable([1024, 10])  
2.	b_fc2 = bias_variable([10])  
3.	  
4.	y_conv=tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)

1.11    訓練和評估模型

為了進行訓練和評估,我們用更加複雜的ADAM進行優化,在feed_dict中加入額外的引數keep_prob來控制dropout比例。然後每100次迭代輸出一次日誌。

1.	cross_entropy = -tf.reduce_sum(y_*tf.log(y_conv))  
2.	train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)  
3.	correct_prediction = tf.equal(tf.argmax(y_conv,1), tf.argmax(y_,1))  
4.	accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))  
5.	sess.run(tf.initialize_all_variables())  
6.	for i in range(20000):  
7.	  batch = mnist.train.next_batch(50)  
8.	  if i%100 == 0:  
9.	    train_accuracy = accuracy.eval(feed_dict={  
10.	        x:batch[0], y_: batch[1], keep_prob: 1.0})  
11.	    print "step %d, training accuracy %g"%(i, train_accuracy)  
12.	  train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5})  
13.	  
14.	print "test accuracy %g"%accuracy.eval(feed_dict={  
15.	    x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0}) 
注意15行因為測試樣本太大,可能會出現記憶體溢位:


那麼將測試集進行劃分成batch,然後進行測試:

1.	for i in xrange(10):  
2.	    testSet = mnist.test.next_batch(1000)  
3.	    print("test accuracy %g"%accuracy.eval(feed_dict={ x: testSet[0], y_: testSet[1], keep_prob: 1.0}))  
4.	  
5.	#print "test accuracy %g" % accuracy.eval(feed_dict={x:mnist.test.images, y_:mnist.test.labels, keep_prob:1.0})  

上述流程,在最終測試集上的準確率大概是99.22%。




  參考資料:

附上完整程式碼:

MLP_CNN.py

1.	# load MNIST data  
2.	import input_data  
3.	mnist = input_data.read_data_sets("MNIST_data", one_hot=True)  
4.	  
5.	# start tensorflow interactiveSession  
6.	import tensorflow as tf  
7.	sess = tf.InteractiveSession()  
8.	  
9.	# weight initialization  
10.	def weight_variable(shape):  
11.	    initial = tf.truncated_normal(shape, stddev=0.1)  
12.	    return tf.Variable(initial)  
13.	  
14.	def bias_variable(shape):  
15.	    initial = tf.constant(0.1, shape = shape)  
16.	    return tf.Variable(initial)  
17.	  
18.	# convolution  
19.	def conv2d(x, W):  
20.	    return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')  
21.	# pooling  
22.	def max_pool_2x2(x):  
23.	    return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')  
24.	  
25.	# Create the model  
26.	# placeholder  
27.	x = tf.placeholder("float", [None, 784])  
28.	y_ = tf.placeholder("float", [None, 10])  
29.	  
30.	# first convolutinal layer  
31.	w_conv1 = weight_variable([5, 5, 1, 32])  
32.	b_conv1 = bias_variable([32])  
33.	  
34.	x_image = tf.reshape(x, [-1, 28, 28, 1])  
35.	  
36.	h_conv1 = tf.nn.relu(conv2d(x_image, w_conv1) + b_conv1)  
37.	h_pool1 = max_pool_2x2(h_conv1)  
38.	  
39.	# second convolutional layer  
40.	w_conv2 = weight_variable([5, 5, 32, 64])  
41.	b_conv2 = bias_variable([64])  
42.	  
43.	h_conv2 = tf.nn.relu(conv2d(h_pool1, w_conv2) + b_conv2)  
44.	h_pool2 = max_pool_2x2(h_conv2)  
45.	  
46.	# densely connected layer  
47.	w_fc1 = weight_variable([7*7*64, 1024])  
48.	b_fc1 = bias_variable([1024])  
49.	  
50.	h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64])  
51.	h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, w_fc1) + b_fc1)  
52.	  
53.	# dropout  
54.	keep_prob = tf.placeholder("float")  
55.	h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)  
56.	  
57.	# readout layer  
58.	w_fc2 = weight_variable([1024, 10])  
59.	b_fc2 = bias_variable([10])  
60.	  
61.	y_conv = tf.nn.softmax(tf.matmul(h_fc1_drop, w_fc2) + b_fc2)  
62.	  
63.	# train and evaluate the model  
64.	cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(y_conv, y_))  
65.	train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)  
66.	correct_prediction = tf.equal(tf.argmax(y_conv,1), tf.argmax(y_,1))  
67.	accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))  
68.	sess.run(tf.initialize_all_variables())  
69.	for i in range(20000):  
70.	  batch = mnist.train.next_batch(50)  
71.	  if i%100 == 0:  
72.	    train_accuracy = accuracy.eval(feed_dict={  
73.	        x:batch[0], y_: batch[1], keep_prob: 1.0})  
74.	    print("step %d, training accuracy %g"%(i, train_accuracy))  
75.	  train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5})  
76.	for i in xrange(10):  
77.	    testSet = mnist.test.next_batch(1000)  
78.	    print("test accuracy %g"%accuracy.eval(feed_dict={ x: testSet[0], y_: testSet[1], keep_prob: 1.0}))  
79.	  
80.	#print "test accuracy %g" % accuracy.eval(feed_dict={x:mnist.test.images, y_:mnist.test.labels, keep_prob:1.0}) 

input_data.py

# Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Functions for downloading and reading MNIST data."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import gzip
import os
import tensorflow.python.platform
import numpy
from six.moves import urllib
from six.moves import xrange  # pylint: disable=redefined-builtin
import tensorflow as tf
SOURCE_URL = 'http://yann.lecun.com/exdb/mnist/'
def maybe_download(filename, work_directory):
  """Download the data from Yann's website, unless it's already here."""
  if not os.path.exists(work_directory):
    os.mkdir(work_directory)
  filepath = os.path.join(work_directory, filename)
  if not os.path.exists(filepath):
    filepath, _ = urllib.request.urlretrieve(SOURCE_URL + filename, filepath)
    statinfo = os.stat(filepath)
    print('Successfully downloaded', filename, statinfo.st_size, 'bytes.')
  return filepath
def _read32(bytestream):
  dt = numpy.dtype(numpy.uint32).newbyteorder('>')
  return numpy.frombuffer(bytestream.read(4), dtype=dt)[0]
def extract_images(filename):
  """Extract the images into a 4D uint8 numpy array [index, y, x, depth]."""
  print('Extracting', filename)
  with gzip.open(filename) as bytestream:
    magic = _read32(bytestream)
    if magic != 2051:
      raise ValueError(
          'Invalid magic number %d in MNIST image file: %s' %
          (magic, filename))
    num_images = _read32(bytestream)
    rows = _read32(bytestream)
    cols = _read32(bytestream)
    buf = bytestream.read(rows * cols * num_images)
    data = numpy.frombuffer(buf, dtype=numpy.uint8)
    data = data.reshape(num_images, rows, cols, 1)
    return data
def dense_to_one_hot(labels_dense, num_classes=10):
  """Convert class labels from scalars to one-hot vectors."""
  num_labels = labels_dense.shape[0]
  index_offset = numpy.arange(num_labels) * num_classes
  labels_one_hot = numpy.zeros((num_labels, num_classes))
  labels_one_hot.flat[index_offset + labels_dense.ravel()] = 1
  return labels_one_hot
def extract_labels(filename, one_hot=False):
  """Extract the labels into a 1D uint8 numpy array [index]."""
  print('Extracting', filename)
  with gzip.open(filename) as bytestream:
    magic = _read32(bytestream)
    if magic != 2049:
      raise ValueError(
          'Invalid magic number %d in MNIST label file: %s' %
          (magic, filename))
    num_items = _read32(bytestream)
    buf = bytestream.read(num_items)
    labels = numpy.frombuffer(buf, dtype=numpy.uint8)
    if one_hot:
      return dense_to_one_hot(labels)
    return labels
class DataSet(object):
  def __init__(self, images, labels, fake_data=False, one_hot=False,
               dtype=tf.float32):
    """Construct a DataSet.
    one_hot arg is used only if fake_data is true.  `dtype` can be either
    `uint8` to leave the input as `[0, 255]`, or `float32` to rescale into
    `[0, 1]`.
    """
    dtype = tf.as_dtype(dtype).base_dtype
    if dtype not in (tf.uint8, tf.float32):
      raise TypeError('Invalid image dtype %r, expected uint8 or float32' %
                      dtype)
    if fake_data:
      self._num_examples = 10000
      self.one_hot = one_hot
    else:
      assert images.shape[0] == labels.shape[0], (
          'images.shape: %s labels.shape: %s' % (images.shape,
                                                 labels.shape))
      self._num_examples = images.shape[0]
      # Convert shape from [num examples, rows, columns, depth]
      # to [num examples, rows*columns] (assuming depth == 1)
      assert images.shape[3] == 1
      images = images.reshape(images.shape[0],
                              images.shape[1] * images.shape[2])
      if dtype == tf.float32:
        # Convert from [0, 255] -> [0.0, 1.0].
        images = images.astype(numpy.float32)
        images = numpy.multiply(images, 1.0 / 255.0)
    self._images = images
    self._labels = labels
    self._epochs_completed = 0
    self._index_in_epoch = 0
  @property
  def images(self):
    return self._images
  @property
  def labels(self):
    return self._labels
  @property
  def num_examples(self):
    return self._num_examples
  @property
  def epochs_completed(self):
    return self._epochs_completed
  def next_batch(self, batch_size, fake_data=False):
    """Return the next `batch_size` examples from this data set."""
    if fake_data:
      fake_image = [1] * 784
      if self.one_hot:
        fake_label = [1] + [0] * 9
      else:
        fake_label = 0
      return [fake_image for _ in xrange(batch_size)], [
          fake_label for _ in xrange(batch_size)]
    start = self._index_in_epoch
    self._index_in_epoch += batch_size
    if self._index_in_epoch > self._num_examples:
      # Finished epoch
      self._epochs_completed += 1
      # Shuffle the data
      perm = numpy.arange(self._num_examples)
      numpy.random.shuffle(perm)
      self._images = self._images[perm]
      self._labels = self._labels[perm]
      # Start next epoch
      start = 0
      self._index_in_epoch = batch_size
      assert batch_size <= self._num_examples
    end = self._index_in_epoch
    return self._images[start:end], self._labels[start:end]
def read_data_sets(train_dir, fake_data=False, one_hot=False, dtype=tf.float32):
  class DataSets(object):
    pass
  data_sets = DataSets()
  if fake_data:
    def fake():
      return DataSet([], [], fake_data=True, one_hot=one_hot, dtype=dtype)
    data_sets.train = fake()
    data_sets.validation = fake()
    data_sets.test = fake()
    return data_sets
  TRAIN_IMAGES = 'train-images-idx3-ubyte.gz'
  TRAIN_LABELS = 'train-labels-idx1-ubyte.gz'
  TEST_IMAGES = 't10k-images-idx3-ubyte.gz'
  TEST_LABELS = 't10k-labels-idx1-ubyte.gz'
  VALIDATION_SIZE = 5000
  local_file = maybe_download(TRAIN_IMAGES, train_dir)
  train_images = extract_images(local_file)
  local_file = maybe_download(TRAIN_LABELS, train_dir)
  train_labels = extract_labels(local_file, one_hot=one_hot)
  local_file = maybe_download(TEST_IMAGES, train_dir)
  test_images = extract_images(local_file)
  local_file = maybe_download(TEST_LABELS, train_dir)
  test_labels = extract_labels(local_file, one_hot=one_hot)
  validation_images = train_images[:VALIDATION_SIZE]
  validation_labels = train_labels[:VALIDATION_SIZE]
  train_images = train_images[VALIDATION_SIZE:]
  train_labels = train_labels[VALIDATION_SIZE:]
  data_sets.train = DataSet(train_images, train_labels, dtype=dtype)
  data_sets.validation = DataSet(validation_images, validation_labels,
                                 dtype=dtype)
  data_sets.test = DataSet(test_images, test_labels, dtype=dtype)
  return data_sets









相關推薦

tensorflow學習筆記使用tensorflow進行MNIST分類2

接著上一篇:http://blog.csdn.net/IEEE_FELLOW/article/details/53012351 本文參考Yann LeCun的LeNet5經典架構,稍加ps得到下面適用於本手寫識別的cnn結構,構造一個兩層卷積神經網路,神經網路的結構如下圖

React學習筆記react進階篇2

-s state ops category strong tro 服務 ive 周期 2.組件與服務器通信   組件的生命周期分為三個階段:掛載階段->更新階段->卸載階段,本文主要集中講述掛載和更新階段組件如何和服務器進行通信。 1.組件掛載階段通信  

tensorflow學習筆記使用tensorflow進行MNIST分類3

在載入MNIST資料集時候用到了Input_data.py。這段程式碼其實非常重要,現在和大家一起分享一下我的學習理解 #coding=utf-8 #input_data.py的詳解 #學習讀取資料檔案的方法,以便讀取自己需要的資料庫檔案(二進位制檔案) """Funct

React學習筆記react進階篇1

ava 不能 success 字符 style 使用 -s 布爾 一次 1.組件的state(狀態) 1.選擇合適的state   state所代表的一個組件UI呈現的完整狀態集又可以分成兩類數據:用作渲染組件時使用到的數據的來源以及用作組件UI展現形式的判斷依據。 示

mybatis學習筆記——連線SQL server資料庫IDEA

我們新建一個普通的專案,File --> New --> Project -->Java --> Java EE。然後新建專案即可。 專案完成後我們新建一個conf資料夾,用來存放配置資訊,新建一個lib資料夾,用來存放jar包。 我們將mybatis的jar包,連線

Java學習筆記抽象類基本概念1

1、基本概念 抽象類:包含一個抽象方法的類 抽象方法:用abstract關鍵字宣告,且只有方法名沒有方法體的方法。 1.1 抽象類的定義和使用規則 包含了一個抽象方法的類必須是抽象類 抽象類和抽象方法都要用abstract關鍵字宣告 抽象方法只需要宣告不用實現

深度學習筆記【隨機梯度下降SGD

筆記 優化問題 toc 最終 來看 應用 優化算法 樣本 找到 隨機梯度下降 幾乎所有的深度學習算法都用到了一個非常重要的算法:隨機梯度下降(stochastic gradient descent,SGD) 隨機梯度下降是梯度下降算法的一個擴展 機器學習中一個反復出現的

《C語言程式設計:現代方法2K.N.King 著學習筆記九:格式化輸入/輸出2

3.2 scanf 函式 就如同 printf 函式用特定的格式顯示輸出一樣,scanf 函式也根據特定的格式讀取輸入。像 printf 函式的格式串一樣,scanf 函式的格式串也可以包含普通字元

GO學習筆記——GO語言整合工具GoLand2

既然開始下定決心要學GO語言了,先從安裝做起吧。 安裝的過程很簡單,百度上一搜大把的教程,我這裡就不做搬運工了,可以自己去百度上搜怎麼安裝。 不過這裡我要說明一下,百度上的教程裡的那個環境變數的設定,有一個GOPATH環境變數,這個環境變數其實我們初學者在學基礎語法的時候

Panda學習筆記4——多表功能開發2後端介面開發

進行功能性的開發,主要涉及到: 序號 型別 名稱 1 DTO CodeRulesTest1Header 2 DTO CodeRulesTest1Line 3 Mapper CodeRulesTest1HeaderMapper 4 Ma

數字語音訊號處理學習筆記——語音訊號的數字模型2

版權宣告:本文為博主原創文章,未經博主允許不得轉載。    https://blog.csdn.net/u013538664/article/details/25126095 2.3 語音的聽覺機理      &nb

caffe 學習系列生成txt 和lmdb2

    在上個筆記中,已經學會了如何使用Caffe利用作者給的指令碼訓練CIFAR-10資料集,得到訓練好的CNN模型。但是在上個筆記中,使用的都是作者提供好的指令碼檔案,完全就是按照教程跑了一下提供的demo。對於自己手裡的一些圖片資料集,如何轉換圖片格式、如何計算圖片資料的均值、如何編寫protot

cocos2dx學習原始碼介面iOS事件分發2

今天看看事件是如何分發的。程式碼版本:cocos2dx-3.9 上次說到GLView接手touch事件:handleTouchesBegin。 原始碼: void GLView::handleTou

【MATLAB 學習筆記】 SimMechanics 流程攻略 2

本章主要內容: 1. 製作斜坡上以及懸掛的彈簧阻尼系統; 2. 用m檔案修改系統中的引數,達到可程式設計控制的目的。 ==================================================================== 首先研究一下各個

Tensorflow 學習筆記使用LSTM實現MNIST資料集

LSTM實現MNIST手寫集識別 這幾天剛好看了RNN之後瞭解了LSTM(原理可以去參考這個)。雖然LSTM主要用於處理自然語言、語音、機器人翻譯等領域,但圖片也可以看做一個有序列的資料。所以用LSTM

Tensorflow學習筆記池化

Tensorflow學習筆記之池化 在深度學習網路中,經常會遇到池化操作,並且往往是在卷積之後,池化操作的意義是降低卷積層輸出特徵向量的維度,並且通過不同的池化方法使不同維度的卷積層輸出結果得到相同維度的特徵向量結果。 1、一般池化 池化過程作用於不重疊區域 我們定義池化視窗的大小為s

Tensorflow學習筆記tf.nn.relu

Tensorflow學習筆記之tf.nn.relu 關於Tensorflow的學習筆記大部分為其他部落格或者書籍轉載,只為督促自己學習。 線性整流函式(Rectified Linear Unit,ReLU),又稱修正線性單元。其定義如下圖,在橫座標的右側,ReLU函式為線性函式。在橫座標

Tensorflow學習筆記tf.layers.conv2d

Tensorflow學習筆記 關於Tensorflow的學習筆記大部分為其他部落格或者書籍轉載,只為督促自己學習。 conv2d(inputs, filters, kernel_size, strides=(1, 1), padding='valid', d

TensorFlow學習筆記--[tf.clip_by_global_norm,tf.clip_by_value,tf.clip_by_norm等的區別]

以下這些函式可以用於解決梯度消失或梯度爆炸問題上。 1. tf.clip_by_value tf.clip_by_value( t, clip_value_min, clip_value_max, name=None ) 輸入一個張量t,把t中的每一個元素的值都

tensorflow 學習:用CNN進行影象分類

# -*- coding: utf-8 -*- from skimage import io,transform import glob import os import tensorflow as tf import numpy as np import time path='e:/flower/'