Tensor数据类型 — 张量
-
应用:
在tensorflow程序中,所有数据都是通过 ‘ 张量 ’的形式来表示
-
创建Tensor:
-
(1)通过 list 创建tensor
import tensorflow as tf
import numpy as np
# 创建list
list = [1,2,3]
print(list)
# 将list转换未tensor
tf1 = tf.convert_to_tensor(list)
print(tf1)
>>> [1, 2, 3]
>>> tf.Tensor([1 2 3], shape=(3,), dtype=int32)
- (2)通过 numpy 创建tensor
import tensorflow as tf
import numpy as np
# 创建numpy数组
numpy = np.ones([2,3])
print(numpy)
# 将numpy转换为tensor
tf = tf.convert_to_tensor(numpy)
print(tf)
>>> [[1. 1. 1.]
[1. 1. 1.]]
>>> tf.Tensor(
[[1. 1. 1.]
[1. 1. 1.]], shape=(2, 3), dtype=float64)
- (3)通过 tf,constant 创建tensor
tf.constant(value, dtype=None, shape=None, name=‘Const’)
参数:
value: 第一个值value是必须的,可以是一个数值,也可以是一个列表。
dtype: 所要创建的tensor的数据类型
shape: 所要创建的tensor的shape
name: (可选)一个该操作的别名
import tensorflow as tf
x = tf.constant(3) # 0阶张量
print(x)
x1 = tf.constant([1,2,3]) # 1阶张量
print(x1)
x2 = tf.constant([[1,2,3],[4,5,6]]) # 2阶张量
print(x2)
x3 = tf.constant(2,shape=[2,3])
print(x3,'\n')
x4 = tf.constant([1,2,3,4,5,6],shape=[2,3])
print(x4,'\n')
x5 = tf.constant([1,2,3,4,5,6],shape=[2,3],dtype=tf.float64,name='张量')
print(x5,'\n')
>>> tf.Tensor(3, shape=(), dtype=int32)
>>> tf.Tensor([1 2 3], shape=(3,), dtype=int32)
>>> tf.Tensor(
[[1 2 3]
[4 5 6]], shape=(2, 3), dtype=int32)
>>> tf.Tensor(
[[2 2 2]
[2 2 2]], shape=(2, 3), dtype=int32)
>>> tf.Tensor(
[[1 2 3]
[4 5 6]], shape=(2, 3), dtype=int32)
>>> tf.Tensor(
[[1. 2. 3.]
[4. 5. 6.]], shape=(2, 3), dtype=float64)
- (4)通过 tf.zeros & tf.ones 创建tensor
tf.zeros(shape, dtype=tf.float32, name=None)
参数:
shape:用于表示维度,用[m,n]来表示
dtype: 所要创建的tensor对象的数据类型
name: (可选)一个该操作的别名.
import tensorflow as tf
x = tf.zeros([2])
print(x,'\n')
x1 = tf.zeros([2,3])
print(x1,'\n')
x2 = tf.zeros([2,3],dtype=tf.int32)
print(x2,'\n')
>>> tf.Tensor([0. 0.], shape=(2,), dtype=float32)
>>> tf.Tensor(
[[0. 0. 0.]
[0. 0. 0.]], shape=(2, 3), dtype=float32)
>>> tf.Tensor(
[[0 0 0]
[0 0 0]], shape=(2, 3), dtype=int32)
- (5)通过 tf.zeros_like & tf.ones_like创建tensor
tf.zeros_like(tensor, dtype=None, name=None)
参数:
tensor: tensor对象
dtype: 返回的tensor对象类型,不设置(为空时)时返回类型同参数tensor一致
name: (可选)该操作别名
import tensorflow as tf
a = tf.constant([[1,2,3],[4,5,6]])
print(a,'\n')
b = tf.zeros_like(a,dtype=tf.float64)
print(b)
>>> tf.Tensor(
[[1 2 3]
[4 5 6]], shape=(2, 3), dtype=int32)
>>> tf.Tensor(
[[0. 0. 0.]
[0. 0. 0.]], shape=(2, 3), dtype=float64)
- (5)通过 tf.fill 创建tensor
tf.fill(dims, value, name=None)
参数:
dims: 类型为int32的tensor对象,用于表示输出的维度(1-D, n-D),通常为一个int32数组,如:[1], [2,3]等
value: 常量值(字符串,数字等),该参数用于设置到最终返回的tensor对象值中
name: (可选)当前操作别名
import tensorflow as tf
import numpy as np
a = tf.fill([10], 0)
b = tf.fill([2, 3], 5)
print(a,'\n')
print(b)
>>> tf.Tensor([0 0 0 0 0 0 0 0 0 0], shape=(10,), dtype=int32)
>>> tf.Tensor(
[[5 5 5]
[5 5 5]], shape=(2, 3), dtype=int32)