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

如何遍历tensorflow.train.Example/Feature对象并转为列表或NumPy数组

将TensorFlow Feature转换为NumPy数组/Python列表

要把你的tf.train.Example对象转换成目标格式的列表或NumPy数组,核心是提取每个Feature的数值列表,再按位置配对组合:

步骤1:提取Feature的数值

每个tf.train.Feature对象的int64_list或float_list都有value属性,直接取出即可得到对应的Python列表:

# 从example中提取整数和浮点数的数值列表
int_values = example.features.feature['my_ints'].int64_list.value
float_values = example.features.feature['my_floats'].float_list.value

步骤2:配对组合成目标格式

用列表推导式结合zip函数,将两个列表按位置一一配对,生成你需要的嵌套列表:

# 生成目标格式的Python列表
target_list = [[int_val, float_val] for int_val, float_val in zip(int_values, float_values)]

步骤3:转换为NumPy数组(可选)

如果需要NumPy数组,直接用numpy.array()转换即可:

import numpy as np
target_np_array = np.array(target_list)

完整测试代码

把上述步骤整合到你的代码中,运行后就能得到预期结果:

import tensorflow as tf
import numpy as np

int_feature = tf.train.Feature(
    int64_list=tf.train.Int64List(value=[1, 2, 3, 4]))
float_feature = tf.train.Feature(
    float_list=tf.train.FloatList(value=[1., 2., 3., 4.]))

example = tf.train.Example(
    features=tf.train.Features(feature={
        'my_ints': int_feature,
        'my_floats': float_feature
    }))

# 提取数值
int_values = example.features.feature['my_ints'].int64_list.value
float_values = example.features.feature['my_floats'].float_list.value

# 生成目标列表
target_list = [[int_val, float_val] for int_val, float_val in zip(int_values, float_values)]
print(target_list)
# 输出:[[1, 1.0], [2, 2.0], [3, 3.0], [4, 4.0]]

# 转换为NumPy数组
target_np_array = np.array(target_list)
print(target_np_array)
# 输出:
# [[1. 1.]
#  [2. 2.]
#  [3. 3.]
#  [4. 4.]]

注意:如果两个Feature的数值长度不一致,zip会自动截断到较短的列表长度,需要确保两个Feature的元素数量匹配。

内容的提问来源于stack exchange,提问作者Zabir Al Nazi Nabil

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 11:30:55