如何将元组ndarray(tf.data.Dataset)转换为普通ndarray?

时间:2020-09-11 22:53:15

标签: python arrays tensorflow

我正在使用tensorflow2。使用我的数据(ndarray),我将训练数据转换为“ tf.data.Dataset”。现在,我想转换回ndarray。但是有一个问题。

toString

我能够使用下面的代码将其转换为ndarray,但这并不常见。

train_dataset
Out[37]: <TakeDataset shapes: ((2,), (1,)), types: (tf.float32, tf.float32)>
len(list(train_dataset))
Out[38]: 15000

由于它最初是具有两个分量的元组数组(一个元组是输入数组,另一个是输出(标量)),所以我只能提取输入数组,如

train_np = np.stack(list(train_dataset))
train_np
Out[39]: 
array([[<tf.Tensor: shape=(2,), dtype=float32, numpy=array([1.542    , 0.6432161], dtype=float32)>,
        <tf.Tensor: shape=(1,), dtype=float32, numpy=array([-0.03497663], dtype=float32)>],
       [<tf.Tensor: shape=(2,), dtype=float32, numpy=array([0.318     , 0.67839193], dtype=float32)>,
        <tf.Tensor: shape=(1,), dtype=float32, numpy=array([0.97045505], dtype=float32)>],
       [<tf.Tensor: shape=(2,), dtype=float32, numpy=array([1.018     , 0.68844223], dtype=float32)>,
        <tf.Tensor: shape=(1,), dtype=float32, numpy=array([-0.63200754], dtype=float32)>],
       ...,
       [<tf.Tensor: shape=(2,), dtype=float32, numpy=array([1.508    , 0.5025126], dtype=float32)>,
        <tf.Tensor: shape=(1,), dtype=float32, numpy=array([-0.9998253], dtype=float32)>],
       [<tf.Tensor: shape=(2,), dtype=float32, numpy=array([1.308   , 0.040201], dtype=float32)>,
        <tf.Tensor: shape=(1,), dtype=float32, numpy=array([0.14029166], dtype=float32)>],
       [<tf.Tensor: shape=(2,), dtype=float32, numpy=array([0.194     , 0.46733668], dtype=float32)>,
        <tf.Tensor: shape=(1,), dtype=float32, numpy=array([-0.05856743], dtype=float32)>]],
      dtype=object)

现在,这是一个问题。 “ input_np”数组中的每个元素都再次为ndarray。

input_np = train_np[:, 0]
input_np
Out[42]: 
array([<tf.Tensor: shape=(2,), dtype=float32, numpy=array([1.542    , 0.6432161], dtype=float32)>,
       <tf.Tensor: shape=(2,), dtype=float32, numpy=array([0.318     , 0.67839193], dtype=float32)>,
       <tf.Tensor: shape=(2,), dtype=float32, numpy=array([1.018     , 0.68844223], dtype=float32)>,
       ...,
       <tf.Tensor: shape=(2,), dtype=float32, numpy=array([1.508    , 0.5025126], dtype=float32)>,
       <tf.Tensor: shape=(2,), dtype=float32, numpy=array([1.308   , 0.040201], dtype=float32)>,
       <tf.Tensor: shape=(2,), dtype=float32, numpy=array([0.194     , 0.46733668], dtype=float32)>],
      dtype=object)

我尝试过'input_np [:] [0]'提取'第一列',这是输入中的两个功能之一。但不起作用。

将ndarray转换为tf.data.Dataset很容易,但反之则不然。 我只想为每个要绘制的组件制作一个普通的简单数组。

请给我一些提示吗? 谢谢

0 个答案:

没有答案