2016-12-05 26 views
1

我试图将Tensorflow MNIST beginner tutorial修改为我自己的一组图像。这里是我到目前为止的代码:将Tensorflow初学者教程修改为自己的数据集

# Copyright 2015 The TensorFlow Authors. All Rights Reserved. 
# 
# Licensed under the Apache License, Version 2.0 (the "License"); 
# you may not use this file except in compliance with the License. 
# You may obtain a copy of the License at 
# 
#  http://www.apache.org/licenses/LICENSE-2.0 
# 
# Unless required by applicable law or agreed to in writing, software 
# distributed under the License is distributed on an "AS IS" BASIS, 
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
# See the License for the specific language governing permissions and 
# limitations under the License. 
# ============================================================================== 

"""A very simple MNIST classifier. 

See extensive documentation at 
http://tensorflow.org/tutorials/mnist/beginners/index.md 
""" 
from __future__ import absolute_import 
from __future__ import division 
from __future__ import print_function 

# Import data 
# from tensorflow.examples.tutorials.mnist import input_data 

import tensorflow as tf 
import pandas as pd 
import numpy as np 

IMAGE_WIDTH = 240 
IMAGE_HEIGHT = 240 
IMAGE_SIZE = IMAGE_WIDTH * IMAGE_HEIGHT 
SYMBOLS = ["accident", "bomb", "car", "casualty", "electricity", "fire", "firebrigade", "flood", "gaz", "injury", "paramedics", "person", "police", "roadblock"] 
NUM_CLASSES = len(SYMBOLS) 

def chunks(l, n): 
    n = max(1, n) 
    return (l[i:i+n] for i in xrange(0, len(l), n)) 

def main(_): 
    # Create the model 
    x = tf.placeholder(tf.float32, [None, IMAGE_SIZE]) 
    W = tf.Variable(tf.zeros([IMAGE_SIZE, NUM_CLASSES])) 
    b = tf.Variable(tf.zeros([NUM_CLASSES])) 
    y = tf.matmul(x, W) + b 

    # Define loss and optimizer 
    y_ = tf.placeholder(tf.float32, [None, NUM_CLASSES]) 

    # The raw formulation of cross-entropy, 
    # 
    # tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(tf.softmax(y)), 
    #         reduction_indices=[1])) 
    # 
    # can be numerically unstable. 
    # 
    # So here we use tf.nn.softmax_cross_entropy_with_logits on the raw 
    # outputs of 'y', and then average across the batch. 
    cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(y, y_)) 
    train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy) 

    sess = tf.InteractiveSession() 

    train = pd.read_csv('test.csv') 
    train.head() 

    xs = [] 
    for img_name in train.filename: 
    img = tf.image.decode_png(img_name) 
    img = tf.image.rgb_to_grayscale(img) 
    img = tf.image.resize_images(img, [IMAGE_WIDTH, IMAGE_HEIGHT]) 
    img = tf.expand_dims(img, 0) 
    xs.append(img) 

    ys = [] 
    for label_name in train.label: 
    one_hot = [0] * NUM_CLASSES 
    one_hot[int(label_name)] = 1 
    ys.append(one_hot) 

    # Train 
    tf.initialize_all_variables().run() 

    batches_img = [xs[x:x+100] for x in xrange(0, len(xs), 100)] 
    batches_labels = [ys[x:x+100] for x in xrange(0, len(ys), 100)] 

    for i, e in enumerate(batches_img): 
    sess.run(train_step, feed_dict={x: batches_img[i], y_: batches_labels[i]}) 

    print("Training done!\n") 

    # Test trained model 
    """test = pd.read_csv('test.csv') 
    test.head() 

    xs_test = [] 
    for img_name in test.filename: 
    img = imread(img_name, flatten=True) 
    xs_test.append(img) 

    ys_test = [] 
    for label_name in test.label: 
    one_hot = [0] * NUM_CLASSES 
    one_hot[int(label_name)] = 1 
    ys_test.append(one_hot) 

    correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1)) 
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) 
    print(sess.run(accuracy, feed_dict={x: xs_test, y_: ys_test}))""" 

if __name__ == '__main__': 
    tf.app.run() 

而我得到的错误是

TypeError: Cannot interpret feed_dict key as Tensor: Can not convert a int into a Tensor. 

回答

0

feed_dict参数期望张量作为自己的价值观,而您从batches_imgbatches_labels列表传递一个单独的项目。如果你看到下面一行:

for i, e in enumerate(batches_img): 
    sess.run(train_step, feed_dict={x: batches_img[i], y_: batches_labels[i]}) 

batches_img[i]会给你从batches_img列表中的单个元素,同样batches_labels[i]将让你一个项目从batches_label列表,你需要做的是通过列表(或np数组或tf.Tensor对象)。