I am trying to extract from a tensor string "2018/12/31 22:59"
the values of year, month, day, hour and minute. I found this function tf.string_split
for this task, but my code is throwing an error
Traceback (most recent call last):
File "path/to/my/file.py", line 12, in <module>
date = split_date_time[0]
TypeError: 'SparseTensor' object does not support indexing
Here's the code
import tensorflow as tf
date_time = tf.placeholder(dtype=tf.string)
day = tf.placeholder(shape=[None], dtype=tf.int32),
month = tf.placeholder(shape=[None], dtype=tf.int32),
year = tf.placeholder(shape=[None], dtype=tf.int32),
hour = tf.placeholder(shape=[None], dtype=tf.int32),
minute = tf.placeholder(shape=[None], dtype=tf.int32)
split_date_time = tf.string_split(date_time, ' ')
date = split_date_time[0]
time = split_date_time[1]
date_splitted = tf.string_split(date, '-')
year = date_splitted[0]
month = date_splitted[1]
day = date_splitted[2]
time_spplitted = tf.string_split(time, ':')
hour = time_spplitted[0]
minute = time_spplitted[1]
with tf.Session() as sess:
print (sess.run(year, feed_dict={date_time: "2018-12-31 22:59"}))
print (sess.run(month, feed_dict={date_time: "2018-12-31 22:59"}))
print (sess.run(day, feed_dict={date_time: "2018-12-31 22:59"}))
print (sess.run(hour, feed_dict={date_time: "2018-12-31 22:59"}))
print (sess.run(minute, feed_dict={date_time: "2018-12-31 22:59"}))
You have several problems in your code (mainly because you apparently didn't read any documentation regarding the functions you're trying to use). I will just mention a few crucial problems related to the specific problem you're trying to solve (but I strongly encourage you to study the basics of TensorFlow and its computational model).
First, as the documentation of tf.string_split
states, the first argument of tf.string_split
should be a " 1-D string Tensor, the strings to split ". However, "2018-12-31 22:59"
is a 0-D string tensor.
Second, tf.string_split
returns a tf.SparseTensor
, which cannot be indexed!
Here's a possible solution to your problem:
import tensorflow as tf
date_time = tf.placeholder(shape=(1,), dtype=tf.string)
split_date_time = tf.string_split(date_time, ' ')
date = split_date_time.values[0]
time = split_date_time.values[1]
split_date = tf.string_split([date], '-')
split_time = tf.string_split([time], ':')
year = split_date.values[0]
month = split_date.values[1]
day = split_date.values[2]
hours = split_time.values[0]
minutes = split_time.values[1]
with tf.Session() as sess:
year, month, day, hours, minutes = sess.run([year, month, day, hours, minutes],
feed_dict={date_time: ["2018-12-31 22:59"]})
print("Year =", year)
print("Month =", month)
print("Day =", day)
print("Hours =", hours)
print("Minutes =", minutes)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.