c++ - 在 C++ 中运行经过训练的 tensorflow 模型

标签 c++ tensorflow

我已经使用 tensorflow 在 python 中训练了一个图像分类网络。训练好的模型保存为 .pb .现在,我想测试模型,我需要在 C++ 中完成。

我用过numpy在操作和处理数据方面。在训练阶段,图像作为 numpy 数组传入。图像被拉伸(stretch)为一维数组,并且类标签被添加到这个数组中。

我对在 C++ 中运行模型时如何传递图像数据感到困惑,其中 numpy对我不可用。我用 numpy操作和处理数据的操作。如果我必须在 C++ 中执行,我应该以什么格式传递数据。

以下是我如何训练和保存我的模型

def trainModel(data):
    global_step = tf.Variable(0, name='global_step', trainable=False)
    X, y,keep_prob = modelInputs((741, 620, 1),4)
    logits = cnnModel(X,keep_prob)
    cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=y), name="cost")
    optimizer = tf.train.AdamOptimizer(.0001, name='Adam').minimize(cost)
    prediction = tf.argmax(logits, 1, name="prediction")
    correct_pred = tf.equal(prediction, tf.argmax(y, 1), name="correct_pred")
    accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32), name='accuracy')
    with tf.Session() as sess:
        sess.run(tf.global_variables_initializer())
        saver = tf.train.Saver()
        batch_size = 30
        for e in range(11):
            batch_x, batch_y = data.next_batch(batch_size)
            batch_y = batch_y.astype('int32')
            x = np.reshape(batch_x, [batch_size, 741, 620, 1])
            labels = np.zeros(shape=(batch_size,4))
            labels[np.arange(len(labels)),batch_y]=1
            sess.run(optimizer, feed_dict={X: x, y: labels,keep_prob:0.5})
            global_step.assign(e).eval()
        saver.save(sess, './my_test_model',global_step=global_step)

*741x620 为图片尺寸

最佳答案

here 中可以找到在 C++ 中使用图形的说明。

这是一些使用图像作为输入的代码:

tensorflow::Tensor keep_prob = tensorflow::Tensor(tensorflow::DT_FLOAT, tensorflow::TensorShape());
keep_prob.scalar<float>()() = 1.0;

tensorflow::Tensor input_tensor(tensorflow::DT_FLOAT, tensorflow::TensorShape({1,height,width,depth}));
auto input_tensor_mapped = input_tensor.tensor<float, 4>();
const float * source_data = (float*) img.data;  // here img is an opencv image, but if it's just a float array this code is very easy to adapt
// copying the image data into the corresponding tensor
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;
            input_tensor_mapped(0, y, x, c) = *source_value;
        }
    }
}
std::vector<tensorflow::Tensor> finalOutput;

tensorflow::Status run_status = this->tf_session->Run({{InputName,input_tensor}, 
                                                       {dropoutPlaceHolderName, keep_prob}},
                                                      {OutputName},
                                                      {},
                                                      &finalOutput);

关于c++ - 在 C++ 中运行经过训练的 tensorflow 模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45027394/

相关文章:

c++ - 使用 boost::asio ssl 服务器减少每次连接的内存使用

c++ - Visual Studio 2005 链接器问题

c++ - 如何使 TCP 套接字与 SO_BINDTODEVICE 一起工作(针对路由表)

python - 使用 Keras,如何将 CuDNNLSTM 生成的权重加载到 LSTM 模型中?

python - 为什么使用 Keras 制作的恢复后的 TensorFlow 模型给出的预测为 0?

c++ - 使用 size_t 作为 "for loop"的限制器

c++ - 生成 GL_INVALID_VALUE 错误。无效的纹理尺寸。在 Cubemap 纹理上 427*240*6

python - 属性错误 : __enter__ from "with tf.Session as sess:"

tensorflow - 如何监控死亡的relus

python - 在 slim 的tensorflow和tf记录批处理中微调inceptionv3的问题