TensorFlow2.0:数据的填充与复制

本文详细解析了TensorFlow中TF.pad填充函数和TF.tile数据复制函数的使用方法。通过实例展示了如何设置paddings参数在不同维度上进行前后填充,以及如何利用multiples参数在各个维度上复制数据。适合初学者理解和掌握这两个常用的数据处理函数。

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

**

一 tf.pad( )填充函数

**

tf.pad(tensor, paddings, mode="CONSTANT", name=None, constant_values=0): 

paddings参数的设置方法:

假设输入tensor有两个维度,则paddings参数设置为paddings = [[a,b],[c,d]]
a,b表示为axis=0维度上最前面填充a行,最后面填充b行,
c,d表示为axis=1维度上最前面填充c列,最后面填充d列,

同理,假设输入的tensor有三个维度,则paddings参数设置为paddings = [[a,b],[c,d],[e,f]]
a,b表示为axis=0维度上最前面填充a行,最后面填充b行,
c,d表示为axis=1维度上最前面填充c列,最后面填充d列,
e,f表示为axis=2维度上最前面填充e,最后面填充f,


In [3]: a                                                                       
Out[3]: <tf.Tensor: id=3, shape=(9,), dtype=int32, numpy=array([0, 1, 2, 3, 4, 5, 6, 7, 8], dtype=int32)>

In [4]: a = tf.reshape(a,[3,3])                                                 

In [5]: a                                                                       
Out[5]: 
<tf.Tensor: id=6, shape=(3, 3), dtype=int32, numpy=
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]], dtype=int32)>

In [6]: tf.pad(a,[[0,0],[0,0]])#不填充                                          
Out[6]: 
<tf.Tensor: id=9, shape=(3, 3), dtype=int32, numpy=
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]], dtype=int32)>

In [7]: tf.pad(a,[[1,0],[0,0]])#在axis=0上最前面填充1行,得到的维度应为[4,3]     
Out[7]: 
<tf.Tensor: id=12, shape=(4, 3), dtype=int32, numpy=
array([[0, 0, 0],
       [0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]], dtype=int32)>

In [8]: tf.pad(a,[[0,1],[0,0]])#在axis=0的最后面填充1行                         
Out[8]: 
<tf.Tensor: id=15, shape=(4, 3), dtype=int32, numpy=
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8],
       [0, 0, 0]], dtype=int32)>

In [9]: tf.pad(a,[[0,0],[1,0]])#在axis=1的最前面填充1列                         
Out[9]: 
<tf.Tensor: id=18, shape=(3, 4), dtype=int32, numpy=
array([[0, 0, 1, 2],
       [0, 3, 4, 5],
       [0, 6, 7, 8]], dtype=int32)>

In [10]: tf.pad(a,[[0,0],[0,1]])#在axis=1的最后面填充1列                        
Out[10]: 
<tf.Tensor: id=21, shape=(3, 4), dtype=int32, numpy=
array([[0, 1, 2, 0],
       [3, 4, 5, 0],
       [6, 7, 8, 0]], dtype=int32)>

In [11]: tf.pad(a,[[1,1],[0,0]])#在axis=0最前面和最后面分别填充                 
Out[11]: 
<tf.Tensor: id=24, shape=(5, 3), dtype=int32, numpy=
array([[0, 0, 0],
       [0, 1, 2],
       [3, 4, 5],
       [6, 7, 8],
       [0, 0, 0]], dtype=int32)>

In [12]: tf.pad(a,[[0,0],[1,1]])#在axis=1最前和最后各填充                       
Out[12]: 
<tf.Tensor: id=27, shape=(3, 5), dtype=int32, numpy=
array([[0, 0, 1, 2, 0],
       [0, 3, 4, 5, 0],
       [0, 6, 7, 8, 0]], dtype=int32)>

In [13]: tf.pad(a,[[1,1],[1,1]])#在axis=0和axis=1的最前和最后各进行填充         
Out[13]: 
<tf.Tensor: id=30, shape=(5, 5), dtype=int32, numpy=
array([[0, 0, 0, 0, 0],
       [0, 0, 1, 2, 0],
       [0, 3, 4, 5, 0],
       [0, 6, 7, 8, 0],
       [0, 0, 0, 0, 0]], dtype=int32)>

iamge padding

