Tensorflow.python.framework.errors\u impl.InvalidArgumentError:重塑的输入是一个具有790272个值的张量

2024-09-27 19:18:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着训练我的形象。此数据的大小为50000张图像

我的图像属性是:

enter image description here

如果我要改变我的图像属性,我该怎么做

这是我的第一个图像分类器工作,所以可能会有很多错误。请理解

你能帮我改进代码吗

这是我的代码:

import os
import zipfile
import tensorflow as tf
from tensorflow.keras.preprocessing.image import ImageDataGenerator,img_to_array,load_img
from glob import glob


config = tf.compat.v1.ConfigProto(gpu_options =
                         tf.compat.v1.GPUOptions(per_process_gpu_memory_fraction=0.8)
# device_count = {'GPU': 1}
)
config.gpu_options.allow_growth = True
session = tf.compat.v1.Session(config=config)
tf.compat.v1.keras.backend.set_session(session)


duzgun = os.path.join('fruits-360/Training/Duzgun')

print('total training düzgün images:', len(os.listdir(duzgun)))
yamuk = os.path.join('fruits-360/Training/Yamuk')
print('total training yamuk images:', len(os.listdir(yamuk)))

duzgun_files = os.listdir(duzgun)
print(duzgun_files[:10])

yamuk_files = os.listdir(yamuk)
print(yamuk_files[:10])

import matplotlib.pyplot as plt
import matplotlib.image as mpimg

pic_index = 2

next_duzgun = [os.path.join(duzgun, fname)
                for fname in duzgun_files[pic_index-2:pic_index]]
next_yamuk = [os.path.join(yamuk, fname)
                for fname in yamuk_files[pic_index-2:pic_index]]



for i, img_path in enumerate(next_duzgun+next_yamuk):
  #print(img_path)
  img = mpimg.imread(img_path)
  plt.imshow(img)
  plt.axis('Off')
  plt.show()

  import tensorflow as tf
  import keras_preprocessing
  from keras_preprocessing import image
  from keras_preprocessing.image import ImageDataGenerator

  TRAINING_DIR = "fruits-360/Training/"
  VALIDATION_DIR = "fruits-360/Test/"
  img = load_img(TRAINING_DIR + "Duzgun/cem.jpg")
  plt.imshow(img)
  plt.axis("off")
  plt.show()
  #TRAINING_DIR = "fruits-360/Training"

  training_datagen = ImageDataGenerator(
    rescale=1. / 255,
    rotation_range=40,
    width_shift_range=0.2,
    height_shift_range=0.2,
    shear_range=0.2,
    zoom_range=0.2,
    horizontal_flip=True,
    fill_mode='nearest')

 # VALIDATION_DIR = "fruits-360/Testing"
  validation_datagen = ImageDataGenerator(rescale=1. / 255)

  train_generator = training_datagen.flow_from_directory(
    TRAINING_DIR,
    target_size=(150, 150),
    class_mode='categorical',
    batch_size=126
  )

  validation_generator = validation_datagen.flow_from_directory(
    VALIDATION_DIR,
    target_size=(150, 150),
    class_mode='categorical',
    batch_size=126
  )
  x = img_to_array(img)
  print(x.shape)
  className = glob(TRAINING_DIR + "/*")
  print(className)
  numberOfClass = len(className)
  print("NumberOfClass:", numberOfClass)

  model = tf.keras.models.Sequential([
    # Note the input shape is the desired size of the image 150x150 with 3 bytes color
    # This is the first convolution
    tf.keras.layers.Conv2D(64, (3, 3), activation='relu',input_shape=x.shape ),
    tf.keras.layers.MaxPooling2D(2, 2),
    # The second convolution
    tf.keras.layers.Conv2D(64, (3, 3), activation='relu'),
    tf.keras.layers.MaxPooling2D(2, 2),
    # The third convolution
    tf.keras.layers.Conv2D(128, (3, 3), activation='relu'),
    tf.keras.layers.MaxPooling2D(2, 2),
    # The fourth convolution
    tf.keras.layers.Conv2D(128, (3, 3), activation='relu'),
    tf.keras.layers.MaxPooling2D(2, 2),
    # Flatten the results to feed into a DNN
    tf.keras.layers.Flatten(),
    tf.keras.layers.Dropout(0.5),
    # 512 neuron hidden layer
    tf.keras.layers.Dense(512, activation='relu'),
    tf.keras.layers.Dense(3, activation='softmax')
  ])


  model.summary()

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

  history = model.fit(train_generator, epochs=25, steps_per_epoch=20, validation_data=validation_generator, verbose=1,
                      validation_steps=3)

  model.save("rps.h5")

