以下のコードを実行した所、モデルの学習の所で、
ValueError: Input 0 of layer dense is incompatible with the layer: expected axis -1 of input shape to have value 2025 but received input with shape (None, 6075)
が発生してしまいます。
ネットワークの入力を、
python
input_shape=(45, 45,3)
とした所、当初のエラーは解消されたように見えます。
今度は、
tensorflow.python.framework.errors_impl.InvalidArgumentError: logits and labels must have the same first dimension, got logits shape [10,10] and labels shape [100]
というエラーが出ます。
CNNをはじめて実装したので,原因がよくわかっていません。
わかる方.宜しくお願い致します。
データセット作成で使用している画像(カラー)(45×45×3)
python
import sys , os import random import numpy as np import cv2 # 画像をランダムの位置で切り抜くプログラム def random_clip(img , clip_size , num = 10): clip_images = [] height, width = img.shape[:2] # 画像をclip_sizeサイズごとにnum回切り抜く for y in range( num ): rand_y = random.randint(0,height - clip_size) rand_x = random.randint(0,width - clip_size) clip_img = img[ rand_y : rand_y + clip_size, rand_x : rand_x + clip_size] clip_img = clip_img.flatten().astype(np.float32)/255.0 clip_images.append(clip_img) return clip_images # データセットから画像とラベルをランダムに取得 def random_sampling( images , labels , train_num , test_num = 0 ): image_train_batch = [] label_train_batch = [] #乱数を発生させ,リストを並び替える. random_seq = list(range(len(images))) random.shuffle(random_seq) # バッチサイズ分画像を選択 image_train_batch = images[ :train_num ] label_train_batch = labels[ :train_num ] if test_num == 0: # 検証用データの指定がないとき return image_train_batch , label_train_batch else: image_test_batch = images[ train_num : train_num + test_num ] label_test_batch = labels[ train_num : train_num + test_num ] return image_train_batch , label_train_batch , image_test_batch , label_test_batch # フォルダーの画像をランダム位置でクリップした後にリサイズして読み込む def make( folder_name , img_size = 0 , clip_num = 0 , clip_size = 0 ,train_num = 0 , test_num = 0 ): train_image = [] test_image = [] train_label = [] test_label= [] # フォルダ内のディレクトリの読み込み classes = os.listdir( folder_name ) for i, d in enumerate(classes): files = os.listdir( folder_name + '/' + d ) tmp_image = [] tmp_label = [] for f in files: # 1枚の画像に対する処理 if not 'jpg' in f:# jpg以外のファイルは無視 continue # 画像読み込み img = cv2.imread( folder_name+ '/' + d + '/' + f) # one_hot_vectorを作りラベルとして追加 label = np.zeros(len(classes)) if d == "0": label[i] = 0 elif d == "1": label[i] = 1 else: label[i] = 0 # リサイズをする処理 if img_size != 0: img = cv2.resize( img , (img_size , img_size )) img = img.flatten().astype(np.float32)/255.0 tmp_image.append(img) tmp_label.append(label) elif clip_size != 0 and clip_num != 0: img = random_clip( img , clip_size , clip_num) tmp_image.extend( img ) for j in range(clip_num): tmp_label.append(label) else: img = img.flatten().astype(np.float32)/255.0 tmp_image.append(img) tmp_label.append(label) # データセットのサイズが指定されているときはその枚数分ランダムに抽出する if train_num == 0 : train_image.extend( tmp_image ) train_label.extend( tmp_label ) # テスト画像の指定がないとき elif test_num == 0 : sampled_image , sampled_label = random_sampling( tmp_image , tmp_label , train_num ) train_image.extend( sampled_image ) train_label.extend( sampled_label ) else : sampled_train_image , sampled_train_label , sampled_test_image , sampled_test_label = random_sampling( tmp_image , tmp_label , train_num , test_num ) train_image.extend( sampled_train_image ) train_label.extend( sampled_train_label ) test_image.extend( sampled_test_image ) test_label.extend( sampled_test_label ) print(d + 'read complete ,' + str(len(train_label)) + ' pictures exit') # numpy配列に変換 train_image = np.asarray( train_image ) train_label = np.asarray( train_label ) if test_num != 0: #testデータセットがあるときは返り値が変わる test_image = np.asarray( test_image ) test_label = np.asarray( test_label ) return train_image , train_label , test_image , test_label return train_image , train_label
python
# TensorFlow と tf.keras のインポート import tensorflow as tf from tensorflow import keras # ヘルパーライブラリのインポート import numpy as np import matplotlib.pyplot as plt print(tf.__version__) #mnist = keras.datasets.mnist #(train_images, train_labels), (test_images, test_labels) = mnist.load_data() import image_dataset #train_images ,train_labels, test_images ,test_labels = image_dataset.make('C:/Users/dataset',img_size = 28, train_num=10000 , test_num =1000) train_images ,train_labels, test_images ,test_labels = image_dataset.make('C:/Users/dataset',img_size = 45, train_num=10000 , test_num =1000) train_images.shape #print(train_images.shape, train_labels.shape) print('train_images.shape:') print(train_images.shape) #plt.figure() #plt.imshow(train_images[0], cmap='gray') #plt.colorbar() #plt.grid(False) #試しに表示 #plt.show() len(train_labels) train_labels test_images.shape len(test_labels) #データの前処理 #plt.figure() #plt.imshow(train_images[0]) #plt.colorbar() #plt.grid(False) #plt.show() train_images = train_images / 255.0 test_images = test_images / 255.0 #model = keras.Sequential([ # keras.layers.Flatten(input_shape=(32, 32, 3)), # keras.layers.Dense(128, activation='relu'), # keras.layers.Dense(10, activation='softmax') #]) model = tf.keras.Sequential([ tf.keras.layers.Flatten(input_shape=(45, 45,3), name='flatten_layer'), tf.keras.layers.Dense(128, activation='relu'), tf.keras.layers.Dropout(0.2), tf.keras.layers.Dense(10, activation='softmax') ]) #model.summary() #モデルのコンパイル model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy']) #モデルの訓練 model.fit(train_images, train_labels, epochs=5) # save model model.save("model_cnn.h5") test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2) #正解率の評価 print('\nTest accuracy:', test_acc) print("end")
実行結果
2021-02-19 13:07:03.954106: W tensorflow/stream_executor/platform/default/dso_loader.cc:60] Could not load dynamic library 'cudart64_110.dll'; dlerror: cudart64_110.dll not f ound 2021-02-19 13:07:03.956781: I tensorflow/stream_executor/cuda/cudart_stub.cc:29] Ignore above cudart dlerror if you do not have a GPU set up on your machine. 2.4.1 0read complete ,1 pictures exit 1read complete ,2 pictures exit train_images.shape: (10, 6075) 2021-02-19 13:07:06.893626: I tensorflow/compiler/jit/xla_cpu_device.cc:41] Not creating XLA devices, tf_xla_enable_xla_devices not set ~中略~ packages\tensorflow\python\eager\execute.py", line 59, in quick_execute tensors = pywrap_tfe.TFE_Py_Execute(ctx._handle, device_name, op_name, tensorflow.python.framework.errors_impl.InvalidArgumentError: logits and labels must have the same first dimension, got logits shape [10,10] and labels shape [100] [[node sparse_categorical_crossentropy/SparseSoftmaxCrossEntropyWithLogits/SparseSoftmaxCrossEntropyWithLogits (defined at cnn_image.py:66) ]] [Op:__inference_train_ function_571] Function call stack: train_function
print(train_images.shape)の結果
(10, 6075)
print(train_labels.shape)の結果
(10,10)
Tensorflow2.4.1
Python3.7
まだ回答がついていません
会員登録して回答してみよう