tf.pad(tensor, paddings, mode="CONSTANT", name=None, constant_values=0): 

In [19]: tf.pad(a,[[0,0],[2,2],[2,2],[2,2],[0,0]],constant_values=255).shape                                                                                                                                
Out[19]: TensorShape([4, 32, 32, 32, 3])

**

二 tf.tile( ) 数据复制函数

**

    tf.tile(  
        input,     #输入  
        multiples,  #某一维度上复制的次数  
        name=None  
    )

multiples参数设置方法:

假设输入Input有两个维度,则可以设置multiples = [a,b]
a表示在维度axis=0上复制a次,
b表示在维度axis=1上复制b次.

同理,假设Input有三个维度,则可以设置multiples = [a,b,c]
a表示在维度axis=0上复制a次,
b表示在维度axis=1上复制b次.
c表示在维度axis=2上复制c次,

In [2]: a = tf.range(9)               
                                                                                                                                                                      
In [3]: a                                                                                                                                                                                                   
Out[3]: <tf.Tensor: id=3, shape=(9,), dtype=int32, numpy=array([0, 1, 2, 3, 4, 5, 6, 7, 8], dtype=int32)>

In [4]: a = tf.reshape(a,[3,3])                                                                                                                                                                             

In [5]: a                                                                                                                                                                                                   
Out[5]: 
<tf.Tensor: id=6, shape=(3, 3), dtype=int32, numpy=
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]], dtype=int32)>

In [6]: tf.tile(a,[1,1])#表示不复制                                                                                                                                                                         
Out[6]: 
<tf.Tensor: id=9, shape=(3, 3), dtype=int32, numpy=
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]], dtype=int32)>

In [7]: tf.tile(a,[1,2])#在axis=1维度上复制2次                                                                                                                                                              
Out[7]: 
<tf.Tensor: id=12, shape=(3, 6), dtype=int32, numpy=
array([[0, 1, 2, 0, 1, 2],
       [3, 4, 5, 3, 4, 5],
       [6, 7, 8, 6, 7, 8]], dtype=int32)>

In [8]: tf.tile(a,[2,2])#在axis=0和axis=1维度上分别复制2,次,先复制小维度,再复制大维度                                                                                                                                                  
Out[8]: 
<tf.Tensor: id=15, shape=(6, 6), dtype=int32, numpy=
array([[0, 1, 2, 0, 1, 2],
       [3, 4, 5, 3, 4, 5],
       [6, 7, 8, 6, 7, 8],
       [0, 1, 2, 0, 1, 2],
       [3, 4, 5, 3, 4, 5],
       [6, 7, 8, 6, 7, 8]], dtype=int32)>

In [9]: tf.tile(a,[2,1])#在axis=0维度上复制2次                                                                                                                                                              
Out[9]: 
<tf.Tensor: id=18, shape=(6, 3), dtype=int32, numpy=
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8],
       [0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]], dtype=int32)>

tile VS broadcast_to
broadcast_to相当于先expand_dims,再tile

In [12]: a = tf.reshape(tf.range(9),[3,3])                                                                                                                                                                  

In [13]: a                                                                                                                                                                                                  
Out[13]: 
<tf.Tensor: id=28, shape=(3, 3), dtype=int32, numpy=
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]], dtype=int32)>

In [14]: aa = tf.expand_dims(a,axis=0)#先扩充维度                                                                                                                                                           

In [15]: aa                                                                                                                                                                                                 
Out[15]: 
<tf.Tensor: id=31, shape=(1, 3, 3), dtype=int32, numpy=
array([[[0, 1, 2],
        [3, 4, 5],
        [6, 7, 8]]], dtype=int32)>

In [16]: bb = tf.tile(aa,[2,1,1])                                                                                                                                                                           

In [17]: bb                                                                                                                                                                                                 
Out[17]: 
<tf.Tensor: id=34, shape=(2, 3, 3), dtype=int32, numpy=
array([[[0, 1, 2],
        [3, 4, 5],
        [6, 7, 8]],

       [[0, 1, 2],
        [3, 4, 5],
        [6, 7, 8]]], dtype=int32)>

In [18]: cc = tf.broadcast_to(a,[2,3,3])                                                                                                                                                                    

