tensorflow 无效参数:In[0] 不是矩阵 [英] tensorflow Invalid argument: In[0] is not a matrix
问题描述
我是 tensorflow C++ API 的新手,正在努力寻找文档在线的.这个短代码执行两个向量的内积W 和 x1,编译正常但有运行时错误,我复制代码和错误日志在这里.非常感谢您的帮助
i am new to tensorflow C++ API and struggling to find documentation online. this short code performs inner product of two vectors W and x1, compile fine but there are run time errors, i copy the code and error logs here. thanks a lot for the help
#include "tensorflow/cc/client/client_session.h"
#include "tensorflow/cc/ops/standard_ops.h"
#include "tensorflow/core/framework/tensor.h"
int main() {
using namespace tensorflow;
using namespace tensorflow::ops;
Tensor W (DT_FLOAT,TensorShape({2}));
Tensor x1(DT_FLOAT,TensorShape({2}));
auto W_map = W .tensor<float,1>();
auto x1_map = x1.tensor<float,1>();
for(int i=0;i<L;++i) {
W_map(i) = -1;
x1_map(i) = 1;
}
std::cout<<"W \n"<<W .flat<float>()<<"\n debug "<<W .DebugString()<<std::endl;
std::cout<<"x1 \n"<<x1.flat<float>()<<"\n debug "<<x1.DebugString()<<std::endl;
Scope root = Scope::NewRootScope();
ClientSession session(root);
// either line of code gives similar run time error
// auto v1 = MatMul(root.WithOpName("v1"), W, x1, MatMul::TransposeA(true));
auto v1 = MatMul(root.WithOpName("v1"), W, x1, MatMul::TransposeB(true));
std::vector<Tensor> o1;
TF_CHECK_OK(session.Run({v1}, &o1));
}
===========================
hweekuans-MacBook-Pro:linear_model hweekuan$ ./linear
W
-1
-1
debug Tensor<type: float shape: [2] values: -1 -1>
x1
1
1
debug Tensor<type: float shape: [2] values: 1 1>
F tensorflow/cc/20170412/linear_model/linear.cc:37] Check failed: ::tensorflow::Status::OK() == (session.Run({v1}, &o1)) (OK vs. Invalid argument: In[0] is not a matrix
[[Node: v1 = MatMul[T=DT_FLOAT, transpose_a=false, transpose_b=true, _device="/job:localhost/replica:0/task:0/cpu:0"](Const/Const, Const_1/Const)]])
Abort trap: 6
推荐答案
错误信息给出了问题的线索:W
和 x1
都不是二维的矩阵——事实上,两者都是一维向量——并且 tensorflow::ops::MatMul()
操作要求它的两个参数至少是二维的.它不会自动将向量转换为其矩阵表示,您必须手动执行此操作.
The error message gives a clue to the problem: neither W
nor x1
is a 2-D matrix—in fact, both are 1-D vectors—and the tensorflow::ops::MatMul()
op requires that both of its arguments are at least 2-dimensional. It does not automatically convert vectors to their matrix representation, and you must do this manually.
为了解决这个问题,在构造W
和TensorShape({2, 1})
TensorShape({1, 2})> 当你构造 x1
时.对于这些形状,您不应设置 MatMul::TransposeA(false)
和 MatMul::TransposeB(false)
,或者您可以省略这些选项,因为它们是默认值.
To solve the problem, specify TensorShape({1, 2})
when you construct W
and TensorShape({2, 1})
when you construct x1
. With these shapes, you should not set MatMul::TransposeA(false)
and MatMul::TransposeB(false)
, or you can omit these options since they are the default values.
这篇关于tensorflow 无效参数:In[0] 不是矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!