Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tensorflow : Transform class name to class index

I am working on machine learning stuff with tensorflow.

Problem :

I can't fingure out how to transform class name into class index.

Example :

Expected mapping :

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

Code :

#!/usr/bin/env python3.6

import tensorflow as tf

names = [
    "Car",
    "Bus",
    "Boat"
]

_, class_name = tf.TextLineReader(skip_header_lines=1).read(
    tf.train.string_input_producer(tf.gfile.Glob("input_file.csv"))
)

# I want to know if it is possible to do that :
#    print(sess.run(class_name)) --> "Car"
#    class_index = f(class_name, names)
#    print(sess.run(class_index)) --> 0

input_file.csv :

class_name
Car
Car
Boat
Bike
...
like image 416
Theophile Champion Avatar asked Jan 22 '26 00:01

Theophile Champion


1 Answers

The easiest way is this:

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

Note that it works fine, while the class is present in names, but returns 263 − 1, when it is not (like Bike in your example). You can avoid this effect but removing tf.reduce_min, but in this case class_index will evaluate to an array, not scalar.

Complete runnable code:

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)
like image 128
Maxim Avatar answered Jan 24 '26 16:01

Maxim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!