【问题标题】:Tensorflow C API - Problem with the Input TensorTensorflow C API - 输入张量问题
【发布时间】:2021-05-13 20:50:02
【问题描述】:

我正在使用 Tensorflow API for C 在 python 中加载预训练模型并在嵌入式编译程序中运行预测。 我使用的模型将字符串作为输入,然后将其转换为张量,并给出一个浮点数作为输出。

API 可以很好地加载模型并运行会话而不会抱怨。

我面临的问题是,无论我将什么数据输入 C API 会话,我总是得到完全相同的输出张量。所以我猜我做错了什么,我只是看不到它是什么。但我假设我没有按照 C API 期望的方式格式化输入数据。

这是saved_model_cli的输出:

The given SavedModel SignatureDef contains the following input(s):
  inputs['lstm_input'] tensor_info:
      dtype: DT_FLOAT
      shape: (-1, 64, 88)
      name: serving_default_lstm_input:0
The given SavedModel SignatureDef contains the following output(s):
  outputs['dense'] tensor_info:
      dtype: DT_FLOAT
      shape: (-1, 1)
      name: StatefulPartitionedCall:0
Method name is: tensorflow/serving/predict

在 python 中,我将输入字符串转换为张量: (变量XX_val分别保存训练字符串和验证字符串)

from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.preprocessing.sequence import pad_sequences
from tensorflow.keras.utils import to_categorical

alphabet_size = len(set(all_lines))

tokenizer = Tokenizer(char_level=True)
tokenizer.fit_on_texts(all_lines)
seq_X = tokenizer.texts_to_sequences(X)
seq_X_val = tokenizer.texts_to_sequences(X_val)

seq_X = pad_sequences(seq_X, maxlen=64, padding='post')
seq_X_val = pad_sequences(seq_X_val, maxlen=64, padding='post')

one_hot_X = [to_categorical(x, num_classes=alphabet_size) for x in seq_X]
one_hot_X_val = [to_categorical(x_val, num_classes=alphabet_size) for x_val in seq_X_val]
one_hot_X = np.array(one_hot_X)
one_hot_X_val = np.array(one_hot_X_val)

这最终给了我以下tokenizer.word_index

{'%': 1, '2': 2, 'e': 3, 'l': 4, 'c': 5, 'n': 6, 'i': 7, 'a': 8, '0': 9, 's': 10, 'r': 11, 't': 12, '/': 13, '1': 14, 'o': 15, 'u': 16, ',': 17, 'd': 18, '7': 19, 'h': 20, '8': 21, ' ': 22, '6': 23, '9': 24, '=': 25, '\n': 26, '(': 27, ')': 28, 'p': 29, 'b': 30, '5': 31, 'm': 32, 'f': 33, 'w': 34, '3': 35, 'g': 36, 'v': 37, '?': 38, 'x': 39, "'": 40, '-': 41, '4': 42, '&': 43, '.': 44, '+': 45, '_': 46, 'y': 47, '|': 48, 'k': 49, 'j': 50, '@': 51, 'z': 52, '#': 53, '"': 54, 'q': 55, '>': 56, '*': 57, '~': 58, '!': 59, '^': 60, ':': 61, '<': 62}

所以当我想在 C 中使用这个模型时,我使用这里描述的方法来加载它: https://github.com/AmirulOm/tensorflow_capi_sample

这是我设置会话的方式:

首先,我有一个 C 数组,其作用与上面的 tokenizer.word_index 相同:

int     dictionary[] = {
...
    14,//1 - 49
    2,//2 - 50
    35,//3 - 51
    42,//4 - 52
    31,//5 - 53
    23,//6 - 54
    19,//7 - 55
    21,//8 - 56
    24,//9 - 57
    61,//: - 58
    0,//59
    62,//< - 60
    25,//= - 61
    56,//> - 62
    38,//? - 63
    51,//@ - 64
...
    5,//c - 99
    18,//d - 100
    3,//e - 101
    33,//f - 102
    36,//g - 103
    20,//h - 104
    7,//i - 105
    50,//j - 106
    49,//k - 107
    4,//l - 108
    32,//m - 109
    6,//n - 110
    15,//o - 111
    29,//p - 112
    55,//q - 113
    11,//r - 114
    10,//s - 115
    12,//t - 116
    16,//u - 117
    37,//v - 118
    34,//w - 119
...
};  

以下函数用于填充 C 浮点数组,其方式与我在 python 模型中的方式相同:

float   *get_input_tensor(char *text)
{
    int     i;
    float   *result;
    size_t  tensor_size;
    char    *current;

    i = 0;
    current = text;
    tensor_size = sizeof(float) * 1 * 64 * 88;
    result = (float*)malloc(sizeof(float) * tensor_size);
    memset(result, 0, tensor_size);
    while (*current)
    {
        *(result + 88 * i + dictionary[(int)*current]) = 1.00f;
        current++;
        i++;
    }
    return (result);
}

最后,设置会话:

    int     ndims = 3;
    int64_t dims[] = {1, 64, 88};
    float   *data = get_input_tensor("test_string");
    int     ndata = sizeof(float) * 1 * 64 * 88;

    TF_Tensor   *float_tensor = TF_NewTensor(TF_FLOAT, dims, ndims, data, ndata, &NoOpDeallocator, 0);
    TF_SessionRun(Session, NULL, Input, InputValues, NumInputs, Output, OutputValues, NumOutputs, NULL, 0, NULL, Status);0);

运行程序总是给出以下输出:

[*] TF_NewTensor OK
[*] Starting session
[*] Session OK
[*] Result tensor: 0.999864
[*] Tensorflow Data memory cleared and freed

我在这里很迷茫。 所以这是我的问题:给定模型的输入张量形状,在将数据放入 TF_NewTensor 然后放入 TF_SessionRun 之前,应该如何在 C API 中格式化数据? 或者是否有我没有找到的在线文档?甚至是填充输入张量时的通用方法?

【问题讨论】:

    标签: c tensorflow c-api


    【解决方案1】:

    TF 的 API C 中的数据以行优先顺序存储。

    如果您有 3D 数据布局,例如 [dim1,dim2,dim3] (1/64/88),并且您想要访问 (d1,d2,d3) 项,您应该使用公式:

    item = d1 * dim2 * dim3 + d2 * dim3 + d3
    

    所以你可以编写如下辅助函数:

    float* AccessResult(float* result, 
        int x, 
        int dim1, // 1
        int y, 
        int dim2, // 64
        int z,
        int dim3)  // 88
    {
        float* item = result + x * dim2 * dim3 + y * dim3 + z;
        return item;
    }
    

    填写数组的代码可能是:

    for (int i = 0; i < 64; ++i) {
        for (int j = 0; j < 88; ++j) {
            float* res = AccessResult(result,0,1,i,64,j,88);
            *res = 1.0f;
        }
    }
    

    ij(调用AccessResult 时)应该替换为dictionary[..],但我无法推断应该替换哪个。

    【讨论】:

      猜你喜欢
      • 2020-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-06
      • 1970-01-01
      • 1970-01-01
      • 2017-12-16
      相关资源
      最近更新 更多