首页 > 解决方案 > 在 Tensorflow C++ 中将浮点向量传递给张量

问题描述

我有一个 LSTM 冻结图,它需要 10 个序列,每个输入序列有 10 个长度为 2002 的向量。
我的代码在 python 中工作,但我不知道如何在 C++ 中做同样的事情。
如何将我的向量序列转换为 LSTM 就绪的张量序列?

代码:

/// concatenate vector 1 and vector 2 features
std::vector<float> vecOne_vecTwo_concat;
/// preallocate memory
vecOne_vecTwo_concat.reserve(vecOne.size() + vecTwo.size());
/// concatenate (first half is vecOne; second half is vecTwo)
/// add vecOne
vecOne_vecTwo_concat.insert(vecOne_vecTwo_concat.end(),
 vecOne.begin(), vecOne.end());
/// add vecTwo
vecOne_vecTwo_concat.insert(vecOne_vecTwo_concat.end(),
 vecTwo.begin(), vecTwo.end() );

/// append to vector of features
sequence_vector_.push_back(vecOne_vecTwo_concat);

/// check if we have enough sequences to make a classification
/// here n_rnn_steps_ is 10
/// each vector in this sequence is of length 2002
/// so we have 10 vectors, each of length 2002
if (sequence_vector_.size() == n_rnn_steps_) {

  /* Here we feed the concatenated vector sequence into
     the session running the LSTM graph
  */

  /// reset vector after we have feed it into the session
  sequence_vector_.clear();
}

标签: pythonc++tensorflowlstm

解决方案


您可以作为指针直接访问创建的张量的内存。

Tensor aTensor(DT_FLOAT, TensorShape({ sequenceLength }));
float *p = aTensor.flat<float>().data();

然后您可以将数据复制到该内存或使用 memcpy。


推荐阅读