如何使用 Tensorflow 为张量添加维度 [英] How to add dimension to a tensor using Tensorflow

查看:67
本文介绍了如何使用 Tensorflow 为张量添加维度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有方法 reformat,其中使用 numpy 我将 label(256,) 转换为 label(256,2) 形状.

I have method reformat in which using numpy I convert a label(256,) to label(256,2) shape.

现在我想对形状为 (256,) 的张量执行相同的操作

Now I want to do same operation on a Tensor with shape (256,)

我的代码看起来像这样 (num_labels=2) :--

My code looks like this (num_labels=2) :--

def reformat(dataset, labels):
  dataset = dataset.reshape((-1, image_size, image_size,num_channels)).astype(np.float32)
  labels = (np.arange(num_labels)==labels[:,None]).astype(np.float32)
  return dataset, labels

推荐答案

您可以使用 tf.expand_dims() 添加新维度.

You can use tf.expand_dims() to add a new dimension.

In [1]: import tensorflow as tf    
        x = tf.constant([3., 2.])
        tf.expand_dims(x, 1).shape

Out[1]: TensorShape([Dimension(2), Dimension(1)])

您也可以为此使用 tf.reshape(),但是建议您使用 expand_dims,因为如果可以满足新形状,这也会将一些值带到新维度.

You can also use tf.reshape() for this, but would recommend you to use expand_dims, as this will also carry some values to new dimension if new shape can be satisfied.

In [1]: tf.reshape(x, [2, 1])
Out[1]: TensorShape([Dimension(2), Dimension(1)])

这篇关于如何使用 Tensorflow 为张量添加维度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