简体   繁体   English

Tensorflow.Keras 说输入与预期输入不同

[英]Tensorflow.Keras says that the input is different than the expected input

I am writing a simple CNN to classify different features of a cartoon face.我正在编写一个简单的 CNN 来对卡通人脸的不同特征进行分类。 I am using this dataset.我正在使用这个数据集。 When I try running my code, I get the following error:当我尝试运行我的代码时,出现以下错误:

Traceback (most recent call last):
  File "cartoonKerasPy.py", line 86, in <module>
    model.fit(x_train, y_train, batch_size=8, epochs=3)
  File "C:\Users\befbr\Anaconda3\envs\Cartoon AI\lib\site-packages\tensorflow\python\keras\engine\training.py", line 1536, in fit
    validation_split=validation_split)
  File "C:\Users\befbr\Anaconda3\envs\Cartoon AI\lib\site-packages\tensorflow\python\keras\engine\training.py", line 992, in _standardize_user_data
    class_weight, batch_size)
  File "C:\Users\befbr\Anaconda3\envs\Cartoon AI\lib\site-packages\tensorflow\python\keras\engine\training.py", line 1154, in _standardize_weights
    exception_prefix='target')
  File "C:\Users\befbr\Anaconda3\envs\Cartoon AI\lib\site-packages\tensorflow\python\keras\engine\training_utils.py", line 293, in standardize_input_data
    str(len(data)) + ' arrays: ' + str(data)[:200] + '...')
