Tensorflow 汇总合并错误:形状 [-1,784] 具有负尺寸

2023-11-26

我试图总结下面神经网络的训练过程。

import tensorflow as tf 
import numpy as np 

from tensorflow.examples.tutorials.mnist import input_data

mnist = input_data.read_data_sets(".\MNIST",one_hot=True)

# Create the model
def train_and_test(hidden1,hidden2, learning_rate, epochs, batch_size):

    with tf.name_scope("first_layer"):
        input_data = tf.placeholder(tf.float32, [batch_size, 784], name = "input")
        weights1  = tf.Variable(
        tf.random_normal(shape =[784, hidden1],stddev=0.1),name = "weights")
        bias = tf.Variable(tf.constant(0.0,shape =[hidden1]), name = "bias")
        activation = tf.nn.relu(
        tf.matmul(input_data, weights1) + bias, name = "relu_act")
        tf.summary.histogram("first_activation", activation)

    with tf.name_scope("second_layer"):
        weights2  = tf.Variable(
        tf.random_normal(shape =[hidden1, hidden2],stddev=0.1),
        name = "weights")
        bias2 = tf.Variable(tf.constant(0.0,shape =[hidden2]), name = "bias")
        activation2 = tf.nn.relu(
        tf.matmul(activation, weights2) + bias2, name = "relu_act")
        tf.summary.histogram("second_activation", activation2)

    with tf.name_scope("output_layer"):
        weights3 = tf.Variable(
            tf.random_normal(shape=[hidden2, 10],stddev=0.5), name = "weights")
        bias3 = tf.Variable(tf.constant(1.0, shape =[10]), name = "bias")
        output = tf.add(
        tf.matmul(activation2, weights3, name = "mul"), bias3, name = "output")
        tf.summary.histogram("output_activation", output)
    y_ = tf.placeholder(tf.float32, [batch_size, 10])

    with tf.name_scope("loss"):
        cross_entropy = tf.reduce_mean(
        tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=output))
        tf.summary.scalar("cross_entropy", cross_entropy)
    with tf.name_scope("train"):
        train_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(cross_entropy)

    with tf.name_scope("tests"):
        correct_prediction = tf.equal(tf.argmax(output, 1), tf.argmax(y_, 1))
        accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

    summary_op = tf.summary.merge_all()

    sess = tf.InteractiveSession()
    writer = tf.summary.FileWriter("./data", sess.graph)
    tf.global_variables_initializer().run()

    # Train
    for i in range(epochs):
        batch_xs, batch_ys = mnist.train.next_batch(batch_size)
         _, summary = sess.run([train_step,summary_op], feed_dict={input_data: batch_xs, y_: batch_ys})
     writer.add_summary(summary)

     if i % 10 ==0:
          test_xs, test_ys = mnist.train.next_batch(batch_size)
          test_accuracy = sess.run(accuracy, feed_dict = {input_data : test_xs, y_ : test_ys})
    writer.close()
    return test_accuracy

if __name__ =="__main__":
print(train_and_test(500, 200, 0.001, 10000, 100))

我每 10 个步骤都会使用一批随机测试数据来测试模型。 问题出在夏日作家身上。 for 循环内的 sess.run() 抛出以下错误。

    Traceback (most recent call last):

  File "<ipython-input-18-78c88c8e6471>", line 1, in <module>
    runfile('C:/Users/Suman 
Nepal/Documents/Projects/MNISTtensorflow/mnist.py', wdir='C:/Users/Suman 
Nepal/Documents/Projects/MNISTtensorflow')

  File "C:\Users\Suman Nepal\Anaconda3\lib\site-
packages\spyder\utils\site\sitecustomize.py", line 880, in runfile
execfile(filename, namespace)

  File "C:\Users\Suman Nepal\Anaconda3\lib\site-
packages\spyder\utils\site\sitecustomize.py", line 102, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)

  File "C:/Users/Suman Nepal/Documents/Projects/MNISTtensorflow/mnist.py", line 68, in <module>
    print(train_and_test(500, 200, 0.001, 100, 100))

  File "C:/Users/Suman Nepal/Documents/Projects/MNISTtensorflow/mnist.py", line 58, in train_and_test
    _, summary = sess.run([train_step,summary_op], feed_dict={input_data: batch_xs, y_: batch_ys})

  File "C:\Users\Suman Nepal\Anaconda3\lib\site-packages\tensorflow\python\client\session.py", line 789, in run
    run_metadata_ptr)

  File "C:\Users\Suman Nepal\Anaconda3\lib\site-packages\tensorflow\python\client\session.py", line 997, in _run
