2017-10-15 35 views
0

訓練,我讀了將被用於訓練我的分類數據集中,如下所示的圖像:如何養活分類器對Tensorflow

filename_strings = [] 
label_strings = [] 
for dirname, dirnames, filenames in os.walk('training'): 
    for filename in filenames: 
     filename_strings.append(dirname + '\\' + filename) 
     label_strings.append(dirname) 

filenames = tf.constant(filename_strings) 
labels = tf.constant(label_strings) 
dataset = tf.contrib.data.Dataset.from_tensor_slices((filenames, labels)) 
dataset_train = dataset.map(_parse_function) 

_parse_function:

# Reads an image from a file, decodes it into a dense tensor, and resizes it 
# to a fixed shape. 
def _parse_function(filename, label): 
    image_string = tf.read_file(filename) 
    image_decoded = tf.image.decode_png(image_string) 
    image_resized = tf.image.resize_images(image_decoded, [28, 28]) 
    return image_decoded, label 

但我現在無法養活列車步:

# Create the Estimator 
mnist_classifier = tf.estimator.Estimator(
model_fn=cnn_model_fn, model_dir="/model") 
# Set up logging for predictions 
tensors_to_log = {"probabilities": "softmax_tensor"} 
logging_hook = tf.train.LoggingTensorHook(
tensors=tensors_to_log, every_n_iter=50) 

# Train the model 
train_input_fn = tf.estimator.inputs.numpy_input_fn(
    x= {"x": dataset_train }, 
    y= dataset_train, 
    batch_size=100, 
    num_epochs=None, 
    shuffle=True) 
mnist_classifier.train(
    input_fn=train_input_fn, 
    steps=200, 
    hooks=[logging_hook]) 

我試圖按照本教程A Guide to TF Layers: Building a Convolutional Neural Network但我自己的IM年齡設置。

我不能直接使用數據集來提供列車步驟嗎?我的意思是,我只是爲每個圖像都有一個張量與特徵和標籤。

+0

對於'numpy_input_fn'數據集中在'numpy'預期,所以'_parse_function'必須返回圖像作爲numpy的陣列 – Maxim

回答

0

您參考的教程將數據讀取到一個numpy數組(請參閱the code here)並將輸入傳遞給tf.estimator.inputs.numpy_input_fn。這是最簡單的方法。

但是,如果您想從一開始就使用張量進行操作,則可以使用custom input function。這裏有一個簡單的例子:

def read_images(batch_size): 
    # A stub. Should read the next batch, shuffle it, etc 
    images = tf.zeros([batch_size, 28, 28, 1]) # 4-rank tensor 
    labels = tf.ones([batch_size])    # 1-rank tensor (not one-hot encoded) 
    return images, labels 

def simple_input(): 
    x, labels = read_images(batch_size=10) 
    return {"x": x}, labels 

tensors_to_log = {"probabilities": "softmax_tensor"} 
logging_hook = tf.train.LoggingTensorHook(tensors=tensors_to_log, every_n_iter=50) 

classifier.train(input_fn=simple_input, 
       steps=10, 
       hooks=[logging_hook])