2016-09-29 72 views
0

我試圖在tensorflow中實現softmax迴歸模型,以便與其他主流深度學習框架進行基準比較。由於tensorflow中的feed_dict issue,官方文檔代碼很慢。我試圖以tensorflow的形式服務數據,但我不知道最有效的方法。現在我只使用單個批次作爲常量並通過該批次進行培訓。對代碼進行minibatched解決方案的有效解決方案是什麼?這裏是我的代碼:張量流中快速的softmax迴歸實現

from tensorflow.examples.tutorials.mnist import input_data 

import tensorflow as tf 
import numpy as np 

mnist = input_data.read_data_sets(FLAGS.data_dir, one_hot=True) 
batch_xs, batch_ys = mnist.train.next_batch(100) 

x = tf.constant(batch_xs, name="x") 
W = tf.Variable(0.1*tf.random_normal([784, 10])) 
b = tf.Variable(tf.zeros([10])) 
logits = tf.matmul(x, W) + b 

batch_y = batch_ys.astype(np.float32) 
y_ = tf.constant(batch_y, name="y_") 

loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits, y_)) 
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(loss) 
.... 
# Minitbatch is never updated during that for loop 
for i in range(5500): 
    sess.run(train_step) 

回答

0

正如以下。

from tensorflow.examples.tutorials.mnist import input_data 

import tensorflow as tf 
import numpy as np 

batch_size = 32 #any size you want 

mnist = input_data.read_data_sets(FLAGS.data_dir, one_hot=True) 


x = tf.placeholder(tf.float32, shape = [None, 784]) 
y = tf.placeholder(tf.float32, shape = [None, 10]) 

W = tf.Variable(0.1*tf.random_normal([784, 10])) 
b = tf.Variable(tf.zeros([10])) 

logits = tf.matmul(x, W) + b 

loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits, y)) 
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(loss) 
.... 
# Minitbatch is never updated during that for loop 
for i in range(1000): 
    batch_xs, batch_ys = mnist.train.next_batch(batch_size) 
    l, _ = sess.run([loss, train_step], feed_dict = {x: batch_x, y: batch_ys}) 
    print l #loss for every minibatch 

形狀類似於[無,784]允許您輸入shape [?,784]的任何值。

我沒有測試過這個代碼,但我希望它能工作。