tensorflow基础操作
- TensorFlow 使用 张量 (Tensor)作为数据的基本单位。TensorFlow 的张量在概念上等同于多维数组
导入tensorflowf模块
import tensorflow as tf - tf.zeros tf.ones
# 创建shape为(4,6)数值全为0的的tensor
zeros=tf.zeros([4,6])
print(zeros)
tf.Tensor(
[[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]], shape=(4, 6), dtype=float32)
# 创建shape为(2,3)数值全为1的的tensor
one=tf.ones([2,3])
print(one)
# 运行结果
tf.Tensor(
[[1. 1. 1.]
[1. 1. 1.]], shape=(2, 3), dtype=float32)
- tf.fill()
# 创建shape为(6,6)数值全为6的的tensor
data=tf.fill([4,6],6)
<tf.Tensor: id=8, shape=(4, 6), dtype=int32, numpy=
array([[6, 6, 6, 6, 6, 6],
[6, 6, 6, 6, 6, 6],
[6, 6, 6, 6, 6, 6],
[6, 6, 6, 6, 6, 6]])>
+创建随机张量
tf.random.normal()
从指定正态分布中随机取值,例如,元素服从均值为0,方差为1
#创建一个shape为(2,3)均值为0,方差为1服从正态分布的tensor
data=tf.random.normal([2, 3], mean=0, stddev=1)
#运行结果
<tf.Tensor: id=32, shape=(2, 3), dtype=float32, numpy=
array([[ 0.8916064 , -0.20759307, 0.28658876],
[ 1.1806337 , 1.70724 , -1.9630079 ]], dtype=float32)>
tf.random.uniform() 从指定均匀分布中随机取值
tf.random.uniform([6,2])
<tf.Tensor: id=39, shape=(6, 2), dtype=float32, numpy=
array([[0.74790776, 0.3966 ],
[0.66748595, 0.17139208],
[0.28174758, 0.83516634],
[0.49451137, 0.9332472 ],
[0.04716289, 0.7451469 ],
[0.02414787, 0.8701292 ]], dtype=float32)>
-
张量的类型转换
tf.strings.to_number(string_tensor, out_type=None, name=None)
tf.to_double(x, name=‘ToDouble’)
tf.to_float(x, name=‘ToFloat’)
tf.to_bfloat16(x, name=‘ToBFloat16’)
tf.to_int32(x, name=‘ToInt32’)
tf.to_int64(x, name=‘ToInt64’)
tf.cast(x, dtype, name=None)主要介绍下cast,tf.strings.to_number
+tf.cast(x, dtype, name=None)
x: 待转换的数据(张量)
dtype: 目标数据类型
x=tf.Variable([4,6])
<tf.Variable 'Variable:0' shape=(2,) dtype=int32, numpy=array([4, 6])>
tf.cast(x,tf.float32)
<tf.Tensor: id=50, shape=(2,), dtype=float32, numpy=array([4., 6.], dtype=float32)>
- tf.strings.to_number(string_tensor, out_type=None, name=None)
将输入张量中的每个字符串转换为指定的数值类型张量
tf.strings.to_number("1.55")
<tf.Tensor: id=53, shape=(), dtype=float32, numpy=1.55>
- constant() 创建常量的方法
创建一个整型张量
tf.constant(6)
创建一个浮点型张量
tf.constant(7.)
通过list参数创建
tf.constant([[1.,2.,],[4.,6.]])
# 返回结果
<tf.Tensor: id=55, shape=(2, 2), dtype=float32, numpy=
array([[1., 2.],
[4., 6.]], dtype=float32)>
- transpose() 转置
a = tf.constant([[1,8,3],[4,9,6]])
a.shape
TensorShape([2, 3])
c = tf.transpose(a)
c.shape
转置后的形状
TensorShape([3, 2])
- reshape
data = tf.ones([2,2,3])
data
<tf.Tensor: id=61, shape=(2, 2, 3), dtype=float32, numpy=
array([[[1., 1., 1.],
[1., 1., 1.]],
[[1., 1., 1.],
[1., 1., 1.]]], dtype=float32)>
data2 = tf.reshape(data, [3, 2, 2])
data2
<tf.Tensor: id=64, shape=(3, 2, 2), dtype=float32, numpy=
array([[[1., 1.],
[1., 1.]],
[[1., 1.],
[1., 1.]],
[[1., 1.],
[1., 1.]]], dtype=float32)>
同时也支持类似numpy的逻辑运算符,切片操作,这里不再一一介绍