Tensorflow tf.dynamic_partition 矩阵拆分(Py3)
March 17, 2018, 11:39 a.m.
read: 1106
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, 1, 1], 2)[0]
one_hot_new_2 = tf.dynamic_partition(one_hot_new, [1, 0, 1], 2)[0]
one_hot_new_3 = tf.dynamic_partition(one_hot_new, [1, 1, 0], 2)[0]
# 按照每一维大小进行拆分
one_hot_1 = tf.dynamic_partition(one_hot_new, [0, 1, 2], 3)[0]
one_hot_2 = tf.dynamic_partition(one_hot_new, [0, 1, 2], 3)[1]
one_hot_3 = tf.dynamic_partition(one_hot_new, [0, 1, 2], 3)[2]
# one_hot_new_3 = tf.dynamic_partition(one_hot_new, [0, 0, 1], 2)[2]
# 拼接以上两维得到原来的结果
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, one_hot_new_3_out, one_hot_1_out, one_hot_2_out, one_hot_3_out = sess.run([one_hot, one_hot_new, one_hot_new_1, one_hot_new_2, one_hot_new_3, one_hot_1, one_hot_2, one_hot_3], 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("方法一拆分:")
print(one_hot_new_out, end='\n\n')
print("拆分(1)维:")
print(one_hot_new_1_out, end='\n\n')
print("拆分 (2)维:")
print(one_hot_new_2_out, end='\n\n')
print("拆分 (3)维:")
print(one_hot_new_3_out, end='\n\n')
print("方法二拆分:")
print("拆分(1)维:")
print(one_hot_1_out, end='\n\n')
print("拆分 (2)维:")
print(one_hot_2_out, end='\n\n')
print("拆分 (3)维:")
print(one_hot_3_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.]]拆分(1)维:
[[ 1. 0. 0. 0. 0. 1. 1. 0. 0. 0. 1. 0.]]拆分 (2)维:
[[ 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.]]方法二拆分:
拆分(1)维:
[[ 1. 0. 0. 0. 0. 1. 1. 0. 0. 0. 1. 0.]]拆分 (2)维:
[[ 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.]]