Tensorflow One-Hot 函式樣例(Python3)
阿新 • • 發佈:2019-02-07
Py3程式碼:
# one-hot 函式的樣例
import tensorflow as tf
label = tf.placeholder(tf.int32,[None])
# 直接把 輸入的序列進行One-Hot的結果
one_hot = tf.one_hot(label, 3, 1, 0)
# 進行轉置
one_hot_new = tf.transpose(one_hot, perm=[1,0])
one_hot_new = tf.cast(one_hot_new, tf.float32)
# one_hot_new[2] = one_hot_new[2] * 1.5
# 按照每兩維的大小進行拆分
one_hot_new_1 = tf.dynamic_partition(one_hot_new, [0, 0, 1], 2)[0]
one_hot_new_2 = tf.dynamic_partition(one_hot_new, [0, 0, 1], 2)[1]
# 拼接以上兩維得到原來的結果
one_hot_new = tf.concat([one_hot_new_1, one_hot_new_2], axis=0)
if __name__ == '__main__':
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
one_hot_out, one_hot_new_out, one_hot_new_1_out, one_hot_new_2_out = sess.run([one_hot, one_hot_new, one_hot_new_1, one_hot_new_2], feed_dict={label: [0 , 1, 1, 2, 2, 0, 0, 1, 2, 2, 0, 2]})
print("原始的One-hot結果:")
print(one_hot_out, end='\n\n')
print("以上的結果.T:")
print(one_hot_new_out, end='\n\n')
print("拆分(1,2)維:")
print(one_hot_new_1_out, end='\n\n')
print("拆分 (3)維:")
print(one_hot_new_2_out, end='\n\n' )
控制檯輸出:
原始的One-hot結果:
[[1 0 0]
[0 1 0]
[0 1 0]
[0 0 1]
[0 0 1]
[1 0 0]
[1 0 0]
[0 1 0]
[0 0 1]
[0 0 1]
[1 0 0]
[0 0 1]]以上的結果.T:
[[ 1. 0. 0. 0. 0. 1. 1. 0. 0. 0. 1. 0.]
[ 0. 1. 1. 0. 0. 0. 0. 1. 0. 0. 0. 0.]
[ 0. 0. 0. 1. 1. 0. 0. 0. 1. 1. 0. 1.]]拆分(1,2)維:
[[ 1. 0. 0. 0. 0. 1. 1. 0. 0. 0. 1. 0.]
[ 0. 1. 1. 0. 0. 0. 0. 1. 0. 0. 0. 0.]]拆分 (3)維:
[[ 0. 0. 0. 1. 1. 0. 0. 0. 1. 1. 0. 1.]]
附錄(一個奇葩的方法):
Py3:
import tensorflow as tf
labels = tf.placeholder(tf.float32)
labels_0 = 0.5 - labels
labels_0 = tf.nn.relu(labels_0) * 2
labels_1_t = labels - 1.5
labels_1_t = tf.nn.relu(labels_1_t) * 3
labels_1 = labels - 0.5
labels_1 = tf.nn.relu(labels_1)
labels_1 = labels_1 - labels_1_t
labels_1 = labels_1 * 2
labels_1 = tf.nn.relu(labels_1)
labels_2 = labels - 1.5
labels_2 = tf.nn.relu(labels_2)
labels_2 = labels_2 * 2
with tf.Session() as sess:
print(sess.run([labels_0, labels_1, labels_2], feed_dict={labels: [0, 1, 2, 2, 2, 0, 1, 2, 0]}))
控制檯:
[array([ 1., 0., 0., 0., 0., 1., 0., 0., 1.], dtype=float32), array([ 0., 1., 0., 0., 0., 0., 1., 0., 0.], dtype=float32), array([ 0., 0., 1., 1., 1., 0., 0., 1., 0.], dtype=float32)]