Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/307.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何将TensorFlow数据集API与密集层结合使用_Python_Tensorflow_Deep Learning - Fatal编程技术网

Python 如何将TensorFlow数据集API与密集层结合使用

Python 如何将TensorFlow数据集API与密集层结合使用,python,tensorflow,deep-learning,Python,Tensorflow,Deep Learning,我正在为中显示的输入管道尝试Dataset API,并使用几乎相同的代码: tr_data = Dataset.from_tensor_slices((train_images, train_labels)) tr_data = tr_data.map(input_parser, NUM_CORES, output_buffer_size=2000) tr_data = tr_data.batch(BATCH_SIZE) tr_data = tr_data.repeat(EPOCHS) ite

我正在为中显示的输入管道尝试Dataset API,并使用几乎相同的代码:

tr_data = Dataset.from_tensor_slices((train_images, train_labels))
tr_data = tr_data.map(input_parser, NUM_CORES, output_buffer_size=2000)
tr_data = tr_data.batch(BATCH_SIZE)
tr_data = tr_data.repeat(EPOCHS)

iterator = dataset.make_one_shot_iterator()
next_example, next_label = iterator.get_next()

# Script throws error here
loss = model_function(next_example, next_label)

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

     while True:
        try:
            train_loss = sess.run(loss)
        except tf.errors.OutOfRangeError:
            print("End of training dataset.")
            break
这应该更快,因为它避免了使用慢速进给指令。但是我不能让它与我的模型一起工作,这是一个简化的LeNet架构。问题是我的
model_function()
中的
tf.layers.dense
,它需要一个已知的输入形状(我猜是因为它必须事先知道权重的数量)。但是
next_示例
next_标签
只能通过在会话中运行它们来获得它们的形状。在评估它们之前,它们的形状只是未定义的

声明
model_函数()
会引发以下错误:

ValueError:
密集输入的最后一个维度应为
定义找到

现在,我不知道我是否以预期的方式使用此Dataset API,或者是否有解决方法

提前谢谢

编辑1: 下面是我的模型,它在第一个密集层抛出错误

def conv_relu(input, kernel_shape):
    # Create variable named "weights".
    weights = tf.get_variable("weights", kernel_shape,
        initializer=tf.random_normal_initializer())
    # Create variable named "biases".
    biases = tf.get_variable("biases", kernel_shape[3],
        initializer=tf.constant_initializer(0.0))
    conv = tf.nn.conv2d(input, weights,
        strides=[1, 1, 1, 1], padding='VALID')
    return tf.nn.relu(conv + biases)

def fully(input, output_dim):
    assert len(input.get_shape())==2, 'Wrong input shape, need flattened tensor as input'
    input_dim = input.get_shape()[1]

    weight = tf.get_variable("weight", [input_dim, output_dim],
        initializer=tf.random_normal_initializer())
    bias = tf.get_variable('bias', [output_dim],
        initializer=tf.random_normal_initializer())

    fully = tf.nn.bias_add(tf.matmul(input, weight), bias)
    return fully


def simple_model(x):

    with tf.variable_scope('conv1'):
        conv1 = conv_relu(x, [3,3,1,10])
        conv1 = tf.nn.max_pool(conv1,[1,2,2,1],[1,2,2,1],'SAME')

    with tf.variable_scope('conv2'):
        conv2 = conv_relu(conv1, [3,3,10,10])
        conv2 = tf.nn.max_pool(conv2,[1,2,2,1],[1,2,2,1],'SAME')

    with tf.variable_scope('conv3'):
        conv3 = conv_relu(conv2, [3,3,10,10])
        conv3 = tf.nn.max_pool(conv3,[1,2,2,1],[1,2,2,1],'SAME')

    flat = tf.contrib.layers.flatten(conv3)
    with tf.variable_scope('fully1'):
        fully1 = tf.layers.dense(flat, 1000)
        fully1 = tf.nn.relu(fully1)

    with tf.variable_scope('fully2'):
        fully2 = tf.layers.dense(fully1, 100)
        fully2 = tf.nn.relu(fully2)

    with tf.variable_scope('output'):
        output = tf.layers.dense(fully2, 4)
        fully1 = tf.nn.relu(output)


    return output
编辑2:

这里你可以看到张量的印记。请注意,下一个示例没有形状

下一个示例:张量(“IteratorGetNext:0”,dtype=float32)
next_标签:Tensor(“IteratorGetNext:1”,shape=(?,4),dtype=float32)


我自己找到了答案

接下来,简单的解决方法是使用
tf.Tensor.set\u shape
设置形状,前提是您事先知道图像大小

def input_parser(img_path, label):

    # read the img from file
    img_file = tf.read_file(img_path)
    img_decoded = tf.image.decode_image(img_file, channels=1)
    img_decoded = tf.image.convert_image_dtype(img_decoded, dtype=tf.float32)
    img_decoded.set_shape([90,160,1]) # This line was missing

    return img_decoded, label

如果tensorflow文档中包含这一行,那就太好了。

在这里看到您的model_函数也会很有帮助:)我想它会太长,但我同意。添加了我的模型。您应该打印tensorflow给出的错误,也可以在创建图形时打印下一个示例和下一个标签吗?我添加了打印。错误已经在问题->ValueError中:应该定义Dense输入的最后一个维度。没有找到。