2016-03-30 15 views
1

2_fullyconnected.ipynb udacity atamasını takip ederek oluşturduğum modele görüntü aktarmaya çalışıyorum.Tensorflow modelinde bir görüntüyü görüntüledikten sonra sınıflandırma yapılmadı

Modeli oluşturduğum kod aşağıda gösterilmiştir.

# In[1]: 

from __future__ import print_function 
import numpy as np 
import tensorflow as tf 
from six.moves import cPickle as pickle 
from six.moves import range 


# First reload the data we generated in `1_notmnist.ipynb`. 

# In[2]: 

pickle_file = 'notMNIST.pickle' 

with open(pickle_file, 'rb') as f: 
    save = pickle.load(f) 
    train_dataset = save['train_dataset'] 
    train_labels = save['train_labels'] 
    valid_dataset = save['valid_dataset'] 
    valid_labels = save['valid_labels'] 
    test_dataset = save['test_dataset'] 
    test_labels = save['test_labels'] 
    del save # hint to help gc free up memory 
    print('Training set', train_dataset.shape, train_labels.shape) 
    print('Validation set', valid_dataset.shape, valid_labels.shape) 
    print('Test set', test_dataset.shape, test_labels.shape) 
    print(train_dataset[0]) 
    print(train_labels[0]) 


# Reformat into a shape that's more adapted to the models we're going to train: 
# - data as a flat matrix, 
# - labels as float 1-hot encodings. 

# In[3]: 

image_size = 28 
num_labels = 10 

def reformat(dataset, labels): 
    print(type(dataset)) 
    #print(dataset[0]) 
    dataset = dataset.reshape((-1, image_size * image_size)).astype(np.float32) 
    # Map 0 to [1.0, 0.0, 0.0 ...], 1 to [0.0, 1.0, 0.0 ...] 
    labels = (np.arange(num_labels) == labels[:,None]).astype(np.float32) 
    return dataset, labels 
train_dataset, train_labels = reformat(train_dataset, train_labels) 
valid_dataset, valid_labels = reformat(valid_dataset, valid_labels) 
test_dataset, test_labels = reformat(test_dataset, test_labels) 
print('Training set', train_dataset.shape, train_labels.shape) 
print('Validation set', valid_dataset.shape, valid_labels.shape) 
print('Test set', test_dataset.shape, test_labels.shape) 


#stochastic gradient descent training 

# In[7]: 

batch_size = 128 

graph = tf.Graph() 
with graph.as_default(): 

    # Input data. For the training data, we use a placeholder that will be fed 
    # at run time with a training minibatch. 
    tf_train_dataset = tf.placeholder(tf.float32, 
            shape=(batch_size, image_size * image_size)) 
    tf_train_labels = tf.placeholder(tf.float32, shape=(batch_size, num_labels)) 
    tf_valid_dataset = tf.constant(valid_dataset) 
    tf_test_dataset = tf.constant(test_dataset) 

    # Variables. 
    weights = tf.Variable(
    tf.truncated_normal([image_size * image_size, num_labels]),name = "weights") 
    biases = tf.Variable(tf.zeros([num_labels]),name ="biases") 

    # Training computation. 
    logits = tf.matmul(tf_train_dataset, weights) + biases 
    loss = tf.reduce_mean(
    tf.nn.softmax_cross_entropy_with_logits(logits, tf_train_labels)) 

    # Optimizer. 
    optimizer = tf.train.GradientDescentOptimizer(0.5).minimize(loss) 

    # Predictions for the training, validation, and test data. 
    train_prediction = tf.nn.softmax(logits) 
    valid_prediction = tf.nn.softmax(
    tf.matmul(tf_valid_dataset, weights) + biases) 
    test_prediction = tf.nn.softmax(tf.matmul(tf_test_dataset, weights) + biases) 


# In[9]: 

def accuracy(predictions, labels): 
    return (100.0 * np.sum(np.argmax(predictions, 1) == np.argmax(labels, 1)) 
     /predictions.shape[0]) 


# Let's run it: 

# In[10]: 

num_steps = 3001 

with tf.Session(graph=graph) as session: 
    tf.initialize_all_variables().run() 
    print("Initialized") 
    for step in range(num_steps): 
    # Pick an offset within the training data, which has been randomized. 
    # Note: we could use better randomization across epochs. 
    offset = (step * batch_size) % (train_labels.shape[0] - batch_size) 
    # Generate a minibatch. 
    batch_data = train_dataset[offset:(offset + batch_size), :] 
    batch_labels = train_labels[offset:(offset + batch_size), :] 
    # Prepare a dictionary telling the session where to feed the minibatch. 
    # The key of the dictionary is the placeholder node of the graph to be fed, 
    # and the value is the numpy array to feed to it. 
    feed_dict = {tf_train_dataset : batch_data, tf_train_labels : batch_labels} 
    _, l, predictions = session.run(
     [optimizer, loss, train_prediction], feed_dict=feed_dict) 
    if (step % 500 == 0): 
     print("Minibatch loss at step %d: %f" % (step, l)) 
     print("Minibatch accuracy: %.1f%%" % accuracy(predictions, batch_labels)) 
     print("Validation accuracy: %.1f%%" % accuracy(
     valid_prediction.eval(), valid_labels)) 
    print("Test accuracy: %.1f%%" % accuracy(test_prediction.eval(), test_labels)) 
    save_path = tf.train.Saver().save(session, "/tmp/important_model/model.ckpt") 
    print("Model saved in file: %s" % save_path) 