feed_dict_string, options, run_metadata)

  File "C:\Users\Suman Nepal\Anaconda3\lib\site-packages\tensorflow\python\client\session.py", line 1132, in _do_run
target_list, options, run_metadata)

  File "C:\Users\Suman Nepal\Anaconda3\lib\site-packages\tensorflow\python\client\session.py", line 1152, in _do_call
raise type(e)(node_def, op, message)

InvalidArgumentError: Shape [-1,784] has negative dimensions
 [[Node: first_layer_5/input = Placeholder[dtype=DT_FLOAT, shape=[?,784], _device="/job:localhost/replica:0/task:0/cpu:0"]()]]

Caused by op 'first_layer_5/input', defined at:
  File "C:\Users\Suman Nepal\Anaconda3\lib\site-packages\spyder\utils\ipython\start_kernel.py", line 231, in <module>
main()
  File "C:\Users\Suman Nepal\Anaconda3\lib\site-packages\spyder\utils\ipython\start_kernel.py", line 227, in main
kernel.start()
  File "C:\Users\Suman Nepal\Anaconda3\lib\site-packages\ipykernel\kernelapp.py", line 477, in start
ioloop.IOLoop.instance().start()
  File "C:\Users\Suman Nepal\Anaconda3\lib\site-packages\zmq\eventloop\ioloop.py", line 177, in start
super(ZMQIOLoop, self).start()
  File "C:\Users\Suman Nepal\Anaconda3\lib\site-packages\tornado\ioloop.py", line 888, in start
handler_func(fd_obj, events)
  File "C:\Users\Suman Nepal\Anaconda3\lib\site-packages\tornado\stack_context.py", line 277, in null_wrapper
return fn(*args, **kwargs)
  File "C:\Users\Suman Nepal\Anaconda3\lib\site-packages\zmq\eventloop\zmqstream.py", line 440, in _handle_events
self._handle_recv()
  File "C:\Users\Suman Nepal\Anaconda3\lib\site-packages\zmq\eventloop\zmqstream.py", line 472, in _handle_recv
self._run_callback(callback, msg)
  File "C:\Users\Suman Nepal\Anaconda3\lib\site-packages\zmq\eventloop\zmqstream.py", line 414, in _run_callback
callback(*args, **kwargs)
  File "C:\Users\Suman Nepal\Anaconda3\lib\site-packages\tornado\stack_context.py", line 277, in null_wrapper
return fn(*args, **kwargs)
 File "C:\Users\Suman Nepal\Anaconda3\lib\site-packages\ipykernel\kernelbase.py", line 283, in dispatcher
return self.dispatch_shell(stream, msg)
 File "C:\Users\Suman Nepal\Anaconda3\lib\site-packages\ipykernel\kernelbase.py", line 235, in dispatch_shell
handler(stream, idents, msg)
  File "C:\Users\Suman Nepal\Anaconda3\lib\site-packages\ipykernel\kernelbase.py", line 399, in execute_request
user_expressions, allow_stdin)
  File "C:\Users\Suman Nepal\Anaconda3\lib\site-packages\ipykernel\ipkernel.py", line 196, in do_execute
res = shell.run_cell(code, store_history=store_history, silent=silent)
  File "C:\Users\Suman Nepal\Anaconda3\lib\site-packages\ipykernel\zmqshell.py", line 533, in run_cell
return super(ZMQInteractiveShell, self).run_cell(*args, **kwargs)
  File "C:\Users\Suman Nepal\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 2717, in run_cell
interactivity=interactivity, compiler=compiler, result=result)
  File "C:\Users\Suman Nepal\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 2827, in run_ast_nodes
if self.run_code(code, result):
  File "C:\Users\Suman Nepal\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 2881, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-8-78c88c8e6471>", line 1, in <module>
runfile('C:/Users/Suman Nepal/Documents/Projects/MNISTtensorflow/mnist.py', wdir='C:/Users/Suman Nepal/Documents/Projects/MNISTtensorflow')
  File "C:\Users\Suman Nepal\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 880, in runfile
