2016-04-21 91 views
1

我一直在各種框架中試驗簡單的基本(簡介教程級別)神經網絡,但是我對TensorFlow中看到的性能感到困惑。簡單網絡TensorFlow性能不佳嗎?

例如,從Michael Nielsen's tutorial(在具有30個隱藏節點的網絡中使用L2隨機梯度下降的MNIST數字識別)的簡單網絡執行得差很多(每個曆元大約8x,具有所有相同的參數) (使用one of the tutorial exercises建議的小批量矢量化)版本Nielsen's basic NumPy code

在單個CPU上運行的TensorFlow是否始終執行此操作?我應該調整以改善性能嗎?或者TensorFlow真的只會在複雜的網絡或學習體系中發光,因此對於這種簡單的玩具來說,它不會有好的表現嗎?


from __future__ import (absolute_import, print_function, division, unicode_literals) 

import tensorflow as tf 
from tensorflow.examples.tutorials.mnist import input_data 
import time 


def weight_variable(shape): 
    return tf.Variable(tf.truncated_normal(shape, stddev=0.1)) 


def bias_variable(shape): 
    return tf.Variable(tf.constant(0.1, shape=shape)) 


mnist = input_data.read_data_sets("./data/", one_hot=True) 

sess = tf.Session() 

# Inputs and outputs 
x = tf.placeholder(tf.float32, shape=[None, 784]) 
y_ = tf.placeholder(tf.float32, shape=[None, 10]) 

# Model parameters 
W1 = weight_variable([784, 30]) 
b1 = bias_variable([30]) 
o1 = tf.nn.sigmoid(tf.matmul(x, W1) + b1, name='o1') 
W2 = weight_variable([30, 10]) 
b2 = bias_variable([10]) 
y = tf.nn.softmax(tf.matmul(o1, W2) + b2, name='y') 

sess.run(tf.initialize_all_variables()) 

loss = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1])) 
loss += 0.1/1000 * (tf.nn.l2_loss(W1) + tf.nn.l2_loss(W2)) 

train_step = tf.train.GradientDescentOptimizer(0.15).minimize(loss) 

accuracy = tf.reduce_mean(tf.cast(tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1)), tf.float32)) 


for ep in range(30): 
    for mb in range(int(len(mnist.train.images)/40)): 
     batch_xs, batch_ys = mnist.train.next_batch(40) 
     sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys}) 
+0

'next_batch'需要多少時間?該功能比Michael Nielsen使用簡單Numpy切片的版本做得更多東西 –

+0

@YaroslavBulatov:是否有辦法禁用「更多東西」,以便它完全符合Michael Nielsen的版本,所以我有一個更直接的比較? – orome

+0

也許你可以將TensorFlow插入到Michael Nielsen的版本中? –

回答

1

是的,我希望在CPU運行的手工編碼的專用簡單網絡將跑得比tensorflow更快。原因通常與tensorflow使用的圖形評估系統相關。

使用張量流的好處是,當你有更復雜的算法,並且你希望能夠首先測試正確性,然後能夠輕鬆移植它以使用更多的機器和更多的處理單元。

例如,您可以嘗試的一種方法是在具有GPU的計算機上運行您的代碼,並且在不更改代碼中的任何內容的情況下,您的代碼速度會提高,可能會比鏈接的手形編碼示例更快。 您可以看到手寫代碼需要付出相當大的努力才能移植到GPU。

+0

大概是因爲我有一個更復雜的網絡(卷積,更多圖層,更多節點等等)或更多花哨的學習(例如退出),即使使用單個CPU,TensorFlow也會開始超越我能用基本NumPy,對嗎? – orome

+0

當然,再加上代碼正在被許多其他開發者使用,所以也更可靠。 – fabrizioM

+0

舉個例子,我昨天在Z840上試過numpy OpenBLAS,大矩陣乘法的時候是430 G ops /秒,同時TensorFlow給了我1.1 T ops /秒 –