TensorFlow 张量变换
原文链接:https://www.w3cschool.cn/tensorflow_python/tensorflow_python-85v22c69.html
import tensorflow as tf
tf.enable_eager_execution()
# tf.string_to_number
str_tensor = tf.constant(["2.2", "1.8"])
flt32_tesnor = tf.string_to_number(str_tensor, out_type=tf.float32)
print(flt32_tesnor) # tf.Tensor([2.2 1.8], shape=(2,), dtype=float32)
# tf.to_double
db_tensor = tf.to_double(flt32_tesnor)
print(db_tensor) # tf.Tensor([2.20000005 1.79999995], shape=(2,), dtype=float64)
# tf.cast
int32_tensor = tf.cast(db_tensor, tf.int32)
print(int32_tensor) # tf.Tensor([2 1], shape=(2,), dtype=int32)
# TensorFlow 张量形状的确定与改变
# tf.broadcast_dynamic_shape
tensor_x = tf.ones(shape=[1, 2, 3], dtype=tf.int32)
tensor_y = tf.ones(shape=[5, 1, 3], dtype=tf.int32)
shape_z = tf.broadcast_dynamic_shape(tensor_x.shape, tensor_y.shape)
print(shape_z) # tf.Tensor([5 2 3], shape=(3,), dtype=int32)
# tf.broadcast_dynamic_shape
shape_w = tf.broadcast_static_shape(tensor_x.shape, tensor_y.shape)
print(shape_w) # (5, 2, 3)
# tf.shape
t = tf.constant([[[1, 1, 1], [2, 2, 2]], [[3, 3, 3], [4, 4, 4]]])
print(tf.shape(t)) # tf.Tensor([2 2 3], shape=(3,), dtype=int32)
# tf.shape_n
print(tf.shape_n(t)) # (1)[ <tf.Tensor: id=31, shape=(2,), dtype=int32, numpy=array([2, 3], dtype=int32)>,
# (2) <tf.Tensor: id=32, shape=(2,), dtype=int32, numpy=array([2, 3], dtype=int32)>]
# 形状是:(2) [2, 3]
# tf.size
print(tf.size(t)) # tf.Tensor(12, shape=(), dtype=int32)
# tf.rank, 相当于np.ndim
# 张量的秩, 比如shape是[2,2,3],则秩(维度)为3
print(tf.rank(t)) # tf.Tensor(3, shape=(), dtype=int32)
# t的shape是[2, 2, 3]
print(tf.reshape(t, [4, 3]))
"""
tf.Tensor(
[[1 1 1]
[2 2 2]
[3 3 3]
[4 4 4]], shape=(4, 3), dtype=int32)
"""
print(tf.reshape(t, [-1])) # [-1] can be used to flatten 't'
"""
tf.Tensor([1 1 1 2 2 2 3 3 3 4 4 4], shape=(12,), dtype=int32)
"""
print(tf.reshape(t, [3, -1])) # -1 can be used to infer the shape
"""
tf.Tensor(
[[1 1 1 2]
[2 2 3 3]
[3 4 4 4]], shape=(3, 4), dtype=int32)
"""
print(tf.reshape(tf.constant([[[7]]]), [])) # shape `[]` reshapes to a scalar
"""
tf.Tensor(7, shape=(), dtype=int32)
"""
# tf.squeeze, 从张量的形状移除尺寸1的尺寸。
# 't' is a tensor of shape [1, 2, 1, 3, 1, 1]
tf.shape(tf.squeeze(t)) # [2, 3]
# 't' is a tensor of shape [1, 2, 1, 3, 1, 1]
tf.shape(tf.squeeze(t, [2, 4])) # [1, 2, 3, 1]
# 't' is a tensor of shape [2]
tf.shape(tf.expand_dims(t, 0)) # ==> [1, 2]
tf.shape(tf.expand_dims(t, 1)) # ==> [2, 1]
tf.shape(tf.expand_dims(t, -1)) # ==> [2, 1]
# 't' is a tensor of shape [2, 3, 5]
tf.shape(tf.expand_dims(t, 0)) # ==> [1, 2, 3, 5]
tf.shape(tf.expand_dims(t, 2)) # ==> [2, 3, 1, 5]
tf.shape(tf.expand_dims(t, 3)) # ==> [2, 3, 5, 1]
"""
tf.tile(
input,
multiples,
name=None
)
"""
找我内推: 字节跳动各种岗位
作者:
ZH奶酪(张贺)
邮箱:
cheesezh@qq.com
出处:
http://www.cnblogs.com/CheeseZH/
*
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。