ValueError: Error when checking model target: the list of Numpy arrays that you are passing to your model is not the size the model expected. Expected to see 1 array(s), but instead got the following list of 160 arrays: [0, 0, 0, 1, 0, 1, 0, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0...

Here is my code:这是我的代码:

print("Importing Packages")
import os
import tensorflow as tf
from tensorflow import keras as k
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
import pandas as pd
from PIL import Image

def createModel():
    model = k.models.Sequential([
      k.layers.Conv3D(filters=64, kernel_size=2, padding='same', activation='relu', input_shape=(500,500, 4, 1)),
      k.layers.MaxPooling3D(pool_size=2),
      k.layers.Dropout(0.2),
      k.layers.Flatten(),
      k.layers.Dense(1000, activation='relu'),
      k.layers.Dense(1, activation='softmax')

    ])
    model.compile(optimizer='adam',
                  loss='sparse_categorical_crossentropy',
                  metrics=['accuracy'])
    return model

def getFile(dir, getEveryNthLine):
    allFiles = list(os.listdir(dir))
    # print(allFiles)
    fileNameList = []
    numOfFiles = len(allFiles)
    i = 0
    for fichier in allFiles:
        if(i % getEveryNthLine == 0):
                # print(fichier)
                if(fichier.endswith(".csv")):
                    fileNameList.append(dir + "/" + fichier[0:-4])
        i += 1
    return fileNameList

print("Creating Model")
model = createModel()

# print("Model Summary")
# model.summary()

print("\nLoad Files")
files = getFile("F:/cartoonset10k/", 100)
print("Loaded " + str(len(files)) + " file names")

print("Split Data Into Train And Test")
train, test = train_test_split(files, test_size=0.2)

x_train = []
y_train = []
x_test = []
y_test = []

def getLabels(filePath):
    df = []
    with open(filePath, "r") as file:
        for line in list(file):
            tempList = line.replace("\n", "").replace('"', "").replace(" ", "").split(",")
            df.append({
                "attr": tempList[0],
                "value":int(tempList[1]),
                "maxValue":int(tempList[2])
            })
    return df

for i in range(len(train)):

    x_train.append([list(Image.open(train[i] + ".png").getdata())])
    y_train.append(pd.DataFrame(getLabels(train[i] + ".csv"))["value"][1])

print("Finished Formating\n\n")

x_train = np.reshape(x_train, (len(train), 500, 500, 4, 1))

with tf.device('/gpu'):
    model.fit(x_train, y_train, batch_size=8, epochs=3)

Does anyone know what is causing it?有谁知道是什么原因造成的? I think the problem has to do with the input shape, but I could be very wrong.我认为问题与输入形状有关,但我可能是非常错误的。 Where can I find where the correct input shape should be?我在哪里可以找到正确的输入形状?

A few problems there my friend:我的朋友有几个问题:

First of all it is bad practice to have a kernal_size of even numbers, Instead i recommend something like (5, 5) since you image in considerably large首先,拥有偶数的 kernal_size 是不好的做法,相反,我建议使用 (5, 5) 之类的东西,因为您的图像相当大

Next, I think you should be using Conv2D instead of Conv3D接下来,我认为您应该使用 Conv2D 而不是 Conv3D

Also, your final layer should have a few outputs like 2, representing maybe something like 0 for that cartoon character and 1 for not that cartoon character.此外,你的最后一层应该有一些输出,比如 2,可能代表那个卡通人物的 0 和不是那个卡通人物的 1。

Finally, I keep getting a sense that your model will underfit and it is always good to overfit your model and combat it using strategies such as L1, L2 weight regularization or Droupout layers.最后,我一直觉得你的模型会欠拟合,过拟合你的模型并使用诸如 L1、L2 权重正则化或 Dropout 层之类的策略来对抗它总是好的。

Overall your model should be something like this, feel free to call me off if I am wrong as I am no expert in this as well :P :总的来说,您的模型应该是这样的,如果我错了,请随时给我打电话,因为我也不是这方面的专家:P:

def build_model():
    model = Sequential()

    model.add(Conv2D(64, (5, 5), input_shape=(500, 500, 4), activation="relu"))
    model.add(MaxPooling2D(pool_size=(2, 2))
    model.add(Droupout(0.2))

    model.add(Conv2D(128, (5, 5), activation="relu"))
    model.add(MaxPooling2D(pool_size=(2, 2))
    model.add(Droupout(0.2))

    model.add(Conv2D(256, (5, 5), activation="relu"))
    model.add(MaxPooling2D(pool_size=(2, 2))
    model.add(Droupout(0.2))

    model.add(Flatten())
    model.add(Dense(512, activation="relu"))
    model.add(Dropout(0.5))
    model.add(Dense(512, activation="relu"))
    model.add(Dropout(0.5))
    model.add(Dense(512, activation="relu"))
    model.add(Dropout(0.5))
    model.add(Dropout(2, activation="softmax"))

return model

I used a few import statements so that I don't have to type k.blah.blah etc. CNN model usually goes: conv -> maxpool -> dropout -> conv -> maxpool -> dropout .......... dropout -> Flatten -> Dense -> High Dropout rate -> Dense -> High Dropout rate -> ........... -> output我使用了一些导入语句,这样我就不必键入 k.blah.blah 等。CNN 模型通常是: conv -> maxpool -> dropout -> conv -> maxpool -> dropout ....... ... dropout -> Flatten -> Dense -> High Dropout rate -> Dense -> High Dropout rate -> ........... -> output

Hope this helps!希望这可以帮助! ciao再见

PS: You are only 13 years old and is able to code stuff like CNNs etc, I am really impressed, you have talents my friend. PS:你才 13 岁,可以编写 CNN 之类的东西,我真的很佩服,你有才华,我的朋友。 Keep up with the good work!继续做好工作! :) :)

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

相关问题 Tensorflow.keras:输入的形状是(),即使形状是(768、8) - Tensorflow.keras: Shape of input is (), EVEN THOUGH SHAPE IS (768, 8) 将输入输入到 tensorflow.keras model 的中间层 - Feed input to intermediate layer of tensorflow.keras model pycharm说它找不到tensorflow.keras,但是可以用 - pycharm says taht it cant find tensorflow.keras but it works 使用预训练的 BERT 嵌入作为 CNN 的输入,使用 tensorflow.keras 导致 ValueError - Using pre-trained BERT embeddings as input to CNN with tensorflow.keras results in ValueError Keras模型到tensorflow.keras - Keras model to tensorflow.keras tensorflow.keras model 具有多个不同形状的输入(错误) - tensorflow.keras model with multiple inputs with different shapes (Error) 如何将自定义数据生成器输入到 model.fit 中,它会生成 X,y 和一个额外的数组,到 tensorflow.keras Z20F4ZF011622Z Z20F4ZF35E630DAF39466 - How to input custom data generator into model.fit, which generates X,y and one additional array, into tensorflow.keras model? 没有名为“tensorflow.keras”的模块 - No module named 'tensorflow.keras' Tensorflow / Keras:模型的输出层期望的输入形状与其收到的形状不同 - Tensorflow/Keras: model's output layer expects different input shape than what it recieved tensorflow keras 输入尺寸 - tensorflow keras input dimensions
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM