You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TensorFlow C++:如何将二维数组转为feed_dict格式传入session.Run()

Alright, let's get your TensorFlow C++ matrix multiplication with placeholders up and running. The key piece you're missing is converting your 2D arrays into proper tensorflow::Tensor objects and feeding them into the session correctly. Here's a step-by-step breakdown plus a complete, runnable example:

Core Concept: Feed Dictionaries in TensorFlow C++

In C++, the feed dictionary is just an std::unordered_map<std::string, tensorflow::Tensor>. Each entry maps the name of a placeholder tensor to a concrete tensorflow::Tensor that holds your data. So the main task is converting your 2D array into a properly shaped Tensor.

Step 1: Helper Function to Convert 2D Arrays to Tensor

First, let's write a simple helper function that takes a 2D std::vector<float> (you can adapt this for other types like double or int) and turns it into a tensorflow::Tensor. This handles shaping the tensor and copying your data into its internal buffer:

#include <tensorflow/core/framework/tensor.h>
#include <vector>

tensorflow::Tensor convert_2d_vector_to_tensor(const std::vector<std::vector<float>>& input_array) {
    // Get dimensions of the input array
    int num_rows = input_array.size();
    int num_cols = input_array[0].size();

    // Create a tensor with the correct shape and data type
    tensorflow::Tensor tensor(tensorflow::DT_FLOAT, tensorflow::TensorShape({num_rows, num_cols}));

    // Get a pointer to the tensor's data buffer
    auto tensor_data_ptr = tensor.flat<float>().data();

    // Copy values from the 2D vector into the tensor
    int index = 0;
    for (const auto& row : input_array) {
        for (float value : row) {
            tensor_data_ptr[index++] = value;
        }
    }

    return tensor;
}
Step 2: Complete Runnable Matrix Multiplication Example

Now let's put this together with a full example that defines placeholders, sets up the matrix multiplication graph, feeds in your 2D arrays, and runs the session:

#include <tensorflow/core/public/session.h>
#include <tensorflow/core/framework/op.h>
#include <tensorflow/core/framework/shape_inference.h>
#include <iostream>

// Include the helper function from Step 1 here
tensorflow::Tensor convert_2d_vector_to_tensor(const std::vector<std::vector<float>>& input_array) {
    int num_rows = input_array.size();
    int num_cols = input_array[0].size();
    tensorflow::Tensor tensor(tensorflow::DT_FLOAT, tensorflow::TensorShape({num_rows, num_cols}));
    auto tensor_data_ptr = tensor.flat<float>().data();
    int index = 0;
    for (const auto& row : input_array) {
        for (float value : row) {
            tensor_data_ptr[index++] = value;
        }
    }
    return tensor;
}

int main() {
    // 1. Create a TensorFlow session
    tensorflow::Session* session;
    tensorflow::Status status = tensorflow::NewSession(tensorflow::SessionOptions(), &session);
    if (!status.ok()) {
        std::cerr << "Session creation failed: " << status.ToString() << std::endl;
        return 1;
    }

    // 2. Define placeholders for our matrices (dynamic shape: -1 means any size)
    auto placeholder_a = tensorflow::Placeholder(tensorflow::DT_FLOAT, tensorflow::TensorShape({-1, -1}));
    auto placeholder_b = tensorflow::Placeholder(tensorflow::DT_FLOAT, tensorflow::TensorShape({-1, -1}));

    // 3. Define the matrix multiplication operation
    auto mat_mul_result = tensorflow::MatMul(
        placeholder_a, 
        placeholder_b, 
        tensorflow::MatMulOptions().TransposeA(false).TransposeB(false)
    );

    // 4. Build the graph (add the operation to the session's graph)
    tensorflow::GraphDef graph_def;
    status = session->Create(graph_def);
    if (!status.ok()) {
        std::cerr << "Graph creation failed: " << status.ToString() << std::endl;
        session->Close();
        return 1;
    }

    // 5. Prepare your 2D array data
    std::vector<std::vector<float>> matrix_a = {{1.0f, 2.0f, 3.0f}, {4.0f, 5.0f, 6.0f}}; // 2x3 matrix
    std::vector<std::vector<float>> matrix_b = {{7.0f, 8.0f}, {9.0f, 10.0f}, {11.0f, 12.0f}}; // 3x2 matrix

    // 6. Convert arrays to tensors and build the feed dictionary
    std::unordered_map<std::string, tensorflow::Tensor> feed_dict;
    feed_dict[placeholder_a.name()] = convert_2d_vector_to_tensor(matrix_a);
    feed_dict[placeholder_b.name()] = convert_2d_vector_to_tensor(matrix_b);

    // 7. Run the session to compute the matrix multiplication
    std::vector<tensorflow::Tensor> outputs;
    status = session->Run(feed_dict, {mat_mul_result.name()}, {}, &outputs);
    if (!status.ok()) {
        std::cerr << "Session run failed: " << status.ToString() << std::endl;
        session->Close();
        return 1;
    }

    // 8. Extract and print the result
    const tensorflow::Tensor& result_tensor = outputs[0];
    auto result_flat = result_tensor.flat<float>();
    int result_rows = result_tensor.dim_size(0);
    int result_cols = result_tensor.dim_size(1);

    std::cout << "Matrix Multiplication Result:\n";
    for (int i = 0; i < result_rows; ++i) {
        for (int j = 0; j < result_cols; ++j) {
            std::cout << result_flat(i * result_cols + j) << " ";
        }
        std::cout << "\n";
    }

    // 9. Clean up the session
    session->Close();
    delete session;

    return 0;
}
Key Notes to Avoid Issues
  • Shape Matching: Make sure your input matrices are compatible for multiplication (columns of first matrix == rows of second matrix).
  • Data Type Consistency: If your placeholder uses DT_DOUBLE, adjust the helper function to use double instead of float.
  • Dynamic Shapes: Using -1 in the placeholder shape lets you feed matrices of different sizes without redefining the graph.
  • Error Checking: Always check the tensorflow::Status objects after session creation, graph building, and running—this will help you catch issues like shape mismatches or invalid data.

内容的提问来源于stack exchange,提问作者cps

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 08:14:12