获取array和tensor的shape

list、array、tensor之间的转换

list转array:np.array(list)
numpy数组转tensor:t = tf.convert_to_tensor(array, tf.float32, name='t')或者t = tf.cast(array, tf.float32)
tensor转numpy数组:array = sess.run(tensor) 或者 array = tensor.eval()

如何获取shape

1、获取numpy数组形状使用:a_array.shape[0]
2、获取tensor形状使用:b_tensor.shape[0]或b_tensor.get_shape().as_list()

示例

import numpy as np
import tensorflow as tf

# numpy数组类型
print("==== numpy.ndarray ====")
a_array = np.array([[1,2,3],[4,5,6]])
print(type(a_array))   # <class 'numpy.ndarray'>
row,column = a_array.shape[0],a_array.shape[1]
print("The rows and columns of a_array is %d, %d" %(row,column))

# tensor 类型
print("==== tensorflow.python.framework.ops.Tensor ====")
b_tensor = tf.constant([[1,2,3],[4,5,6]])
print(type(b_tensor)) # <class 'tensorflow.python.framework.ops.Tensor'>
row,column = b_tensor.shape[0],b_tensor.shape[1]
print("The rows and columns of b_tensor is %d, %d" %(row,column))
row,column = b_tensor.get_shape().as_list()
print("The rows and columns of b_tensor is %d, %d" %(row,column))
posted @ 2020-08-17 09:26  笑着刻印在那一张泛黄  阅读(1102)  评论(0编辑  收藏  举报