1. 程式人生 > >ubuntu-kylin 16.04 LTS +VM12pro+py2.7+tensorflow0.8.0+mnist

ubuntu-kylin 16.04 LTS +VM12pro+py2.7+tensorflow0.8.0+mnist

引言

經過兩天的不懈努力,外加翻看各種部落格,論壇,安裝,解除安裝,再安裝。。。終於把這一套深度學習的入門工具和資料環境安裝成功。下邊就把這個過程詳細記錄下來,希望入手學習深度學習的小白們能少些彎路。

環境安裝

上邊兩個安裝比較順利,主要把32位系統和64位系統不要搞錯。

在這裡用的是ubuntu自帶的Python2.7環境。所以接下來就安裝的是tensorflow -0.8.0

3)安裝tensorflow0.8.0

4) 安裝jupiter
開啟終端輸入
sudo pip install jupyter
可能會出現pip版本過低等可輸入:pip install –upgrade pip

mnist手寫字型資料匯入

可以自己先下載出來放到自己寫成程式的資料夾的目錄下“your程式/mnist”

File "g3doc/tutorials/mnist/input_data.py", line 60, in extract_images
    buf = bytestream.read(rows * cols * num_images)
  File "/usr/lib/python2.7/gzip.py", line 263, in read
    chunk = self.extrabuf\[offset: offset + size]
TypeError: only integer
scalar arrays can be converted to a scalar index

解決辦法:

曾經的嘗試

anaconda3 4.2 + tensorflow0.12.0 這個是gpu版本 但是我的電腦沒有GPU計算。。。然後
import tensorflow.examples.tutorials.mnist.input_data as input_data
mnist = input_data.read_data_sets(“MNIST_data/”, one_hot=True)
這兩句一直出錯。。。。

其實我想說這個方式安裝真的沒有省多少事。。。。

mnist手寫字型softmax實現

softmax迴歸詳解

程式碼實現

import tensorflow as tf
import input_data
mnist = input_data.read_data_sets("mnist", one_hot=True)
Extracting mnist/train-images-idx3-ubyte.gz
Extracting mnist/train-labels-idx1-ubyte.gz
Extracting mnist/t10k-images-idx3-ubyte.gz
Extracting mnist/t10k-labels-idx1-ubyte.gz
print(mnist.train.images.shape,mnist.train.labels.shape)#訓練模型
print(mnist.test.images.shape,mnist.test.images.shape)#在測試集熵評估模型
print(mnist.validation.images.shape,mnist.validation.images.shape)#調優模型
((55000, 784), (55000, 10))
((10000, 784), (10000, 784))
((5000, 784), (5000, 784))
#定義會話介面
sess = tf.InteractiveSession()

#儲存輸入資料的容器,一旦被使用,該資料就會被清除,
#None表示可以輸入任意個樣本點數,784為特徵個數
x = tf.placeholder(tf.float32,[None,784])

#Variable()是用來儲存模型引數,是永久儲存,在模型訓練過程中,引數可以被更新
#tf.zeros()表示對引數w,b進行0初始化。10表示類別個數。784表示特徵個數。
w = tf.Variable(tf.zeros([784,10]))
b = tf.Variable(tf.zeros([10]))

#定義計算公式,y=softmax(wx+b)
#tf.nn包含了大量的聖經網路元件,tf.matmul()矩陣乘法函式
y = tf.nn.softmax(tf.matmul(x,w) + b)

#定義損失函式,softmax損失函式是交叉熵,y_true為例項的真實類別
y_true = tf.placeholder(tf.float32,[None,10])
#reduction_indices = [1]表示列方向。
cross_entropy = tf.reduce_mean(- tf.reduce_sum(y_true * tf.log(y),reduction_indices = [1]))

#指定訓練過程中的優化器,0.5表示學習率
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)

#定義完成,執行計算圖
init = tf.initialize_all_variables()
#sess = tf.Session()
sess.run(init)
#tf.global_variables_initializer().run()

#使用隨機梯度下降演算法,每次選擇100個樣本點,迭代的求解模型引數
for i in range(1000):
    batch_xs,batch_ys = mnist.train.next_batch(100)
    train_step.run({x: batch_xs,y_true: batch_ys})
#計算分類精度,tf.cast將輸出的bool轉換成float32
correct_prediction = tf.equal(tf.argmax(y,1),tf.argmax(y_true,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))
print(accuracy.eval({x:mnist.test.images,y_true:mnist.test.labels}))

   #手寫字型的分類精度
    0.9197