Tensorflow_2 Tutorials TF2 入门-Tensor

这篇教程介绍了Tensorflow 2.0中张量的创建和操作,包括从numpy创建、从python类型创建、类型转换以及数学运算、张量运算。此外,还详细讲解了广播、expand_dims和tile等高级操作,帮助理解张量在不同维度上的变换和扩展。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

张量及其操作

Tensor的创建

  1. 从numpy创建
    import tensorflow as tf
    import numpy as np
    
    
    if __name__ == '__main__':
        x = np.ones([1, 2], dtype=np.float)
        X = tf.convert_to_tensor(x, dtype=tf.float32)
        print(X) # tf.Tensor([1. 1.], shape=(2,), dtype=float32)
    
  2. 从python内置类型创建
import tensorflow as tf
import numpy as np


if __name__ == '__main__':
    x = [5, 5]
    X = tf.convert_to_tensor(x, dtype=tf.float32)
    print(X) # tf.Tensor([5. 5.], shape=(2,), dtype=float32)
  1. 使用tensorflow创建
    import tensorflow as tf
    import numpy as np
    
    
    if __name__ == '__main__':
        m, n = 3, 5
        a = tf.constant([0.] * 5, dtype=tf.float32) # 创建自定义常量
        b = tf.zeros(5, dtype=tf.float32) # 创建全0常量, 全一常量ones(...), 单位矩阵eye...
        c = tf.Variable([0.] * 5, dtype=tf.float32)  # 创建变量 可求导!
        print(a, b , c, sep='\n')
    	"""
    		tf.Tensor([0. 0. 0. 0. 0.], shape=(5,), dtype=float32)
    		tf.Tensor([0. 0. 0. 0. 0.], shape=(5,), dtype=float32)
    		<tf.Variable 'Variable:0' shape=(5,) dtype=float32, numpy=array([0., 0., 0., 0., 0.], dtype=float32)>
    	"""
    
  2. 类型转换
    你还在为创建随机的变量而苦恼吗?你还在为类型不匹配而焦虑吗?赶快拨打电话12315投诉吧(打了你就输了)
a = tf.constant([0.] * 5, dtype=tf.float32)
b = tf.Variable(a)
print(tf.is_tensor(b), type(b), b.dtype)
'''
True <class 'tensorflow.python.ops.resource_variable_ops.ResourceVariable'> <dtype: 'float32'>
#1 Variable 也是tensorflow的张量类型
#2 tf.Variable 可以将常量转化为 ResourceVariable
#3 dtype 不重新指定与constant的类型一致
'''
b = tf.cast(b, tf.float64)
print(b.dtype)
'''
<dtype: 'float64'>
#1 类型必须是tf的类型
#2 cast的返回值是变化后的向量,传入的原始向量不会被改变!
'''

Tensor的操作

数学运算

import tensorflow as tf
import numpy as np

if __name__ == '__main__':
	# 运算
    a = tf.ones([5, 5])
    q = tf.matmul(a, a) # 矩阵乘法 @
    w = tf.multiply(a, a) # 按位乘法 *
    e = tf.add(a, a) # 按位加法 +
    r = tf.subtract(a, a) # 按位减法 -
    t = tf.divide(a, a) # 按位除法 /
    ## a // a # 取整除法
    print(q, w, e, r, t)
    # 自动广播
    a = tf.ones([5, 5])
    b = tf.ones([5, 1]) * 2 # [[2.],[2.],[2.],[2.],[2.]]
    q = tf.matmul(a, b)
    w = tf.multiply(a, b)
    e = tf.add(a, b)
    r = tf.subtract(a, b)
    t = tf.divide(a, b)
    print(q, w, e, r, t)
    # 函数运算
    a = tf.ones([1, 1])
    q = tf.exp(a)
    w = tf.math.log(a) # log_e
    e = tf.cos(a)
    r = tf.sinh(a)
    t = tf.asin(a)
    print(q, w, e, r, t)

张量运算

import tensorflow as tf
import numpy as np

if __name__ == '__main__':
    from tensorflow.keras.datasets.mnist import load_data

    (x_train, y_train), (x_test, y_test) = load_data()

    X = tf.constant(x_train) # 60000 * 28 * 28

    print(X.shape, X.ndim) # 输出形状和维度
    # (60000, 28, 28) 3
    # 分割数据
    X1 = tf.split(X, 2) # 将数据分割为k块
    X1[0] = tf.expand_dims(X1[0], axis=-1) # 在最后面加一个维度
    X1[1] = tf.expand_dims(X1[1], axis=-1) # 在最后面加一个维度
    Y = tf.concat(X1, 3) # 按第三维度合并
    print(Y.shape) # TensorShape([30000, 28, 28, 2])

    # 改变形状
    print(tf.reshape(Y, [30000, 784, 2]).shape)
    print(tf.reshape(Y, [30000, -1, 2]).shape)
    # (30000, 784, 2)
    # (30000, 784, 2) # -1 只能有一个!表示余下所有
    print(tf.reshape(Y, [30000, -1, 28]).shape)
    # (30000, 56, 28)
    # 还原形状
    print(tf.equal(tf.reshape(tf.reshape(Y, [30000, -1, 28]), [30000, 28, 28, 2]), Y))
    # 压缩维度为1的维度
    print(X1[0].shape)
    print(tf.squeeze(X1[0]).shape)
    # (30000, 28, 28, 1)
    # (30000, 28, 28)

broadcast&tile&expand_dims

broadcast 广播,把低位数据广播到高维
expand_dims 扩展维度,在指定位置增加一个维度
tile 复制某些维度

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值