简体   繁体   English

深度学习 Tensorflow 重塑不起作用?

[英]Deep Learning Tensorflow reshape is not working?

I try to get a prediction out of a trained model but i need to reshape it for tensorflow but it gives me this error all the time:我试图从训练有素的 model 中得到预测,但我需要为 tensorflow 重塑它,但它一直给我这个错误:

ValueError: in user code: ValueError:在用户代码中:

WARNING:tensorflow:Model was constructed with shape (None, 100, 100, 3) for input KerasTensor(type_spec=TensorSpec(shape=(None, 100, 100, 3), dtype=tf.float32, name='conv2d_input'), name='conv2d_input', description="created by layer 'conv2d_input'"), but it was called on an input with incompatible shape (None, 100, 100, 1).
Traceback (most recent call last):
  File "c:\Dev\PM_AI\partthree.py", line 16, in <module>
    prediction = model.predict([prepare("wurmbefall.jpg")])
  File "C:\Users\danie\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\keras\utils\traceback_utils.py", line 67, in error_handler
    raise e.with_traceback(filtered_tb) from None
  File "C:\Users\danie\AppData\Local\Temp\__autograph_generated_filenl1hl3g5.py", line 15, in tf__predict_function
    retval_ = ag__.converted_call(ag__.ld(step_function), (ag__.ld(self), ag__.ld(iterator)), None, fscope)
ValueError: in user code:

    File "C:\Users\danie\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\keras\engine\training.py", line 1845, in predict_function  *
        return step_function(self, iterator)
    File "C:\Users\danie\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\keras\engine\training.py", line 1834, in step_function  **
        outputs = model.distribute_strategy.run(run_step, args=(data,))
    File "C:\Users\danie\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\keras\engine\training.py", line 1823, in run_step  **
        outputs = model.predict_step(data)
    File "C:\Users\danie\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\keras\engine\training.py", line 1791, in predict_step
        return self(x, training=False)
    File "C:\Users\danie\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\keras\utils\traceback_utils.py", line 67, in error_handler
        raise e.with_traceback(filtered_tb) from None
    File "C:\Users\danie\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\keras\engine\input_spec.py", line 248, in assert_input_compatibility 
        raise ValueError(

    ValueError: Exception encountered when calling layer "sequential" (type Sequential).

    Input 0 of layer "conv2d" is incompatible with the layer: expected axis -1 of input shape to have value 3, but received input with shape (None, 100, 100, 1)

    Call arguments received by layer "sequential" (type Sequential):
      • inputs=('tf.Tensor(shape=(None, 100, 100, 1), dtype=uint8)',)
      • training=False
      • mask=None

MY Code: Part One我的代码:第一部分

import numpy as np
import matplotlib.pyplot as plt
import os
import random
import pickle
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout, Activation, Flatten, Conv2D, MaxPooling2D
from tqdm import tqdm

DATADIR = 'C:\Dev\PM_AI\FlowerImages'
CATEGORIES = ['Apfelschorf', 'Blattlaeuse', 'echterMehltau', 'falscherMehltau', 'Grauschimmel', 'KrautBraunFaeule', 'Raupen', 'Rostpilze']

training_data = []
def create_training_data():
    for category in CATEGORIES:
        path = os.path.join(DATADIR, category) #Path to images
        class_num = CATEGORIES.index(category)
        for img in tqdm(os.listdir(path)):
            try:
                img_array = cv2.imread(os.path.join(path,img))
                new_array = cv2.resize(img_array, (IMG_Size, IMG_Size))
                training_data.append([new_array, class_num])
            except Exception as e:
                pass

IMG_Size = 100

create_training_data()

print(len(training_data))

random.shuffle(training_data)

for sample in training_data[:10]:
    print(sample[1])

X = []
y = []

for features, label in training_data:
    X.append(features)
    y.append(label)

X = np.array(X).reshape(-1, IMG_Size, IMG_Size, 3)

pickle_out = open("X.pickle", "wb")
pickle.dump(X, pickle_out)
pickle_out.close()

pickle_out = open("y.pickle", "wb")
pickle.dump(y, pickle_out)
pickle_out.close()

Part Two:第二部分:

import tensorflow as tf
import numpy as np
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout, Activation, Flatten, Conv2D, MaxPooling2D
from tensorflow.keras.callbacks import TensorBoard

NAME = "PflanzenApp"

X = pickle.load(open("X.pickle", "rb"))
y = pickle.load(open("Y.pickle", "rb"))

y = np.array(y)
X = np.array(X)

X = X/255.0

model = Sequential()

model.add(Conv2D(64, (3,3), input_shape = X.shape[1:]))
model.add(Activation("relu"))
model.add(MaxPooling2D(pool_size=(2,2)))

model.add(Conv2D(64, (3,3)))
model.add(Activation("relu"))
model.add(MaxPooling2D(pool_size=(2,2)))

model.add(Flatten())
model.add(Dense(64))

model.add(Dense(1))
model.add(Activation('sigmoid'))

tensorboard = TensorBoard(log_dir="logs/{}".format(NAME))

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

model.fit(tf.expand_dims(X, axis=-1), y, batch_size=10, epochs=5, validation_split=0.1, callbacks=[tensorboard])

model.save('PflanzenApp.model')

Part Three:第三部分:

import tensorflow as tf
import numpy as np

CATEGORIES = ['Apfelschorf', 'Blattlaeuse', 'echterMehltau', 'falscherMehltau', 'Grauschimmel', 'KrautBraunFaeule', 'Raupen', 'Rostpilze']

def prepare(filepath):
    IMG_Size = 100
    img_array = cv2.imread(filepath)
    new_array = cv2.resize(img_array, (IMG_Size, IMG_Size))
    reshaped_array = np.array(new_array).reshape(-1, IMG_Size, IMG_Size, 1)
    return reshaped_array

model = tf.keras.models.load_model("PflanzenApp.model")

prediction = model.predict([prepare("wurmbefall.jpg")])

print(prediction)

The Error is in Part Three.错误在第三部分。 I already tried to find the error why it says shape (None, 100, 100,1) if the none is the error but i couldnt find anything.我已经尝试找到错误,为什么它说形状 (None, 100, 100,1) 如果没有错误但我找不到任何东西。 Has somebody an Idea?有人有想法吗?

As lejlot explains in the comments above, the model expects colour pictures not greyscale and thus [100,100,3] not [100,100,1] .正如 lejlot 在上面的评论中解释的那样, model 期望彩色图片不是灰度,因此[100,100,3]不是[100,100,1]

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

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