简体   繁体   English

形状与 Tensorflow 数据集和网络不匹配

[英]Shape mismatch with Tensorflow Dataset and Network

I am getting an error relating to shapes whilst defining a very simple network using Tensorflow 2.我在使用 Tensorflow 2 定义一个非常简单的网络时遇到与形状有关的错误。

My code is:我的代码是:

import tensorflow as tf
import pandas as pd

data = pd.read_csv('data.csv')

target = data.pop('result')
target = tf.keras.utils.to_categorical(target.values, num_classes=3)
data_set = tf.data.Dataset.from_tensor_slices((data.values, target))

model = tf.keras.Sequential([
    tf.keras.layers.Input(shape=data.shape[1:]),
    tf.keras.layers.Dense(12, activation='relu'),
    tf.keras.layers.Dense(3, activation='softmax')
])

model.compile(optimizer='adam', loss='categorical_crossentropy')
model.fit(data_set, epochs=5)

The call to fit() throws the following error:对 fit() 的调用会引发以下错误:

ValueError: Input 0 of layer sequential is incompatible with the layer: expected axis -1 of input shape to have value 12 but received input with shape [12, 1]

Walking through the code:遍历代码:

  1. The input CSV file has thirteen columns - with the last being the label输入 CSV 文件有 13 列 - 最后是 label
  2. This is converted to a 3 bit one-hot encoding这被转换为 3 位 one-hot 编码
  3. The Dataset is constructed of two Tensors - one of shape (12,) and the other of shape (3,)数据集由两个张量构成 - 一个形状为 (12,),另一个为形状 (3,)
  4. The network Input layer defines it's expected shape as be the value data shape ignoring the first axis which is the batch size网络输入层将其预期形状定义为值数据形状,忽略第一个轴,即批量大小

I am stumped about why there is mismatch between the shape of the data and the expected data shape for the network - especially as the latter is defined by reference to the former.我很困惑为什么数据的形状和网络的预期数据形状之间存在不匹配——尤其是后者是通过引用前者来定义的。

Add .batch() at the end of the dataset:在数据集末尾添加.batch()

data_set = tf.data.Dataset.from_tensor_slices((data.values, target)).batch(8)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM