准备Tensorflow
Tensor表示张量;Numpy只能在CPU中计算;Tensor可以在GPU和TPU中计算。
在Tensorflow2版本中,所有张量都可以调用numpy的方法
import tensorflow as tf
import numpy as np
print("Tensorflow version:", tf.__version__)
Tensorflow version: 2.3.0
print("Eger execution is:", tf.executing_eagerly())
Eger execution is: True
使用 tf.constant(value, dtype, shape)
函数创建张量, value表示数字、Python列表或numpy数组
参数为Python列表
a = tf.constant([[1,2], [3,4]])
print(a)
tf.Tensor(
[[1 2]
[3 4]], shape=(2, 2), dtype=int32)
a.numpy()
array([[1, 2],
[3, 4]])
type(a)
tensorflow.python.framework.ops.EagerTensor
参数为数字
b = tf.constant(1)
print(b)
tf.Tensor(1, shape=(), dtype=int32)
参数为Numpy数组
tf.constant(np.array([1,2]))
<tf.Tensor: shape=(2,), dtype=int32, numpy=array([1, 2])>
tf.constant(np.array([1,2]), dtype=tf.float32)
<tf.Tensor: shape=(2,), dtype=float32, numpy=array([1., 2.], dtype=float32)>
通过is_tensor()
函数判断对象是否为Tensor
tf.is_tensor(a)
True
类似于Numpy,在TensorFlow中也可以创建特殊张量
创建全0张量和全1张量
tf.zeros(shape, dtype=tf.float32
tf.ones(shape, dtype=tf.float32
tf.ones(shape=(2,1))
<tf.Tensor: shape=(2, 1), dtype=float32, numpy=
array([[1.],
[1.]], dtype=float32)>
tf.zeros(shape=(2,3))
<tf.Tensor: shape=(2, 3), dtype=float32, numpy=
array([[0., 0., 0.],
[0., 0., 0.]], dtype=float32)>
创建元素值都相同的张量
tf.fill(dims, value)
tf.constant(value, shape)
tf.fill([2,3],9)
<tf.Tensor: shape=(2, 3), dtype=int32, numpy=
array([[9, 9, 9],
[9, 9, 9]])>
tf.constant(value=9, shape=(2,3)) #需要显示调用参数
<tf.Tensor: shape=(2, 3), dtype=int32, numpy=
array([[9, 9, 9],
[9, 9, 9]])>
创建随机数张量——正态分布
tf.random.normal(shape, mean, stddev, dtype)
tf.random.shuffle()
根据数组的第一维,打乱数据
tf.random.normal([2,3])
<tf.Tensor: shape=(2, 3), dtype=float32, numpy=
array([[ 0.47237134, -0.7897855 , -1.3904623 ],
[-0.8305992 , -0.03698471, 0.09299516]], dtype=float32)>
tf.random.set_seed()
创建序列
tf.range(start, end, step)
tf.range(10)
<tf.Tensor: shape=(10,), dtype=int32, numpy=array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])>
tf.range(1,11,2) #创建奇数张量
<tf.Tensor: shape=(5,), dtype=int32, numpy=array([1, 3, 5, 7, 9])>
Tensor对象的属性——ndim、shape、dtype
a = tf.constant([[1,2],[3,4]])
print('ndim:', a.ndim)
print('dtype:', a.dtype)
print('shape:', a.shape)
ndim: 2
dtype: <dtype: 'int32'>
shape: (2, 2)
通过 reshape(tensor, shape)
改变tensor的形状
shape参数中如果为-1,表示该维度不知道,由Python自行推测
a = range(24)
b = tf.reshape(a, [2,3,4])
print(b)
tf.Tensor(
[[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
[[12 13 14 15]
[16 17 18 19]
[20 21 22 23]]], shape=(2, 3, 4), dtype=int32)
# 首先生成一个np数组,再转换为tensor对象
tf.constant(np.arange(24).reshape(2,3,4))
<tf.Tensor: shape=(2, 3, 4), dtype=int32, numpy=
array([[[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]],
[[12, 13, 14, 15],
[16, 17, 18, 19],
[20, 21, 22, 23]]])>
通过 tf.transpose(a, perm)
交换Tensor的维度,对于二维张量,等价于转置操作
通过perm参数调整轴的顺序
a = range(6)
b = tf.reshape(a, [2,3])
print(b)
tf.Tensor(
[[0 1 2]
[3 4 5]], shape=(2, 3), dtype=int32)
tf.transpose(b)
<tf.Tensor: shape=(3, 2), dtype=int32, numpy=
array([[0, 3],
[1, 4],
[2, 5]])>