execfile(filename, namespace)
  File "C:\Users\Suman Nepal\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 102, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
  File "C:/Users/Suman Nepal/Documents/Projects/MNISTtensorflow/mnist.py", line 86, in <module>
  File "C:/Users/Suman Nepal/Documents/Projects/MNISTtensorflow/mnist.py", line 12, in train_and_test
   input_data = tf.placeholder(tf.float32, [None, 784], name = "input")
  File "C:\Users\Suman Nepal\Anaconda3\lib\site-packages\tensorflow\python\ops\array_ops.py", line 1530, in placeholder
return gen_array_ops._placeholder(dtype=dtype, shape=shape, name=name)
  File "C:\Users\Suman Nepal\Anaconda3\lib\site-packages\tensorflow\python\ops\gen_array_ops.py", line 1954, in _placeholder
name=name)
  File "C:\Users\Suman Nepal\Anaconda3\lib\site-packages\tensorflow\python\framework\op_def_library.py", line 767, in apply_op
op_def=op_def)
  File "C:\Users\Suman Nepal\Anaconda3\lib\site-packages\tensorflow\python\framework\ops.py", line 2506, in create_op
original_op=self._default_original_op, op_def=op_def)
  File "C:\Users\Suman Nepal\Anaconda3\lib\site-packages\tensorflow\python\framework\ops.py", line 1269, in __init__
self._traceback = _extract_stack()

InvalidArgumentError (see above for traceback): Shape [-1,784] has negative dimensions
     [[Node: first_layer_5/input = Placeholder[dtype=DT_FLOAT, shape=[?,784], _device="/job:localhost/replica:0/task:0/cpu:0"]()]]

如果我删除了所有摘要编写者和摘要,则模型运行良好。 你能帮我找出这里的问题吗?我尝试操纵张量的形状但一无所获。


来自原始海报的已删除答案的一条评论:

我实际上在下面构建了一个神经网络with tf.Graph() as g。我删除了交互式会话并开始会话with tf.Session(g) as sess。它解决了问题。

图表g没有以这种方式标记为默认图,因此会话 (tf.InteractiveSession在原始代码中)将使用另一个图表来代替。

请注意,由于相同的错误消息,我偶然发现了这里。就我而言,我无意中遇到了这样的事情:

input_data = tf.placeholder(tf.float32, shape=(None, 50))
input_data = tf.tanh(input_data)
session.run(..., feed_dict={input_data: ...})

IE。我没有喂占位符。似乎其他一些张量运算可能会导致此令人困惑的错误,因为内部未定义的维度表示为 -1。

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