In [19]: cc                                                                                                                                                                                                 
Out[19]: 
<tf.Tensor: id=37, shape=(2, 3, 3), dtype=int32, numpy=
array([[[0, 1, 2],
        [3, 4, 5],
        [6, 7, 8]],

       [[0, 1, 2],
        [3, 4, 5],
        [6, 7, 8]]], dtype=int32)>

<think>嗯,用户问的是如何给Tensor数组赋初值。之前他们问过如何在Sionna中生成特定形状的数组,现在这个问题更具体了,是关于赋初值的。我需要回忆一下TensorFlow中的相关方法,以及Sionna是否有什么特别的函数。 首先,用户之前的问题是关于生成形状为[...,k]的数组,现在他们可能是在实际编程中遇到了需要初始化特定值的情况。可能他们需要不同的初始化方式,比如全零、全一、特定数值填充,或者随机初始化。不过,用户可能更关心的是除了这些基本方法之外,是否有其他高级的初始化技巧,或者如何在Sionna的上下文中应用这些方法。 接下来,我需要考虑TensorFlow中常用的初始化方法。比如,tf.zeros、tf.ones、tf.fill这些基本函数,还有各种随机分布如均匀分布、正态分布等。另外,用户可能还想知道如何根据已有张量的形状来动态初始化,比如继承前置维度,这在之前的回答中已经提到过动态shape的处理,这里可能需要再次强调。 另外,用户可能对初始化变量的方式不太清楚,比如使用tf.Variable还是直接操作张量。在Sionna中,大部分操作可能都是基于张量的,但变量初始化在某些情况下也是必要的,比如可训练参数。 还需要注意,用户可能对不同类型的初始值有需求,比如复数类型,这在通信库如Sionna中可能很常见。因此,可能需要提到如何初始化复数张量,比如使用tf.complex来组合实部和虚部。 此外,用户可能会遇到需要从已有数据(如NumPy数组)创建Tensor的情况,所以tf.convert_to_tensor方法也值得提及。同时,复制已有张量的形状但填充不同值的情况,比如用tf.zeros_like或tf.ones_like,但填充其他数值可能需要结合tf.fill或其他方法。 还有,用户可能对初始化的性能有要求,比如预分配内存或者使用TensorArray来处理动态shape的情况,这在之前的回答中也提到过,可能需要再次强调。 需要检查是否覆盖了所有常见的初始化场景,包括常量、随机值、序列、特殊矩阵(如单位矩阵)、从外部数据导入、继承形状等。同时,是否需要提到在模型训练中的参数初始化,比如使用Keras层的初始值设定项,这可能对更高级的用法有帮助。 在Sionna的上下文中,用户可能是在构建通信系统模型,比如信道编码、调制解调等模块,因此可能需要初始化信道系数、噪声参数、编码矩阵等。这时候正确的初始化方法对模型的行为和性能有直接影响,所以需要确保提供的方法既准确又实用。 最后,注意事项部分需要考虑数据类型的一致性、设备分配(如GPU)、形状推断以及Sionna特有的功能。比如,Sionna是否提供了某些便利函数来初始化张量,或者推荐的最佳实践是什么。 总结下来,回答需要结构清晰,分步骤讲解各种初始化方法,覆盖基本和高级用法,结合Sionna的应用场景举例,并提醒常见的注意事项和错误。需要确保示例代码正确,特别是动态shape的处理部分,避免用户在使用时出现错误。</think>在TensorFlow/Sionna中为张量赋初值,可以通过以下方法实现,涵盖常量填充、随机分布、继承形状等场景: --- ### **1. 基础常量初始化** #### **(1) 全零张量** ```python import tensorflow as tf x = tf.zeros(shape=[3,5]) # 创建3×5的全零矩阵 ``` #### **(2) 全一张量** ```python y = tf.ones(shape=[2,4,6]) # 创建2×4×6的全一三维张量 ``` #### **(3) 指定值填充** ```python z = tf.fill(dims=[2,3], value=3.14) # 创建2×3矩阵,所有元素为3.14 ``` --- ### **2. 随机分布初始化** #### **(1) 均匀分布** ```python # 区间[0,1)的均匀分布 rand_uniform = tf.random.uniform(shape=[4,4], minval=0.0, maxval=1.0) # 整数均匀分布(常用于生成比特序列) rand_int = tf.random.uniform(shape=[10], minval=0, maxval=2, dtype=tf.int32) ``` #### **(2) 正态分布** ```python # 标准正态分布(均值0, 方差1) rand_normal = tf.random.normal(shape=[3,3]) # 自定义参数的正态分布 custom_normal = tf.random.normal(shape=[5], mean=2.0, stddev=0.5) ``` #### **(3) 截断正态分布** ```python # 生成值在[μ-2σ, μ+2σ]范围内的正态分布 truncated = tf.random.truncated_normal(shape=[10,2], mean=0.0, stddev=0.1) ``` --- ### **3. 序列生成** #### **(1) 等差序列** ```python linspace = tf.linspace(start=0.0, stop=10.0, num=5) # 输出: [0.0, 2.5, 5.0, 7.5, 10.0] ``` #### **(2) 整数范围** ```python range_tensor = tf.range(start=3, limit=9, delta=2) # 输出: [3,5,7] ``` --- ### **4. 继承已有张量的形状** #### **(1) 复制形状并赋新值** ```python original = tf.constant([[1,2], [3,4]]) zeros_like = tf.zeros_like(original) # 创建original相同shape的全零张量 filled_like = tf.fill(original.shape, value=-1) # 显式继承形状 ``` #### **(2) 动态适配前置维度** ```python def create_compatible_tensor(ref_tensor, k): new_shape = tf.concat([tf.shape(ref_tensor)[:-1], [k]], axis=0) return tf.random.normal(shape=new_shape) input_tensor = tf.zeros([32, 64]) # shape=[32,64] output = create_compatible_tensor(input_tensor, 128) # 输出shape=[32,128] ``` --- ### **5. 特殊矩阵初始化** #### **(1) 单位矩阵** ```python identity = tf.eye(num_rows=3, num_columns=3) # 3×3单位矩阵 ``` #### **(2) 对角矩阵** ```python diag = tf.linalg.diag([1.0, 2.0, 3.0]) # 主对角线为1,2,3的3×3矩阵 ``` --- ### **6. 从外部数据导入** #### **(1) 从NumPy数组转换** ```python import numpy as np numpy_array = np.array([[1,2], [3,4]]) tensor_from_np = tf.convert_to_tensor(numpy_array) # dtype自动推断为int32 ``` #### **(2) 从Python列表创建** ```python list_data = [[0.1, 0.2], [0.3, 0.4]] tensor_from_list = tf.constant(list_data, dtype=tf.float32) ``` --- ### **7. 在Sionna中的典型应用** #### **(1) 生成QAM调制符号** ```python import sionna # 生成随机QAM符号(实部和虚部独立初始化) num_symbols = 1000 constellation = sionna.mapping.Constellation("qam", num_bits_per_symbol=4) symbols = constellation(tf.random.uniform(shape=[num_symbols], minval=0, maxval=2, dtype=tf.int32)) ``` #### **(2) 初始化信道系数** ```python # 生成瑞利衰落信道系数(复数高斯分布) num_tx = 4 num_rx = 2 h_real = tf.random.normal(shape=[num_tx, num_rx]) h_imag = tf.random.normal(shape=[num_tx, num_rx]) h = tf.complex(h_real, h_imag) # shape=[4,2]的复数张量 ``` --- ### **8. 高级技巧** #### **(1) 使用`tf.Variable`进行可训练初始化** ```python # 创建可训练参数(常用于神经网络权重) initializer = tf.keras.initializers.GlorotNormal() weights = tf.Variable( initial_value=initializer(shape=[128, 64]), trainable=True ) ``` #### **(2) 稀疏矩阵初始化** ```python indices = [[0,1], [1,0], [2,2]] values = [3.0, 6.0, 9.0] sparse_tensor = tf.sparse.SparseTensor( indices=indices, values=values, dense_shape=[3,3] ) ``` --- ### **注意事项** 1. **数据类型一致性**:通过`dtype`参数显式指定类型(如`tf.float32`) 2. **设备分配**:使用`with tf.device("/GPU:0")`控制张量存储位置 3. **形状推断**:动态shape操作时建议使用`tf.shape()`而非`tensor.shape` 4. **Sionna优化**:在信道建模等场景中优先使用`sionna.utils`中的工具函数 以上方法覆盖了从简单常量到复杂动态形状的初始化需求,可灵活应用于Sionna中的信道仿真、信号处理等任务。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值