tf.expand_dims和tf.squeeze函数

tf.expand_dims和tf.squeeze函数

 

个人分类: 机器学习

tf.expand_dims()

Function

tf.expand_dims(input, axis=None, name=None, dim=None)

Inserts a dimension of 1 into a tensor’s shape. 
在第axis位置增加一个维度

Given a tensor input, this operation inserts a dimension of 1 at the dimension index axis of input’s shape. The dimension index axis starts at zero; if you specify a negative number for axis it is counted backward from the end.

给定张量输入,此操作在输入形状的维度索引轴处插入1的尺寸。 尺寸索引轴从零开始; 如果您指定轴的负数,则从最后向后计数。

This operation is useful if you want to add a batch dimension to a single element. For example, if you have a single image of shape [height, width, channels], you can make it a batch of 1 image with expand_dims(image, 0), which will make the shape [1, height, width, channels].

如果要将批量维度添加到单个元素,则此操作非常有用。 例如,如果您有一个单一的形状[height,width,channels],您可以使用expand_dims(image,0)使其成为1个图像,这将使形状[1,高度,宽度,通道]。

For example:

 
  1. # 't' is a tensor of shape [2]

  2. shape(expand_dims(t, 0)) ==> [1, 2]

  3. shape(expand_dims(t, 1)) ==> [2, 1]

  4. shape(expand_dims(t, -1)) ==> [2, 1]

  5. # 't2' is a tensor of shape [2, 3, 5]

  6. shape(expand_dims(t2, 0)) ==> [1, 2, 3, 5]

  7. shape(expand_dims(t2, 2)) ==> [2, 3, 1, 5]

  8. shape(expand_dims(t2, 3)) ==> [2, 3, 5, 1]

Args:

input: A Tensor. 
axis: 0-D (scalar). Specifies the dimension index at which to expand the shape of input. 
name: The name of the output Tensor. 
dim: 0-D (scalar). Equivalent to axis, to be deprecated.

输入:张量。
轴:0-D(标量)。 指定扩大输入形状的维度索引。
名称:输出名称Tensor。
dim:0-D(标量)。 等同于轴,不推荐使用。

Returns:

A Tensor with the same data as input, but its shape has an additional dimension of size 1 added.

tf.squeeze()

Function

tf.squeeze(input, squeeze_dims=None, name=None)

Removes dimensions of size 1 from the shape of a tensor. 
从tensor中删除所有大小是1的维度

Given a tensor input, this operation returns a tensor of the same type with all dimensions of size 1 removed. If you don’t want to remove all size 1 dimensions, you can remove specific size 1 dimensions by specifying squeeze_dims. 

给定张量输入,此操作返回相同类型的张量,并删除所有尺寸为1的尺寸。 如果不想删除所有尺寸1尺寸,可以通过指定squeeze_dims来删除特定尺寸1尺寸。
如果不想删除所有大小是1的维度,可以通过squeeze_dims指定。

For example:

 
  1. # 't' is a tensor of shape [1, 2, 1, 3, 1, 1]

  2. shape(squeeze(t)) ==> [2, 3]

  3. Or, to remove specific size 1 dimensions:

  4.  
  5. # 't' is a tensor of shape [1, 2, 1, 3, 1, 1]

  6. shape(squeeze(t, [2, 4])) ==> [1, 2, 3, 1]

Args:

input: A Tensor. The input to squeeze. 
squeeze_dims: An optional list of ints. Defaults to []. If specified, only squeezes the dimensions listed. The dimension index starts at 0. It is an error to squeeze a dimension that is not 1. 
name: A name for the operation (optional).

输入:张量。 输入要挤压。
squeeze_dims:可选的ints列表。 默认为[]。 如果指定,只能挤压列出的尺寸。 维度索引从0开始。挤压不是1的维度是一个错误。
名称:操作的名称(可选)。

Returns:

A Tensor. Has the same type as input. Contains the same data as input, but has one or more dimensions of size 1 removed.