Tensorflow 汇总合并错误:形状 [-1,784] 具有负尺寸 的相关文章

  • Tensorflow 数据 API - 预取

    我正在尝试使用 TF 的新功能 即 Data API 但我不知道如何使用prefetch作品 在下面的代码中 def dataset input fn dataset tf data TFRecordDataset filenames co
  • 如何使用 TFlearn 中的 ImageAugmentation 训练 CNN 中的图像和数据混合

    我想使用图像 像素信息 和数据的混合在 Tflearn Tensorflow 中训练卷积神经网络 由于我的图像数量较少 因此我需要使用图像增强来增加传递到网络的图像样本数量 但这意味着我只能传递图像数据作为输入数据 必须在稍后阶段 大概在全
  • TensorFlow.js 调整 3D 张量大小

    我有一个具有以下尺寸的 3D 张量 宽度 x 高度 x 深度 我需要将可变大小的体积调整为特定形状 例如 256 x 256 x 256 不幸的是 在 TensorFlow js 中 他们有一组用于调整大小的方法 例如tf image re
  • 如何使用 keras.backend.gradients() 获取梯度值

    我试图获得 Keras 模型的输出相对于模型输入 x 而不是权重 的导数 似乎最简单的方法是使用 keras backend 中的 梯度 它返回梯度张量 https keras io backend https keras io backe
  • TensorFlow CUDA_ERROR_OUT_OF_MEMORY

    我正在尝试在 TensorFlow 中构建一个大型 CNN 并打算在多 GPU 系统上运行它 我采用了 塔式 系统 并为两个 GPU 拆分批次 同时将变量和其他计算保留在 CPU 上 我的系统有 32GB 内存 但是当我运行代码时出现错误
  • TensorFlow 中的 global_step 是什么意思?

    在这就是教程代码 https github com tensorflow tensorflow blob master tensorflow examples tutorials mnist mnist py来自 TensorFlow 网站
  • 跨多个 GPU/机器的 TF-Slim 的配置/标志

    我很好奇是否有关于如何使用部署 model deploy py 在多台机器上的多个 GPU 上运行 TF Slim models slim 的示例 该文档非常好 但我缺少一些内容 具体来说 需要为worker device和ps devic
  • 使用输入管道时如何替换 feed_dict?

    假设您有一个已与feed dict到目前为止将数据注入到图表中 每隔几个时期 我就会通过将任一数据集的一批数据输入到我的图表中来评估训练和测试损失 现在 出于性能原因 我决定使用输入管道 看看这个虚拟示例 import tensorflow
  • Tensorflow推荐的系统规格?

    我开始在我的 RHEL 6 5 机器上安装 Tensorflow 但事实证明 Tensorflow 需要 glibc gt 2 17 而 rhel 6 5 上默认的 glibc 是 2 12 我想知道是否有人可以帮助我了解张量流的最低 推荐
  • 如何使用 Tensorflow 中的 Hugging Face Transformers 库对自定义数据进行文本分类?

    我正在尝试使用 Hugging Face Transformers 库提供的不同变压器架构对自定义数据 csv 格式 进行二进制文本分类 我正在用这个张量流博客文章 https blog tensorflow org 2019 11 hug
  • Tensorboard 和 Dropout 层

    我有一个非常基本的查询 我制作了 4 个几乎相同 差异在于输入形状 的 CNN 并在连接到全连接层的前馈网络时合并了它们 几乎相同的 CNN 的代码 model3 Sequential model3 add Convolution2D 32
  • AttributeError:模块“keras.engine”没有属性“Layer”

    当我试图运行时Parking Slot mask rcnn py文件我收到如下错误mrcnn model py文件我该如何解决 gt 2021 06 17 08 25 18 585897 W tensorflow stream execut
  • 通过 cmake 使用预编译的张量流

    我已经建立了一个 C 项目CLion使用CMake 我正在使用各种第三方库 并且还想集成张量流 我试过了bazel编译张量流到共享库libtensorflow so哪种工作有效 但是仍然有相当多的依赖项 例如当前的 protobuf 版本
  • Tensorflow如何生成不平衡组合数据集

    我对新数据集 API tensorflow 1 4 有疑问 我有两个数据集 我需要创建一个组合的不平衡数据集 即 每个批次应包含第一个数据集中一定数量的元素和第二个数据集中一定数量的元素 例如 dataset1 tf data Datase
  • 从字符串列表创建 TfRecords 并在解码后在张量流中提供图形

    目的是创建 TfRecords 数据库 给定 我有 23 个文件夹 每个文件夹包含 7500 个图像 以及 23 个文本文件 每个文件有 7500 行描述单独文件夹中 7500 个图像的特征 我通过以下代码创建了数据库 import ten
  • 有没有办法在bigquery中使用kmeans、tensorflow保存的模型?

    我知道这有点愚蠢 因为 BigQueryML 现在为 Kmeans 提供了良好的初始化 尽管如此 我还是需要在张量流中训练一个模型 然后将其传递给 BigQuery 进行预测 我保存了模型 一切正常 直到我尝试将其上传到 bigquery
  • 无需安装 Tensorflow 即可服务 Tensorflow 模型

    我有一个经过训练的模型 想在 python 应用程序中使用 但我看不到任何在不安装 TensorFlow 或创建 gRPC 服务的情况下部署到生产环境的示例 有可能吗 在这种情况下 正确的做法是什么 如果不使用 TensorFlow 本身或
  • Tensorboard——High-level节点的计算时间与其子节点计算时间的总和不同

    继tutorial https www tensorflow org programmers guide graph viz在 TensorFlow 上 我试图使用张量板来理解运行时统计数据 我发现代表名称范围的高级节点的计算时间不等于其子
  • 交换keras中的张量轴

    我想将图像批次的张量轴从 batch size row col ch 交换为 批次大小 通道 行 列 在 numpy 中 这可以通过以下方式完成 X batch np moveaxis X batch 3 1 我该如何在 Keras 中做到
  • 对输入求 Keras 模型的导数返回全零

    所以我有一个 Keras 模型 我想将模型的梯度应用于其输入 这就是我所做的 import tensorflow as tf from keras models import Sequential from keras layers imp

随机推荐