Tensorflow : 将类名转换为类索引

我正在使用Tensorflow进行机器学习工作。

问题:

我无法弄清楚如何将类名转换为类索引。

示例:

预期映射:

Car  ---> 0Bike ---> 1Boat ---> 2

代码:

#!/usr/bin/env python3.6import tensorflow as tfnames = [    "Car",    "Bus",    "Boat"]_, class_name = tf.TextLineReader(skip_header_lines=1).read(    tf.train.string_input_producer(tf.gfile.Glob("input_file.csv")))# 我想知道是否可以这样做:#    print(sess.run(class_name)) --> "Car"#    class_index = f(class_name, names)#    print(sess.run(class_index)) --> 0

input_file.csv :

class_nameCarCarBoatBike...

回答:

最简单的方法是这样的:

class_index = tf.reduce_min(tf.where(tf.equal(names, class_name)))

请注意,当类在names中存在时,它工作得很好,但当类不存在时(如你的例子中的Bike),它会返回263 − 1。你可以通过移除tf.reduce_min来避免这种情况,但这样class_index将评估为数组,而不是标量。

完整的可运行代码:

names = ["Car", "Bus", "Boat"]_, class_name = tf.TextLineReader(skip_header_lines=1).read(    tf.train.string_input_producer(tf.gfile.Glob("input_file.csv")))class_index = tf.reduce_min(tf.where(tf.equal(names, class_name)))with tf.Session() as session:  coord = tf.train.Coordinator()  threads = tf.train.start_queue_runners(coord=coord)  for i in range(4):    print(class_name.eval())  # Car, Car, Boat, Bike  for i in range(4):    print(class_index.eval()) # 0, 0, 2, 9223372036854775807  coord.request_stop()  coord.join(threads)

Related Posts

L1-L2正则化的不同系数

我想对网络的权重同时应用L1和L2正则化。然而,我找不…

使用scikit-learn的无监督方法将列表分类成不同组别,有没有办法?

我有一系列实例,每个实例都有一份列表,代表它所遵循的不…

f1_score metric in lightgbm

我想使用自定义指标f1_score来训练一个lgb模型…

通过相关系数矩阵进行特征选择

我在测试不同的算法时,如逻辑回归、高斯朴素贝叶斯、随机…

可以将机器学习库用于流式输入和输出吗?

已关闭。此问题需要更加聚焦。目前不接受回答。 想要改进…

在TensorFlow中,queue.dequeue_up_to()方法的用途是什么?

我对这个方法感到非常困惑,特别是当我发现这个令人费解的…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注