import matplotlib.pyplot as plt
acc = history.history['accuracy']
val_acc = history.history['val_accuracy']
loss = history.history['loss']
val_loss = history.history['val_loss']

epochs = range(len(acc))

plt.plot(epochs, acc, 'r', label='Training accuracy')
plt.plot(epochs, val_acc, 'b', label='Validation accuracy')
plt.title('Training and validation accuracy')
plt.legend(loc=0)
plt.figure()


plt.show()

这是我的输出:

C:\Users\akgun\miniconda3\envs\tf2-nightly-gpu\python.exe C:/Users/akgun/PycharmProjects/pythonProject/deneme2.py
2020-12-15 14:49:08.370723: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library cudart64_110.dll
2020-12-15 14:49:09.980852: 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:  AVX2
To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags.
2020-12-15 14:49:09.983593: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library nvcuda.dll
2020-12-15 14:49:09.990995: E tensorflow/stream_executor/cuda/cuda_driver.cc:328] failed call to cuInit: CUDA_ERROR_UNKNOWN: unknown error
2020-12-15 14:49:09.993186: I tensorflow/stream_executor/cuda/cuda_diagnostics.cc:169] retrieving CUDA diagnostic information for host: DESKTOP-5CNHSHI
2020-12-15 14:49:09.993315: I tensorflow/stream_executor/cuda/cuda_diagnostics.cc:176] hostname: DESKTOP-5CNHSHI
WARNING:tensorflow:From C:/Users/akgun/PycharmProjects/pythonProject/deneme2.py:14: The name tf.keras.backend.set_session is deprecated. Please use tf.compat.v1.keras.backend.set_session instead.

