簡體   English   中英

不適合 model lenet

[英]fail to fit model lenet

我想使用 Le-Net 將圖片訓練為實時人臉識別,但出現此錯誤。 我不知道如何解決這個問題。 before I decide to create this model because I can't use facet it to old can't load model then I decide to create this model and get an error, the label encode will be [0,0] [0,1] if有 2 個 output

錯誤:

PS C:\work\ฝึกงาน\deeplearn> & C:/Users/godja/AppData/Local/Programs/Python/Python39/python.exe c:/work/ฝึกงาน/deeplearn/prepareDataToTrain.py
2021-06-01 17:03:49.441501: I tensorflow/stream_executor/platform/default/dso_loader.cc:53] Successfully opened dynamic library cudart64_110.dll
X= (40, 32, 32)
Y= (40, 2)
2021-06-01 17:03:52.093770: I tensorflow/stream_executor/platform/default/dso_loader.cc:53] Successfully opened dynamic library nvcuda.dll
2021-06-01 17:03:52.137676: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1733] Found device 0 with properties: 
pciBusID: 0000:01:00.0 name: NVIDIA GeForce GTX 960M computeCapability: 5.0
coreClock: 1.176GHz coreCount: 5 deviceMemorySize: 2.00GiB deviceMemoryBandwidth: 74.65GiB/s
2021-06-01 17:03:52.138496: I tensorflow/stream_executor/platform/default/dso_loader.cc:53] Successfully opened dynamic library cudart64_110.dll
2021-06-01 17:03:52.154010: I tensorflow/stream_executor/platform/default/dso_loader.cc:53] Successfully opened dynamic library cublas64_11.dll
2021-06-01 17:03:52.154428: I tensorflow/stream_executor/platform/default/dso_loader.cc:53] Successfully opened dynamic library cublasLt64_11.dll
2021-06-01 17:03:52.160773: I tensorflow/stream_executor/platform/default/dso_loader.cc:53] Successfully opened dynamic library cufft64_10.dll
2021-06-01 17:03:52.163106: I tensorflow/stream_executor/platform/default/dso_loader.cc:53] Successfully opened dynamic library curand64_10.dll
2021-06-01 17:03:52.169121: I tensorflow/stream_executor/platform/default/dso_loader.cc:53] Successfully opened dynamic library cusolver64_11.dll
2021-06-01 17:03:52.176610: I tensorflow/stream_executor/platform/default/dso_loader.cc:53] Successfully opened dynamic library cusparse64_11.dll
2021-06-01 17:03:52.178368: W tensorflow/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'cudnn64_8.dll'; dlerror: cudnn64_8.dll not found
2021-06-01 17:03:52.178665: W tensorflow/core/common_runtime/gpu/gpu_device.cc:1766] Cannot dlopen some GPU libraries. Please make sure the missing libraries mentioned above are installed properly if you would like to use GPU. Follow the guide at https://www.tensorflow.org/install/gpu for how to download and setup the required libraries for your platform.
Skipping registering GPU devices...
2021-06-01 17:03:52.180226: I tensorflow/core/platform/cpu_feature_guard.cc:142] This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN) to use the following CPU instructions in performance-critical operations:  AVX AVX2
To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags.
2021-06-01 17:03:52.181740: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1258] Device interconnect StreamExecutor with strength 1 edge matrix:
2021-06-01 17:03:52.182046: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1264]
Model: "sequential"
_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
conv2d (Conv2D)              (None, 28, 28, 6)         156
_________________________________________________________________
max_pooling2d (MaxPooling2D) (None, 14, 14, 6)         0
_________________________________________________________________
conv2d_1 (Conv2D)            (None, 10, 10, 16)        2416
_________________________________________________________________
max_pooling2d_1 (MaxPooling2 (None, 5, 5, 16)          0
_________________________________________________________________
flatten (Flatten)            (None, 400)               0
_________________________________________________________________
dense (Dense)                (None, 400)               160400
_________________________________________________________________
dense_1 (Dense)              (None, 120)               48120
_________________________________________________________________
dense_2 (Dense)              (None, 84)                10164
_________________________________________________________________
dense_3 (Dense)              (None, 2)                 170
=================================================================
Total params: 221,426
Trainable params: 221,426
Non-trainable params: 0
_________________________________________________________________
2021-06-01 17:03:52.933912: I tensorflow/compiler/mlir/mlir_graph_optimization_pass.cc:176] None of the MLIR Optimization Passes are enabled (registered 2)
Epoch 1/100
Traceback (most recent call last):
  File "c:\work\ฝึกงาน\deeplearn\prepareDataToTrain.py", line 64, in <module>
    history = lenet5.fit(x_train , y_train , validation_split=0.1 , epochs = 100)
  File "C:\Users\godja\AppData\Roaming\Python\Python39\site-packages\tensorflow\python\keras\engine\training.py", line 1183, in fit
    tmp_logs = self.train_function(iterator)
  File "C:\Users\godja\AppData\Roaming\Python\Python39\site-packages\tensorflow\python\eager\def_function.py", line 889, in __call__
    result = self._call(*args, **kwds)
  File "C:\Users\godja\AppData\Roaming\Python\Python39\site-packages\tensorflow\python\eager\def_function.py", line 933, in _call
    self._initialize(args, kwds, add_initializers_to=initializers)
  File "C:\Users\godja\AppData\Roaming\Python\Python39\site-packages\tensorflow\python\eager\def_function.py", line 763, in _initialize
    self._stateful_fn._get_concrete_function_internal_garbage_collected(  # pylint: disable=protected-access
  File "C:\Users\godja\AppData\Roaming\Python\Python39\site-packages\tensorflow\python\eager\function.py", line 3050, in _get_concrete_function_internal_garbage_collected
    graph_function, _ = self._maybe_define_function(args, kwargs)
  File "C:\Users\godja\AppData\Roaming\Python\Python39\site-packages\tensorflow\python\eager\function.py", line 3444, in _maybe_define_function
    graph_function = self._create_graph_function(args, kwargs)
  File "C:\Users\godja\AppData\Roaming\Python\Python39\site-packages\tensorflow\python\eager\function.py", line 3279, in _create_graph_function
    func_graph_module.func_graph_from_py_func(
  File "C:\Users\godja\AppData\Roaming\Python\Python39\site-packages\tensorflow\python\framework\func_graph.py", line 999, in func_graph_from_py_func
    func_outputs = python_func(*func_args, **func_kwargs)
  File "C:\Users\godja\AppData\Roaming\Python\Python39\site-packages\tensorflow\python\eager\def_function.py", line 672, in wrapped_fn
    out = weak_wrapped_fn().__wrapped__(*args, **kwds)
  File "C:\Users\godja\AppData\Roaming\Python\Python39\site-packages\tensorflow\python\framework\func_graph.py", line 986, in wrapper
    raise e.ag_error_metadata.to_exception(e)
ValueError: in user code:

    C:\Users\godja\AppData\Roaming\Python\Python39\site-packages\tensorflow\python\keras\engine\training.py:855 train_function  *
        return step_function(self, iterator)
    C:\Users\godja\AppData\Roaming\Python\Python39\site-packages\tensorflow\python\keras\engine\training.py:845 step_function  **
        outputs = model.distribute_strategy.run(run_step, args=(data,))
    C:\Users\godja\AppData\Roaming\Python\Python39\site-packages\tensorflow\python\distribute\distribute_lib.py:1285 run
        return self._extended.call_for_each_replica(fn, args=args, kwargs=kwargs)
    C:\Users\godja\AppData\Roaming\Python\Python39\site-packages\tensorflow\python\distribute\distribute_lib.py:2833 call_for_each_replica
        return self._call_for_each_replica(fn, args, kwargs)
    C:\Users\godja\AppData\Roaming\Python\Python39\site-packages\tensorflow\python\distribute\distribute_lib.py:3608 _call_for_each_replica
        return fn(*args, **kwargs)
    C:\Users\godja\AppData\Roaming\Python\Python39\site-packages\tensorflow\python\keras\engine\training.py:838 run_step  **
        outputs = model.train_step(data)
    C:\Users\godja\AppData\Roaming\Python\Python39\site-packages\tensorflow\python\keras\engine\training.py:795 train_step
        y_pred = self(x, training=True)
    C:\Users\godja\AppData\Roaming\Python\Python39\site-packages\tensorflow\python\keras\engine\base_layer.py:1013 __call__
        input_spec.assert_input_compatibility(self.input_spec, inputs, self.name)
    C:\Users\godja\AppData\Roaming\Python\Python39\site-packages\tensorflow\python\keras\engine\input_spec.py:230 assert_input_compatibility
        raise ValueError('Input ' + str(input_index) + ' of layer ' +

    ValueError: Input 0 of layer sequential is incompatible with the layer: : expected min_ndim=4, found ndim=3. Full shape received: (None, 32, 32)

這是我的代碼:

import os
import cv2
from sys import path
from tqdm import tqdm
import numpy as np 
from sklearn.preprocessing import LabelEncoder
from tensorflow.keras.utils import to_categorical
from sklearn.model_selection import train_test_split



data=[]
path_data = "Data"
def prepare_data():
    #encode label
    person_name=os.listdir(path_data)
    enc=LabelEncoder()
    label_encode=enc.fit_transform(person_name)
    label_encode=to_categorical(label_encode)
    # print(person_name)
    # print(label)
    #trainform img to array


    x=[]
    y=[]
    for index,name in enumerate(person_name):
        img_name=os.listdir(os.path.join(path_data,name))
        for each_img in img_name:
            path_img=os.path.join(path_data,os.path.join(name,each_img))
            img_array=cv2.imread(path_img,cv2.IMREAD_GRAYSCALE)
            img_array=cv2.resize(img_array,(32,32))
            # data.append([np.array(img_array),label_encode[index]])
            x.append(img_array)
            y.append(label_encode[index])
        
    return x,y,person_name,label_encode
x,y,person_name,label_encode,=prepare_data()
x=np.array(x)
y=np.array(y)
print("X= "+str(x.shape))
print("Y= "+str(y.shape))
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=42)
# print(x_train.shape)
# print(y_test.shape)
#####Create Model#####
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense , MaxPool2D , Flatten  , Conv2D
lenet5=Sequential()
lenet5.add(Conv2D(6, (5,5) , activation='relu' , input_shape=(32,32,1)))
lenet5.add(MaxPool2D(pool_size=(2,2)))
lenet5.add(Conv2D(16, (5,5), activation='relu'))
lenet5.add(MaxPool2D(pool_size=(2,2)))
lenet5.add(Flatten())
lenet5.add(Dense(400,activation = 'relu' ))
lenet5.add(Dense(120, activation = 'relu' ))
lenet5.add(Dense(84, activation = 'relu' ))
lenet5.add(Dense(2 , activation = 'softmax'))
lenet5.compile(loss = 'categorical_crossentropy' , metrics = ['accuracy'] , optimizer = "Adam")
lenet5.summary()

# Train
import matplotlib.pyplot as plt
history = lenet5.fit(x_train , y_train , validation_split=0.1 , epochs = 100)





plt.plot(history.history['loss'])
plt.title('Food Model loss')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.show()

tf.keras.layers.Conv2D 期望輸入形狀:4+D 張量,形狀: batch_shape + (channels, rows, cols)如果 data_format='channels_first' 或 4+D 張量,形狀: batch_shape + (rows, cols, channels)如果 data_format='channels_last'。

為您的數據集添加額外的維度,如下面的代碼片段。

x_train, x_test = x_train.reshape(-1,32,32,1), x_test.reshape(-1,32,32,1)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM