Tensorflow、train_step 馈送不正确

2024-01-10

我正在从 Convnetjs 切换到 Tensorflow,并且正在学习读取图像和使用 Tensorflow 训练 CNN 的基础知识。

我在两个文件夹中有一堆 160*120*1 的图像:train/go 和 train/no,所以我使用两个类。

不知何故,我可以了解 tf.train.slice_input_ Producer 和 sess.run(train_step.

My code:

import tensorflow as tf

def read_my_list( minId, maxId ):
    """ create list with train/no and train/go from 1 to maxid
        max maxId = 50000
    """ 

    filenames = []
    labels = []
    for num in range( minId, maxId ):

        filenames.append( "/media/boss/tensor/train/go/" + str( num ) + ".jpg" )
        labels.append( int( 1 ) )

        filenames.append( "/media/boss/tensor/train/no/" + no_go_name( num ) + ".jpg" )
        labels.append( int( 0 ) )

        # return list with all filenames
    return filenames, labels

def no_go_name( id ):

    # create string where id = 5 becomes 00005

    ret = str( id )
    while ( len( ret ) < 5 ):
      ret = "0" + ret;

    return ret;


def read_images_from_disk(input_queue):
    """Consumes a single filename and label as a ' '-delimited string.
    Args:
      filename_and_label_tensor: A scalar string tensor.
    Returns:
      Two tensors: the decoded image, and the string label.
    """
    label = input_queue[1]
    print( "read file "  )
    file_contents = tf.read_file(input_queue[0])
    example = tf.image.decode_jpeg(file_contents, channels=1)

    # do i need to set shape??????????
    example.set_shape([160, 120, 1])
    print( "file read " )
    return  example, label



# some stuff to create a cnn etc
x = tf.placeholder(tf.float32, [None, 19200])

W = tf.Variable(tf.zeros([19200, 2]))
b = tf.Variable(tf.zeros([2]))

y = tf.nn.softmax(tf.matmul(x, W) + b)

y_ = tf.placeholder(tf.float32, [None, 2])

cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1]))

train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)

init = tf.initialize_all_variables()

with tf.Session() as sess:
    sess.run(init)

    # get filelist and labels
    image_list, label_list = read_my_list( 1, 10 )

    # conver to tensors for input_queue
    images = tf.convert_to_tensor(image_list, dtype=tf.string)
    labels = tf.convert_to_tensor(label_list, dtype=tf.int32)

    # Makes an input queue
    input_queue = tf.train.slice_input_producer([images, labels],
                                        num_epochs=10,
                                        shuffle=True)

    image, label = read_images_from_disk(input_queue)

    for i in range(100):
        print( i )

        image_batch, label_batch = tf.train.batch([image, label],
                                          batch_size=2)


        #gives error see below                                     
        sess.run(train_step, feed_dict={x: image_batch, y_: label_batch})


    # test accuracy, unsure if something is wrong here
    correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))

    accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

    batch_xs, batch_ys = tf.train.batch([image, label],
                                      batch_size=10)

    print(sess.run(accuracy, feed_dict={x: batch_xs, y_: batch_ys}))

下面的行给出了一个错误:

sess.run(train_step, feed_dict={x: image_batch, y_: label_batch})

这是错误:

Traceback (most recent call last):

File "detectGoNo.py", line 95, in <module>
sess.run(train_step, feed_dict={x: image_batch, y_: label_batch})

File "/home/boss/anaconda2/envs/tensor2/lib/python2.7/site-
packages/tensorflow/python/client/session.py", line 340, in run

run_metadata_ptr)

File "/home/boss/anaconda2/envs/tensor2/lib/python2.7/site-
packages/tensorflow/python/client/session.py", line 545, in _run

raise TypeError('The value of a feed cannot be a tf.Tensor object. '

TypeError: The value of a feed cannot be a tf.Tensor object. Acceptable 
feed values include Python scalars, strings, lists, or numpy ndarrays.

更新 02-06-2016

我得到了与 nessuno 的解决方案、训练和验证相关的一切(代码如下) Mrry 表示管道更为典型,不幸的是这个管道不起作用(代码如下) 没有给出任何错误,但计算的成本保持不变,并且验证表明网络没有改善。

我最好的猜测是我向训练器提供标签的方式或使用 one_hot 函数的方式有问题。

验证部分似乎正在工作,当我感觉标签 0 准确度始终为 100%,标签 1 准确度为 0% 和 50/50 的图像为 50% 时。当然也可能是相反的情况,但由于训练时成本没有改变,我认为训练时出了问题

我知道,我现在使用的模型很简单,但对于调试来说它已经足够好了,工作版本能够在 1500 张图像内达到 80% 的准确率。

label = tf.cast( label, tf.int64 )

label = tf.one_hot( label, 2, 0, 1 )
label = tf.cast( label, tf.float32 )

我的代码:(工作)

import tensorflow as tf
import numpy      as np
import math

IMAGE_WIDTH  = 160
IMAGE_HEIGHT = 120
IMAGE_DEPTH  = 1
IMAGE_PIXELS = IMAGE_WIDTH * IMAGE_HEIGHT
NUM_CLASSES  = 2

STEPS         = 50000
STEP_PRINT    = 100
STEP_VALIDATE = 100
LEARN_RATE    = 0.0014
DECAY_RATE    = 0.4
BATCH_SIZE    = 5

def read_my_list( minId, maxId, folder ):
    """ create list with train/no and train/go from 1 to maxid
        max maxId = 50000
    """ 

    filenames = []
    labels    = []
    #labels = np.zeros( ( ( maxId - minId ) * 2, 2 ) )
    for num in range( minId, maxId ):

        filenames.append( "/media/boss/2C260F93260F5CE8/tensor/" + folder + "/go/" + str( num ) + ".jpg" )
        #labels[ ( num - minId ) * 2 ][ 1 ] = 1
        labels.append( int( 1 ) )

        filenames.append( "/media/boss/2C260F93260F5CE8/tensor/" + folder + "/no/" + no_go_name( num ) + ".jpg" )
        #labels[ ( ( num - minId ) * 2 ) + 1 ][ 0 ] = 1
        labels.append( int( 0 ) )

        # return list with all filenames
    print( "label: " + str( len( labels ) ) )
    print( "image: " + str( len( filenames ) ) )
    return filenames, labels

def no_go_name( id ):

    # create string where id = 5 becomes 00005

    ret = str( id )
    while ( len( ret ) < 5 ):
      ret = "0" + ret;

    return ret;

# Create model
def conv_net(x):

    img_width  = IMAGE_WIDTH
    img_height = IMAGE_HEIGHT
    img_depth  = IMAGE_DEPTH

    weights    = tf.Variable( tf.random_normal( [ img_width * img_height * img_depth, NUM_CLASSES ] ) )
    biases     = tf.Variable( tf.random_normal( [ NUM_CLASSES ] ) )

    # softmax layer
    out        = tf.add( tf.matmul( x, weights ), biases )
    return out 

def read_images_from_disk(input_queue):
    """Consumes a single filename and label as a ' '-delimited string.
    Args:
      filename_and_label_tensor: A scalar string tensor.
    Returns:
      Two tensors: the decoded image, and the string label.
    """
    label = input_queue[1]
    print( "read file "  )
    file_contents = tf.read_file(input_queue[0])
    example = tf.image.decode_jpeg( file_contents, channels = 1 )

    example = tf.reshape( example, [ IMAGE_PIXELS ] )
    example.set_shape( [ IMAGE_PIXELS ] )

    example = tf.cast( example, tf.float32 )
    example = tf.cast( example, tf.float32 ) * ( 1. / 255 ) - 0.5

    label = tf.cast( label, tf.int64 )

    label = tf.one_hot( label, 2, 0, 1 )
    label = tf.cast( label, tf.float32 )

    print( "file read " )
    return  example, label

with tf.Session() as sess:

    ########################################
    # get filelist and labels for training
    image_list, label_list = read_my_list( 501, 50000, "train" )

    # create queue for training
    input_queue = tf.train.slice_input_producer( [ image_list, label_list ],
                                                num_epochs = 100,
                                                shuffle = True )

    # read files for training
    image, label = read_images_from_disk( input_queue )

    # `image_batch` and `label_batch` represent the "next" batch
    # read from the input queue.
    image_batch, label_batch = tf.train.batch( [ image, label ], batch_size = BATCH_SIZE )

    # input output placeholders

    x = tf.placeholder(tf.float32, [None, IMAGE_PIXELS])
    y_ = tf.placeholder(tf.float32, [None, NUM_CLASSES])

    # create the network
    y = conv_net( x )

    # loss
    cost = tf.reduce_mean( tf.nn.softmax_cross_entropy_with_logits( y, y_) )

    learning_rate = tf.placeholder(tf.float32, shape=[])

    # train step
    train_step   = tf.train.AdamOptimizer( 1e-3 ).minimize( cost )


    ########################################
    # get filelist and labels for validation
    image_list_test, label_list_test = read_my_list( 1, 500, "validation" )

    # create queue for validation
    input_queue_test = tf.train.slice_input_producer( [ image_list_test, label_list_test ],
                                                shuffle=True )

    # read files for validation
    image_test, label_test = read_images_from_disk( input_queue_test )

    # `image_batch_test` and `label_batch_test` represent the "next" batch
    # read from the input queue test.
    image_batch_test, label_batch_test = tf.train.batch( [ image_test, label_test ], batch_size=200 )

    correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))

    accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

    init = tf.initialize_all_variables()
    sess.run(init)

    # N.B. You must run this function before `sess.run(train_step)` to
    # start the input pipeline.
    #tf.train.start_queue_runners(sess)
    coord = tf.train.Coordinator()
    threads = tf.train.start_queue_runners(coord=coord)

    for i in range(STEPS):
        # No need to feed, because `x` and `y_` are already bound to
        # the next input batch.   
        if i % STEP_PRINT == 0:
            LEARN_RATE = LEARN_RATE * DECAY_RATE
            print( str( i ) + " " + str( LEARN_RATE ) )

        if i % STEP_VALIDATE == 0:

            imgs, lbls = sess.run([image_batch_test, label_batch_test])

            print(sess.run(accuracy, feed_dict={
                    x: imgs,
                    y_: lbls}))

        imgs, lbls = sess.run([image_batch, label_batch])

        sess.run(train_step, feed_dict={
         x: imgs,
         y_: lbls}) 
#         ,learning_rate:LEARN_RATE})      

    imgs, lbls = sess.run([image_batch_test, label_batch_test])

    print(sess.run(accuracy, feed_dict={
         x: imgs,
         y_: lbls}))

    coord.request_stop()
    coord.join(threads)

我的代码:(不工作)

with tf.Session() as sess:

    ########################################
    # get filelist and labels for training
    image_list, label_list = read_my_list( 501, 50000, "train" )

    # create queue for training
    input_queue = tf.train.slice_input_producer( [ image_list, label_list ],
                                                num_epochs = 100,
                                                shuffle = True )

    # read files for training
    image, label = read_images_from_disk( input_queue )

    # `image_batch` and `label_batch` represent the "next" batch
    # read from the input queue.
    image_batch, label_batch = tf.train.batch( [ image, label ], batch_size = BATCH_SIZE )

    x = image_batch
    y_ = label_batch

    # create the network
    y = conv_net( x )

    # loss
    cost = tf.reduce_mean( tf.nn.softmax_cross_entropy_with_logits( y, y_) )

    # train step
    train_step   = tf.train.AdamOptimizer( 1e-3 ).minimize( cost )


    ########################################
    # get filelist and labels for validation
    image_list_test, label_list_test = read_my_list( 1, 500, "validation" )

    # create queue for validation
    input_queue_test = tf.train.slice_input_producer( [ image_list_test, label_list_test ],
                                                shuffle=True )

    # read files for validation
    image_test, label_test = read_images_from_disk( input_queue_test )

    # `image_batch_test` and `label_batch_test` represent the "next" batch
    # read from the input queue test.
    image_batch_test, label_batch_test = tf.train.batch( [ image_test, label_test ], batch_size=200 )

    xval = image_batch_test
    yval_ = label_batch_test

    # network for validation
    yval = conv_net( xval )

    # validate network
    correct_prediction = tf.equal( tf.argmax( yval, 1 ), tf.argmax( yval_, 1 ) )

    # calculate accuracy
    accuracy = tf.reduce_mean( tf.cast( correct_prediction, tf.float32 ) )

    # init all variables
    init = tf.initialize_all_variables()
    sess.run( init )

    # N.B. You must run this function before `sess.run(train_step)` to
    # start the input pipeline.
    coord = tf.train.Coordinator()
    threads = tf.train.start_queue_runners( coord = coord )

    for i in range(STEPS):
        # No need to feed, because `x` and `y_` are already bound to
        # the next input batch.   
        if i % STEP_PRINT == 0:
            print( i )

        # validate accuracy
        if i % STEP_VALIDATE == 0:
            print( sess.run( accuracy ) )

        # train one step
        sess.run( train_step )  

    # validate accuracy
    print( sess.run( accuracy ) )

    coord.request_stop()
    coord.join( threads )