Model/tmp/important_model/dizinine kaydedilir.

important_model/ 
|-- checkpoint 
|-- model.ckpt 
`-- model.ckpt.meta 

Şimdi ben Modelimin geri yükleyebilir ve ardından sınıflandırma için modele bir görüntü geçmesine çalışıyorum ettiği yeni bir dosya oluşturma şu şekildedir: bu klasör için

Ağacı yapıdır.

Grafiği yeni python dosyasında da oluşturdum, bu da modeli geri yüklemek için gerekli (bence yanlış olabilirim, yanılıyorsam lütfen beni düzeltin). i geliyor çıkışı notebookthe bu ipython içinde ln [34] yürütme am

# In[16]: 

# These are all the modules we'll be using later. Make sure you can import them 
# before proceeding further. 
from __future__ import print_function 
import numpy as np 
import tensorflow as tf 
from six.moves import cPickle as pickle 
from six.moves import range 
from scipy import ndimage 


# In[17]: 

image_size = 28 
num_labels = 10 


# In[25]: 

# With gradient descent training, even this much data is prohibitive. 
# Subset the training data for faster turnaround. 
#train_subset = 1000 

batch_size = 1 

graph = tf.Graph() 
with graph.as_default(): 

    # Variables. 
    # These are the parameters that we are going to be training. The weight 
    # matrix will be initialized using random valued following a (truncated) 
    # normal distribution. The biases get initialized to zero. 
    # Variables. 
    #saver = tf.train.Saver() 
    weights = tf.Variable(
    tf.truncated_normal([image_size * image_size, num_labels]),name = "weights") 
    biases = tf.Variable(tf.zeros([num_labels]),name ="biases") 

    tf_valid_dataset = tf.placeholder(tf.float32, 
            shape=(batch_size, image_size * image_size)) 
    valid_prediction = tf.nn.softmax(
    tf.matmul(tf_valid_dataset, weights) + biases) 


# In[26]: 

def accuracy(predictions, labels): 
    return (100.0 * np.sum(np.argmax(predictions, 1) == np.argmax(labels, 1)) 
     /predictions.shape[0]) 


# In[34]: 

pixel_depth = 255 
image_data = (ndimage.imread('notMNIST_small/A/QXJyaWJhQXJyaWJhU3RkLm90Zg==.png').astype(float) - 
        pixel_depth/2)/pixel_depth 
print(image_data.shape) 
resized_data = image_data.reshape((-1,784)) 
print(resized_data.shape) 

with tf.Session(graph=graph) as session: 
    tf.train.Saver().restore(session, "/tmp/important_model/model.ckpt") 
    print("Model restored.") 
    session.run(valid_prediction,feed_dict={tf_valid_dataset:resized_data}) 

geçerli:

(28, 28) 
(1, 784) 
Model restored 

Bana verilen görüntü ait olabilir 5 muhtemel etiketleri anlatmak istiyorum ama don' nasıl yapılacağını bilmeden, Yukarıdaki program herhangi bir hata göstermez, ancak istenilen çıktıyı göstermez. Görüntümün tf.nn.softmax işlevinde geçirdiğim, ancak maalesef hiçbir şey almadığım gibi, tüm sınıflardaki görüntülenme olasılıklarını alacağımı düşündüm.

Herhangi bir yardım için teşekkür ederiz.

session.run(valid_prediction,feed_dict={tf_valid_dataset:resized_data}) 

Bu yöntemin sonucu NumPy geçerli:

cevap

2

kodunuzda aşağıdaki satırı (bu durumda tek bir görüntü), veri kümesindeki her resim için olası çıkış Etiketler arasında bir olasılık dağılımını hesaplar şekil (1, 10) dizisi. olasılıkları görmek için, basitçe dizi yazdırabilirsiniz:

Eğer görüntü için üst k tahminler alabilirsiniz birçok yolu vardır
result = session.run(valid_prediction,feed_dict={tf_valid_dataset:resized_data}) 
print(result) 

. Yardımlarınız için

valid_prediction = tf.nn.softmax(tf.matmul(tf_valid_dataset, weights) + biases) 
top_5_labels = tf.nn.top_k(valid_prediction, k=5) 

# ... 
result = session.run(top_5_labels, feed_dict={tf_valid_dataset: resized_data}) 
print(result) 
+0

Teşekkür: En kolay biri, grafiğini tanımlarken TensorFlow en tf.nn.top_k() operatörü kullanmaktır. Şimdi çalışıyor . Grafiği yeniden modele geri yüklediğimiz python dosyasında neden yeniden tanımlamamız gerekiyor? . Bunu hala anlamadım. – kkk

+1

Bunu, otomatik olarak "tf.MetaGraphDef" (kontrol noktası koduyla oluşturulmuş) kullanarak yapmak için deneysel destek var, ancak büyük olasılıkla henüz asal bir zamanda hazır değil. Yine de işler sürekli gelişiyor! – mrry