『TensorFlow』pad图片

本文详细介绍了TensorFlow中tf.pad()函数的用法,包括如何通过paddings参数来指定不同维度上的填充数量,以及不同mode选项(如CONSTANT、REFLECT和SYMMETRIC)产生的效果。通过具体示例展示了如何使用tf.pad()函数进行张量的填充操作。

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

 tf.pad()文档如下,

pad(tensor, paddings, mode='CONSTANT', name=None, constant_values=0)
    Pads a tensor.
    
    This operation pads a `tensor` according to the `paddings` you specify.
    `paddings` is an integer tensor with shape `[n, 2]`, where n is the rank of
    `tensor`. For each dimension D of `input`, `paddings[D, 0]` indicates how
    many values to add before the contents of `tensor` in that dimension, and
    `paddings[D, 1]` indicates how many values to add after the contents of
    `tensor` in that dimension. If `mode` is "REFLECT" then both `paddings[D, 0]`
    and `paddings[D, 1]` must be no greater than `tensor.dim_size(D) - 1`. If
    `mode` is "SYMMETRIC" then both `paddings[D, 0]` and `paddings[D, 1]` must be
    no greater than `tensor.dim_size(D)`.
    
    The padded size of each dimension D of the output is:
    
    `paddings[D, 0] + tensor.dim_size(D) + paddings[D, 1]`

 实际使用注意,参数paddings元素数(rank)必须和输入维度一一对应,表示该维度前后填充的层数,文档示例验证如下,

import tensorflow as tf
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
sess = tf.Session(config=config)

t = tf.constant([[1, 2, 3], [4, 5, 6]])
paddings = tf.constant([[1, 1,], [2, 2]])
# 'constant_values' is 0.
# rank of 't' is 2.
res = tf.pad(t, paddings, "CONSTANT", constant_values=1)  # [[0, 0, 0, 0, 0, 0, 0],
                                                          #  [0, 0, 1, 2, 3, 0, 0],
                                                          #  [0, 0, 4, 5, 6, 0, 0],
                                                          #  [0, 0, 0, 0, 0, 0, 0]]


print(sess.run(res))

'''
tf.pad(t, paddings, "REFLECT")  # [[6, 5, 4, 5, 6, 5, 4],
                                #  [3, 2, 1, 2, 3, 2, 1],
                                #  [6, 5, 4, 5, 6, 5, 4],
                                #  [3, 2, 1, 2, 3, 2, 1]]

tf.pad(t, paddings, "SYMMETRIC")  # [[2, 1, 1, 2, 3, 3, 2],
                                  #  [2, 1, 1, 2, 3, 3, 2],
                                  #  [5, 4, 4, 5, 6, 6, 5],
                                  #  [5, 4, 4, 5, 6, 6, 5]]
'''

 

### TensorFlow 示例代码与演示教程 以下是关于 TensorFlow 的一些基础示例以及高级应用案例,涵盖了卷积神经网络(CNN)、循环神经网络(RNN)以及其他常见任务。 #### 1. TensorFlow 极简入门代码 以下是一个简单的 TensorFlow 运行实例,展示了如何定义张量并执行基本操作: ```python import tensorflow as tf # 创建两个常量张量 a = tf.constant(2) b = tf.constant(3) # 执行加法运算 c = a + b print(f"The result of adding {a.numpy()} and {b.numpy()} is {c.numpy()}") ``` 这段代码通过创建两个常量张量 `a` 和 `b` 并计算它们的和来展示 TensorFlow 的基本功能[^1]。 --- #### 2. 使用 TensorFlow 实现卷积神经网络(CNN) 下面是一段基于 TensorFlow 的 CNN 示例代码,用于图像分类任务。此代码假设输入数据为 MNIST 数据集中的手写数字图片。 ```python import tensorflow as tf from tensorflow.keras import layers, models # 加载MNIST数据集 mnist = tf.keras.datasets.mnist (x_train, y_train), (x_test, y_test) = mnist.load_data() x_train, x_test = x_train / 255.0, x_test / 255.0 # 归一化处理 # 将数据调整为适合CNN的形状 x_train = x_train[..., tf.newaxis] x_test = x_test[..., tf.newaxis] # 定义模型架构 model = models.Sequential([ layers.Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=(28, 28, 1)), layers.MaxPooling2D(pool_size=(2, 2)), layers.Flatten(), layers.Dense(128, activation='relu'), layers.Dense(10, activation='softmax') ]) # 编译模型 model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy']) # 训练模型 model.fit(x_train, y_train, epochs=5) # 测试模型性能 test_loss, test_acc = model.evaluate(x_test, y_test, verbose=2) print(f"\nTest accuracy: {test_acc}") ``` 上述代码实现了完整的 CNN 模型构建过程,包括加载数据、预处理、搭建模型结构、编译及训练等步骤[^3]。 --- #### 3. TensorFlow 中的膨胀卷积(Dilated Convolution) 如果需要实现多尺度上下文聚合的任务,则可以考虑使用膨胀卷积技术。以下是一个简单的例子: ```python import tensorflow as tf input_tensor = tf.random.normal([1, 64, 64, 3]) # 输入尺寸为 [batch, height, width, channels] dilated_conv_layer = tf.keras.layers.Conv2D( filters=64, kernel_size=3, strides=1, padding="same", dilation_rate=2, # 设置膨胀率 activation=tf.nn.relu ) output_tensor = dilated_conv_layer(input_tensor) print(output_tensor.shape) ``` 该代码片段展示了如何利用 `dilation_rate` 参数设置膨胀卷积的操作方法[^2]。 --- #### 4. 循环神经网络(RNN/LSTM)示例 对于序列建模任务,LSTM 是一种常用的 RNN 变体。以下是如何在 TensorFlow 中实现 LSTM 的简单示例: ```python import tensorflow as tf from tensorflow.keras.preprocessing.sequence import pad_sequences from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Embedding, LSTM, Dense # 假设我们有一个文本分类任务的数据集 vocab_size = 10000 max_length = 100 # 预处理后的输入数据 data = [[...], [...]] # 替换为实际数据 labels = [...] # 替换为实际标签 padded_data = pad_sequences(data, maxlen=max_length, truncating='post') # 构建模型 model = Sequential([ Embedding(vocab_size, 64), LSTM(64, return_sequences=False), Dense(1, activation='sigmoid') # 输出层激活函数取决于具体任务 ]) # 编译模型 model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) model.summary() # 训练模型 model.fit(padded_data, labels, epochs=10, batch_size=32) ``` 以上代码适用于二分类问题,可以根据需求修改最后一层的激活函数和损失函数。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值