Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
185 views
in Technique[技术] by (71.8m points)

machine learning - Label Shape mismatch in Tensorflow

I am beginner at tensorflow. i want to build a simple model but i got this error. i think it's because labels but i don't know how to fix it. i bulid my dataset from directory files with tf.data.Dataset.

this is data set:

visit : https://i.stack.imgur.com/H2EQT.jpg

data

  • --------class1: [x.jpeg ...]
  • --------class2: [y.png ....]
  • .
  • .
  • .
  • --------class10: [z.jpg ...]
    data_dir = os.path.join(os.path.dirname('D:/Downloads/Image data set/'), 'raw-img')
    data_dir = pathlib.Path(data_dir)
    image_count = len(list(data_dir.glob('*/*.*')))

    list_ds = tf.data.Dataset.list_files(str(data_dir / '*/*'), shuffle=False)
    list_ds = list_ds.shuffle(image_count, reshuffle_each_iteration=False)

    train_size = int(image_count * 0.8)
    test_size = int(image_count * 0.1)
    val_size = int(image_count * 0.1)
    
    train_ds = list_ds.take(train_size)
    val_ds = list_ds.skip(train_size)
    test_ds = val_ds.skip(test_size)
    val_ds = val_ds.take(test_size)

    def parse_image(filename):
      parts = tf.strings.split(filename, os.sep)
      label = tf.cast(parts[-2] == class_names, tf.float32)
      label = tf.argmax(label)
    
      image = tf.io.read_file(filename)
      image = tf.image.decode_jpeg(image, channels=3)
      image = tf.image.convert_image_dtype(image, tf.float32)
      image = tf.reshape(image, [32, 150, 150, 3])
      return image, labels
    
    AUTOTUNE = tf.data.experimental.AUTOTUNE
    
    train_ds = train_ds.map(parse_image, num_parallel_calls=AUTOTUNE)
    val_ds = val_ds.map(parse_image, num_parallel_calls=AUTOTUNE)
    test_ds = test_ds.map(parse_image, num_parallel_calls=AUTOTUNE)
    
    model = tf.keras.Sequential([
        kr.layers.Conv2D(16, 3, activation='relu', input_shape=(150, 150 ,3)),
        kr.layers.MaxPooling2D(),
        kr.layers.Conv2D(32, 3, activation='relu'),
        kr.layers.MaxPooling2D(),
        kr.layers.Conv2D(64, 3, activation='relu'),
        kr.layers.MaxPooling2D(),
        kr.layers.Flatten(),
        kr.layers.Dense(128, activation='softmax'),
        kr.layers.Dense(10)
    ])
    
    model.compile(
      optimizer='adam',
      loss='sparse_categorical_crossentropy',
      metrics=['accuracy'])
    
    model.fit(
      train_ds,
      epochs=3
    )

error : this is error when i want to fit the model.

Train for 20943 steps
Epoch 1/3
    1/20943 [..............................] - ETA: 1:14:41
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-38-c408313d0649> in <module>
      1 model.fit(
      2   train_ds,
----> 3   epochs=3
      4 )

    
.
.
.
.

ValueError: Shape mismatch: The shape of labels (received (320,)) should equal the shape of logits except for the last dimension (received (32, 10)).
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

the problem solved by using batch size and step_per_epoch variables.

train_ds = train_ds.map(parse_image, num_parallel_calls=AUTOTUNE)
train_ds = train_ds.cache()
train_ds = train_ds.batch(BATCH_SIZE, drop_remainder=True).repeat()
train_ds = train_ds.prefetch(buffer_size=AUTOTUNE)

and train

history = model.fit(train_ds, steps_per_epoch = train_size // BATCH_SIZE,
        epochs = EPOCHS, batch_size = BATCH_SIZE,
        validation_data = val_ds, validation_steps = val_size // BATCH_SIZE)

and SOLVED.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...