【问题标题】:Problem with shapes of experimental Tensorflow dataset实验 TensorFlow 数据集的形状问题
【发布时间】:2021-05-18 10:45:04
【问题描述】:

我正在尝试将 numpy 数组存储在 Tensorflow 数据集中。该模型在使用 numpy 数组作为训练和测试数据时正确拟合,但在我将 numpy 数组存储在单个 Tensorflow 数据集中时不合适。问题在于数据集的维度。尽管形状乍一看似乎没问题,但还是有问题。

在尝试了多种方法来重塑我的 Tensorflow 数据集后,我仍然无法使其正常工作。我的代码如下:

train_x.shape 
Out[54]: (7200, 40)
train_y.shape
Out[55]: (7200,)
dataset = tf.data.Dataset.from_tensor_slices((x,y))
print(dataset)
Out[56]: <TensorSliceDataset shapes: ((40,), ()), types: (tf.int32, tf.int32)>
model.compile(optimizer=optimizer, loss='sparse_categorical_crossentropy')
history = model.fit(dataset, epochs=EPOCHS, batch_size=256)

    sparse_softmax_cross_entropy_with_logits
        logits.get_shape()))
    ValueError: Shape mismatch: The shape of labels (received (1,)) should equal the shape of logits except for the last dimension (received (40, 1351)).

我见过this answer,但我确信它不适用于这里。我必须使用 sparse_categorical_crossentropy。我从this example 启发了自己,我想将训练和测试数据存储在 Tensorflow 数据集中。我还想将数组存储在数据集中,因为稍后我将不得不使用它。

【问题讨论】:

    标签: numpy tensorflow dataset reshape


    【解决方案1】:

    在使用tf.data.Dataset 时,您不能将batch_sizemodel.fit() 一起使用。而是使用tf.data.Dataset.batch()。您必须按如下方式更改您的代码才能使其正常工作。

    import numpy as np
    import tensorflow as tf
    
    # Some toy data
    train_x = np.random.normal(size=(7200, 40))
    train_y = np.random.choice([0,1,2], size=(7200))
    
    dataset = tf.data.Dataset.from_tensor_slices((train_x,train_y))
    dataset = dataset.batch(256)
    
    #### - Define your model here - ####
    
    model.compile(optimizer=optimizer, loss='sparse_categorical_crossentropy')
    history = model.fit(dataset, epochs=EPOCHS)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-16
      • 2018-09-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多