【问题标题】:Check failed: 1 == NumElements() (1 vs. 1792)Must have a one element tensor in Tensorflow C++检查失败:1 == NumElements() (1 vs. 1792)在 Tensorflow C++ 中必须有一个单元素张量
【发布时间】:2017-03-07 03:04:55
【问题描述】:

在Python代码中,将图像数据赋值给张量image_batch:

部分代码:

image_data = misc.imread(image_path)

image_batch = graph.get_tensor_by_name("input:0")
phase_train_placeholder = graph.get_tensor_by_name("phase_train:0")
embeddings = graph.get_tensor_by_name("embeddings:0")

feed_dict = {image_batch: np.expand_dims(image_data, 0), phase_train_placeholder: False}
rep = sess.run(embeddings, feed_dict=feed_dict)

C++ 代码:

const float * source_data = (float*) image.data;
Tensor image_batch(DT_FLOAT, TensorShape({1, 160, 160, 3}));
auto input = image_batch.tensor<float, 4>();
for (int y = 0; y < height; ++y) {
    const float* source_row = source_data + (y * width * depth);
    for (int x = 0; x < width; ++x) {
        const float* source_pixel = source_row + (x * depth);
        for (int c = 0; c < depth; ++c) {
            const float* source_value = source_pixel + c;
            //std::cout << *source_value << std::endl;
            input(0, y, x, c) = *source_value;
        }
    }
}
Tensor phase_train(DT_BOOL, TensorShape());
phase_train.scalar<bool>()() = false;

std::vector<std::pair<string, tensorflow::Tensor>> inputs = {
    { "input:0", image_batch },
    { "phase_train:0", phase_train },
};    
std::vector<Tensor> outputs;
Status run_status = session->Run(inputs, {"embeddings:0"}, {}, &outputs);
if (!status.ok()) {
    std::cout << status.ToString() << "\n";
    return 1;
}

auto output_c = outputs[0].scalar<float>(); //Error here

std::cerr << "SHOW\n";
// Print the results
std::cout << outputs[0].DebugString() << "\n";
std::cout << output_c() << "\n"; // 30

错误:

F tensorflow/core/framework/tensor.cc:493] 检查失败:1 == NumElements() (1 vs. 1792)必须有一个单元素张量

进程以退出代码 6 结束

报错的原因是什么?

【问题讨论】:

  • 猜测一下,可能文件没有正确读取,因此张量没有正确构造?您是否尝试过使用调试器或类似工具来隔离错误?或者打印相关对象的当前状态?
  • 是的,错误信息来自status.ToString(),有没有其他方法可以看到更详细的状态?

标签: c++ tensorflow


【解决方案1】:

在此之前,我犯了一个愚蠢的错误,并没有找到关键的错误代码。

auto output_c = outputs[0].scalar<float>();

替换:

auto output_c = outputs[0].flat<float>();

所有问题都解决了。

https://github.com/tensorflow/tensorflow/issues/3362(提示我检查什么代码)

@Aziuth 谢谢。

【讨论】:

  • 这是我收到的最神秘的错误。感谢您指出这一点。
猜你喜欢
  • 1970-01-01
  • 2018-10-23
  • 2019-03-23
  • 2021-04-09
  • 2021-09-19
  • 2022-07-04
  • 1970-01-01
  • 1970-01-01
  • 2011-02-19
相关资源
最近更新 更多