更新 10-06-2016
我花了一段时间才意识到训练管道和验证管道不具有相同的权重和偏差。
现在我训练、保存模型并在单独的脚本中加载模型,效果非常好。


image_batch and label_batch are tf.Tensor对象。

背后的想法feed_dict是将值从图外传递到图内。张量对象是图中的值。

因此,您必须在图表内评估两个张量对象(以提取内容),然后将计算值(现在是 python 值)提供给图表。

因此,评估值

imgs, lbls = image_batch.eval(), label_batch.eval()

或者(更好,因为它使用单个调用)

imgs, lbls = sess.run([image_batch, label_batch])

然后提供图表,用返回值替换占位符的内容:

    sess.run(train_step, feed_dict={
         x: imgs,
         y_: lbls})
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Tensorflow、train_step 馈送不正确 的相关文章

随机推荐

  • 无法执行简单的导航到查看和返回 SwiftUI 导航栏按钮

    我正在尝试使用 SwiftUI 进行从一个视图到另一个视图的简单导航 一个栏按钮项目 我尝试了三种不同的方法来调用新视图 在正文视图中使用 Button 可以 但在导航中使用 NavigationBarItems bar 以两种不同的方式失
  • 如何在android中创建自定义通知

    我需要创建一个自定义通知而不是 android 中的默认通知 当前通知有一个图标 标题和消息 如下图所示 我想要它像这样定制 我怎样才能做到这一点 通知视图 普通视图 普通视图中的通知出现在高度高达 64 dp 的区域中 即使您创建具有大视
  • 如何将两个函数传递给react中的onClick事件

    我想将两个函数传递给onClick事件是handleSubmit and handleDelete to the HomePage js来自HomeItem js 这是我的错误 No duplicate props allowed reac
  • C# - 通过相同的方法传递不同类型的对象

    原始问题 所以我有这 3 个对象 public class obj1 public int Id get set public string Name get set public class obj2 public int AccNum
  • Android 版 Google 登录:无法解析 RC_SIGN_IN

    我正在尝试通过移动应用程序通过后端服务器进行身份验证 我正在关注这个文档 https developers google com identity sign in android sign in https developers googl
  • 使用 Google Apps 脚本标记 Gmail 邮件(不是整个线程)

    是否可以搜索带有 应用程序脚本队列 标签的消息并为这些特定消息 而不是整个线程 提供新标签 当我使用 GmailApp search label Apps script queue 时 我收到请求的邮件 但是当我为这些邮件分配新标签时 该线
  • 如何包含动态时间?

    我正在尝试提取有关时间段的日志 当没有时 下面的程序运行得很好 给出小时数 并提取该范围内的日志 但现在我还包括动态给出的开始和结束 即说之间8 am to 8pm or 6am to 8am等等 我怎样才能得到它 当前程序中的任何编辑也可
  • 在 SwiftUI 的 Picker 中添加新元素

    我找不到如何在 SwiftUI 的选择器视图中添加某些元素 在我的示例中 我想在单击按钮时在选择器中添加 Z 值 struct ContentView View State var values String A B C State pri
  • hash( (-2,2) ) == hash( (2,-2) ) 返回 True (Python)

    所以 这很有趣 Python 的hash臭名昭著的回报True on hash 1 hash 2 正如其他地方所讨论的 https stackoverflow com questions 10130454 why do 1 and 2 bo
  • 我如何要求 Lisp 编译器忽略(标签种类)函数?

    我盯着斯蒂尔的Common Lisp 语言直到我脸色发青 仍然有这个问题 如果我编译 defun x labels y 5 princ x terpri 有时候是这样的 home clisp experiments clisp c q x
  • 信号发射结构

    这个问题在我脑海里萦绕了很多天 但直到现在我才弄清楚 如果我尝试发送一个结构信号 struct radarStruct unsigned char Data unsigned int rate unsigned int timeStamp
  • ADB 设备卡在“连接”状态

    我正在尝试将我的手机连接到 Android Studio 以跟进一些应用程序开发 我目前正在努力将手机正确连接到计算机 因为 ADB 似乎从未连接到设备 当尝试在设备上启动应用程序时 这是 Android Studio 在运行控制台中告诉我
  • 如何向背景图像添加颜色叠加? [复制]

    这个问题在这里已经有答案了 我在 SO 和 Web 上都看到过很多这个问题 但它们都不是我要寻找的 如何仅使用 CSS 将颜色叠加添加到背景图像 HTML 示例 div class testclass div CSS 示例 testclas
  • R 和 ggplot-将 x 轴更改为日期可消除位置闪避

    我一直在使用 ggplot 来创建绘图 并且我总是喜欢水平偏移数据点 这样误差线就不会重叠 我发现当我使用日期数据作为 x 轴时 我失去了偏移数据点的能力 DF data frame Date c 2006 09 01 2007 09 01
  • 我怎样才能停止ajax请求(不要等到响应到来)?

    如果我使用Ajax发送请求并且这个请求需要很长时间 如果我想发送花药请求我该怎么办 当前的行为第二个请求 我做了 等待第一个请求得到响应 NOTE 我想在整个应用程序上执行此行为 任何新请求立即执行 而不是等待旧请求首先完成 我的应用程序使
  • 为什么我必须重新解释指针指针?

    So this static cast代码是完全合法的 int n 13 void pn static cast
  • MS Visual Studio 2012 可以与 Windows Vista 一起使用吗?

    我运行 Windows Vista Business 并想尝试 MS Visual Studio Express 2012 它们兼容吗 兼容性列表在哪里 至少官方没有 http www microsoft com visualstudio
  • 这个 GCD 实现的 getter setter 线程安全并且比 @synchronized 工作得更好吗?对象

    interface ViewController property nonatomic strong NSString someString end implementation ViewController synthesize some
  • wxPython ListCtrl 帮助

    我正在使用 ListCtrl 它会动态填充项目 当项目 激活 双击 Enter 时 它会调用一个函数 def onClick self event 由于没有预设 ID 我如何找出列表中的哪个项目被单击 字符串是作为自身还是事件的一部分传递给
  • Tensorflow、train_step 馈送不正确

    我正在从 Convnetjs 切换到 Tensorflow 并且正在学习读取图像和使用 Tensorflow 训练 CNN 的基础知识 我在两个文件夹中有一堆 160 120 1 的图像 train go 和 train no 所以我使用两