张量。 与输入的类型相同。 包含与输入相同的数据,但具有一个或多个删除尺寸1的维度。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
代码分析如下: ```python def cnn_model(features, target): # 对target进行one-hot编码 target = tf.one_hot(target, 15, 1, 0) # 对features中的词进行embedding,得到词向量 word_vectors = tf.contrib.layers.embed_sequence(features, vocab_size=n_words, embed_dim=EMBEDDING_SIZE, scope='words') # 在词向量上增加一个维度,用于卷积 word_vectors = tf.expand_dims(word_vectors, 3) with tf.variable_scope('CNN_Layer1'): # 添加卷积层 conv1 = tf.contrib.layers.convolution2d(word_vectors, N_FILTERS, FILTER_SHAPE1, padding='VALID') # 对卷积结果进行ReLU非线性变换 conv1 = tf.nn.relu(conv1) # 对卷积结果进行最大池化 pool1 = tf.nn.max_pool(conv1, ksize=[1, POOLING_WINDOW, 1, 1], strides=[1, POOLING_STRIDE, 1, 1], padding='SAME') # 对池化结果进行转置,以满足形状要求 pool1 = tf.transpose(pool1, [0, 1, 3, 2]) with tf.variable_scope('CNN_Layer2'): # 添加卷积层 conv2 = tf.contrib.layers.convolution2d(pool1, N_FILTERS, FILTER_SHAPE2, padding='VALID') # 对卷积结果进行ReLU非线性变换 conv2 = tf.nn.relu(conv2) # 对卷积结果进行最大池化 pool2 = tf.squeeze(tf.reduce_max(conv2, 1), squeeze_dims=[1]) # 将池化结果送入全连接层,输出最终的分类结果 logits = tf.contrib.layers.fully_connected(pool2, 15, activation_fn=None) loss = tf.losses.softmax_cross_entropy(target, logits) train_op = tf.contrib.layers.optimize_loss(loss, tf.contrib.framework.get_global_step(), optimizer='Adam', learning_rate=LEARNING_RATE) return ({ 'class': tf.argmax(logits, 1), 'prob': tf.nn.softmax(logits) }, loss, train_op) ``` 1. `tf.one_hot(target, 15, 1, 0)`:对target进行one-hot编码,将每个词转化为一个长度为15的向量,其中对应的位置为1,其余为0。 2. `tf.contrib.layers.embed_sequence(features, vocab_size=n_words, embed_dim=EMBEDDING_SIZE, scope='words')`:对features(即输入的词)进行embedding,将每个词转化为一个EMBEDDING_SIZE维的向量。 3. `tf.expand_dims(word_vectors, 3)`:在词向量上增加一个维度,用于卷积。 4. `tf.contrib.layers.convolution2d(word_vectors, N_FILTERS, FILTER_SHAPE1, padding='VALID')`:添加卷积层,使用N_FILTERS个大小为FILTER_SHAPE1的滤波器进行卷积操作。 5. `tf.nn.relu(conv1)`:对卷积结果进行ReLU非线性变换。 6. `tf.nn.max_pool(conv1, ksize=[1, POOLING_WINDOW, 1, 1], strides=[1, POOLING_STRIDE, 1, 1], padding='SAME')`:对卷积结果进行最大池化,使用大小为POOLING_WINDOW的池化窗口,步长为POOLING_STRIDE。 7. `tf.transpose(pool1, [0, 1, 3, 2])`:对池化结果进行转置,将第3维和第4维交换,以满足后续卷积层的输入要求。 8. `tf.contrib.layers.convolution2d(pool1, N_FILTERS, FILTER_SHAPE2, padding='VALID')`:添加卷积层,使用N_FILTERS个大小为FILTER_SHAPE2的滤波器进行卷积操作。 9. `tf.nn.relu(conv2)`:对卷积结果进行ReLU非线性变换。 10. `tf.squeeze(tf.reduce_max(conv2, 1), squeeze_dims=[1])`:对卷积结果进行最大池化,并去除不必要的维度。 11. `tf.contrib.layers.fully_connected(pool2, 15, activation_fn=None)`:将池化结果送入全连接层,输出最终的分类结果。 12. `tf.losses.softmax_cross_entropy(target, logits)`:计算损失函数,使用softmax交叉熵作为损失函数。 13. `tf.contrib.layers.optimize_loss(loss, tf.contrib.framework.get_global_step(), optimizer='Adam', learning_rate=LEARNING_RATE)`:使用Adam优化器最小化损失函数,更新模型参数。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值