total training düzgün images: 2102
total training yamuk images: 2102
['Basler_acA1440-220um__40052667__20201119_135952603_1000_result.jpg', 'Basler_acA1440-220um__40052667__20201119_135952603_1001_result.jpg', 'Basler_acA1440-220um__40052667__20201119_135952603_1002_result.jpg', 'Basler_acA1440-220um__40052667__20201119_135952603_1003_result.jpg', 'Basler_acA1440-220um__40052667__20201119_135952603_1004_result.jpg', 'Basler_acA1440-220um__40052667__20201119_135952603_1005_result.jpg', 'Basler_acA1440-220um__40052667__20201119_135952603_1007_result.jpg', 'Basler_acA1440-220um__40052667__20201119_135952603_1008_result.jpg', 'Basler_acA1440-220um__40052667__20201119_135952603_1009_result.jpg', 'Basler_acA1440-220um__40052667__20201119_135952603_100_result.jpg']
['Basler_acA1440-220um__40052667__20201119_135952603_1000_result.jpg', 'Basler_acA1440-220um__40052667__20201119_135952603_1001_result.jpg', 'Basler_acA1440-220um__40052667__20201119_135952603_1002_result.jpg', 'Basler_acA1440-220um__40052667__20201119_135952603_1003_result.jpg', 'Basler_acA1440-220um__40052667__20201119_135952603_1004_result.jpg', 'Basler_acA1440-220um__40052667__20201119_135952603_1005_result.jpg', 'Basler_acA1440-220um__40052667__20201119_135952603_1007_result.jpg', 'Basler_acA1440-220um__40052667__20201119_135952603_1008_result.jpg', 'Basler_acA1440-220um__40052667__20201119_135952603_1009_result.jpg', 'Basler_acA1440-220um__40052667__20201119_135952603_100_result.jpg']
Found 4204 images belonging to 2 classes.
Found 31030 images belonging to 133 classes.
(1080, 1440, 3)
['fruits-360/Training\\Duzgun', 'fruits-360/Training\\Yamuk']
NumberOfClass: 2
2020-12-15 14:49:17.828107: W tensorflow/core/framework/cpu_allocator_impl.cc:80] Allocation of 1499463680 exceeds 10% of free system memory.
2020-12-15 14:49:18.376445: W tensorflow/core/framework/cpu_allocator_impl.cc:80] Allocation of 1499463680 exceeds 10% of free system memory.
2020-12-15 14:49:18.538420: W tensorflow/core/framework/cpu_allocator_impl.cc:80] Allocation of 1499463680 exceeds 10% of free system memory.
Model: "sequential"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
conv2d (Conv2D)              (None, 1078, 1438, 64)    1792      
_________________________________________________________________
max_pooling2d (MaxPooling2D) (None, 539, 719, 64)      0         
_________________________________________________________________
conv2d_1 (Conv2D)            (None, 537, 717, 64)      36928     
_________________________________________________________________
max_pooling2d_1 (MaxPooling2 (None, 268, 358, 64)      0         
_________________________________________________________________
conv2d_2 (Conv2D)            (None, 266, 356, 128)     73856     
_________________________________________________________________
max_pooling2d_2 (MaxPooling2 (None, 133, 178, 128)     0         
_________________________________________________________________
conv2d_3 (Conv2D)            (None, 131, 176, 128)     147584    
_________________________________________________________________
max_pooling2d_3 (MaxPooling2 (None, 65, 88, 128)       0         
_________________________________________________________________
flatten (Flatten)            (None, 732160)            0         
_________________________________________________________________
dropout (Dropout)            (None, 732160)            0         
_________________________________________________________________
dense (Dense)                (None, 512)               374866432 
_________________________________________________________________
dense_1 (Dense)              (None, 3)                 1539      
=================================================================
Total params: 375,128,131
Trainable params: 375,128,131
Non-trainable params: 0
_________________________________________________________________
Epoch 1/25
2020-12-15 14:49:20.430705: I tensorflow/compiler/mlir/mlir_graph_optimization_pass.cc:127] None of the MLIR optimization passes are enabled (registered 2)
2020-12-15 14:49:20.546988: W tensorflow/core/framework/cpu_allocator_impl.cc:80] Allocation of 1499463680 exceeds 10% of free system memory.
2020-12-15 14:49:21.043400: W tensorflow/core/framework/cpu_allocator_impl.cc:80] Allocation of 1499463680 exceeds 10% of free system memory.
Traceback (most recent call last):
  File "C:/Users/akgun/PycharmProjects/pythonProject/deneme2.py", line 122, in <module>
    validation_steps=3)
  File "C:\Users\akgun\miniconda3\envs\tf2-nightly-gpu\lib\site-packages\tensorflow\python\keras\engine\training.py", line 1132, in fit
    tmp_logs = self.train_function(iterator)
  File "C:\Users\akgun\miniconda3\envs\tf2-nightly-gpu\lib\site-packages\tensorflow\python\eager\def_function.py", line 797, in __call__
    result = self._call(*args, **kwds)
  File "C:\Users\akgun\miniconda3\envs\tf2-nightly-gpu\lib\site-packages\tensorflow\python\eager\def_function.py", line 858, in _call
    return self._stateless_fn(*args, **kwds)
  File "C:\Users\akgun\miniconda3\envs\tf2-nightly-gpu\lib\site-packages\tensorflow\python\eager\function.py", line 2972, in __call__
    filtered_flat_args, captured_inputs=graph_function.captured_inputs)  # pylint: disable=protected-access
  File "C:\Users\akgun\miniconda3\envs\tf2-nightly-gpu\lib\site-packages\tensorflow\python\eager\function.py", line 1948, in _call_flat
    ctx, args, cancellation_manager=cancellation_manager))
  File "C:\Users\akgun\miniconda3\envs\tf2-nightly-gpu\lib\site-packages\tensorflow\python\eager\function.py", line 561, in call
    ctx=ctx)
  File "C:\Users\akgun\miniconda3\envs\tf2-nightly-gpu\lib\site-packages\tensorflow\python\eager\execute.py", line 60, in quick_execute
    inputs, attrs, num_outputs)
tensorflow.python.framework.errors_impl.InvalidArgumentError:  Input to reshape is a tensor with 790272 values, but the requested shape requires a multiple of 732160
     [[node sequential/flatten/Reshape (defined at /Users/akgun/PycharmProjects/pythonProject/deneme2.py:122) ]] [Op:__inference_train_function_1144]

Function call stack:
train_function

这是我的错误:

tensorflow.python.framework.errors_impl.InvalidArgumentError:  Input to reshape is a tensor with 790272 values, but the requested shape requires a multiple of 732160
     [[node sequential/flatten/Reshape (defined at /Users/akgun/PycharmProjects/pythonProject/deneme2.py:122) ]] [Op:__inference_train_function_1144]

Function call stack:
train_function

Tags: ofinimportnoneimgtftensorflowplt

热门问题