質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.50%
Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

Q&A

解決済

3回答

1089閲覧

Tensorflowによるモデル学習で躓いています

tanuki_

総合スコア31

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

0グッド

0クリップ

投稿2021/02/16 03:43

編集2021/02/17 01:22

以下のコードを実行した所、モデルの学習の所でエラーが
発生してしまいます。
原因と対処方法をご教示頂けると幸いです。

python

1import sys , os 2import random 3 4import numpy as np 5import cv2 6 7 8# 画像をランダムの位置で切り抜くプログラム 9def random_clip(img , clip_size , num = 10): 10 clip_images = [] 11 height, width = img.shape[:2] 12 13 # 画像をclip_sizeサイズごとにnum回切り抜く 14 for y in range( num ): 15 rand_y = random.randint(0,height - clip_size) 16 rand_x = random.randint(0,width - clip_size) 17 clip_img = img[ rand_y : rand_y + clip_size, rand_x : rand_x + clip_size] 18 clip_img = clip_img.flatten().astype(np.float32)/255.0 19 clip_images.append(clip_img) 20 21 return clip_images 22 23 24# データセットから画像とラベルをランダムに取得 25def random_sampling( images , labels , train_num , test_num = 0 ): 26 image_train_batch = [] 27 label_train_batch = [] 28 29 #乱数を発生させ,リストを並び替える. 30 random_seq = list(range(len(images))) 31 random.shuffle(random_seq) 32 33 # バッチサイズ分画像を選択 34 image_train_batch = images[ :train_num ] 35 label_train_batch = labels[ :train_num ] 36 37 if test_num == 0: # 検証用データの指定がないとき 38 return image_train_batch , label_train_batch 39 else: 40 image_test_batch = images[ train_num : train_num + test_num ] 41 label_test_batch = labels[ train_num : train_num + test_num ] 42 return image_train_batch , label_train_batch , image_test_batch , label_test_batch 43 44 45# フォルダーの画像をランダム位置でクリップした後にリサイズして読み込む 46def make( folder_name , img_size = 0 , clip_num = 0 , clip_size = 0 ,train_num = 0 , test_num = 0 ): 47 train_image = [] 48 test_image = [] 49 train_label = [] 50 test_label= [] 51 52 # フォルダ内のディレクトリの読み込み 53 classes = os.listdir( folder_name ) 54 55 for i, d in enumerate(classes): 56 files = os.listdir( folder_name + '/' + d ) 57 58 tmp_image = [] 59 tmp_label = [] 60 for f in files: 61 # 1枚の画像に対する処理 62 if not 'jpg' in f:# jpg以外のファイルは無視 63 continue 64 65 # 画像読み込み 66 img = cv2.imread( folder_name+ '/' + d + '/' + f) 67 # one_hot_vectorを作りラベルとして追加 68 label = np.zeros(len(classes)) 69 if d == "0": 70 label[i] = 0 71 elif d == "1": 72 label[i] = 1 73 else: 74 label[i] = 0 75 76 # リサイズをする処理 77 if img_size != 0: 78 img = cv2.resize( img , (img_size , img_size )) 79 img = img.flatten().astype(np.float32)/255.0 80 tmp_image.append(img) 81 tmp_label.append(label) 82 elif clip_size != 0 and clip_num != 0: 83 img = random_clip( img , clip_size , clip_num) 84 tmp_image.extend( img ) 85 for j in range(clip_num): 86 tmp_label.append(label) 87 else: 88 img = img.flatten().astype(np.float32)/255.0 89 tmp_image.append(img) 90 tmp_label.append(label) 91 92 93 # データセットのサイズが指定されているときはその枚数分ランダムに抽出する 94 if train_num == 0 : 95 train_image.extend( tmp_image ) 96 train_label.extend( tmp_label ) 97 # テスト画像の指定がないとき 98 elif test_num == 0 : 99 sampled_image , sampled_label = random_sampling( tmp_image , tmp_label , train_num ) 100 train_image.extend( sampled_image ) 101 train_label.extend( sampled_label ) 102 else : 103 sampled_train_image , sampled_train_label , sampled_test_image , sampled_test_label = random_sampling( tmp_image , tmp_label , train_num , test_num ) 104 train_image.extend( sampled_train_image ) 105 train_label.extend( sampled_train_label ) 106 test_image.extend( sampled_test_image ) 107 test_label.extend( sampled_test_label ) 108 109 print(d + 'read complete ,' + str(len(train_label)) + ' pictures exit') 110 111 # numpy配列に変換 112 train_image = np.asarray( train_image ) 113 train_label = np.asarray( train_label ) 114 115 if test_num != 0: #testデータセットがあるときは返り値が変わる 116 test_image = np.asarray( test_image ) 117 test_label = np.asarray( test_label ) 118 return train_image , train_label , test_image , test_label 119 120 return train_image , train_label 121

python

1# TensorFlow と tf.keras のインポート 2import tensorflow as tf 3from tensorflow import keras 4 5# ヘルパーライブラリのインポート 6import numpy as np 7import matplotlib.pyplot as plt 8 9print(tf.__version__) 10 11#mnist = keras.datasets.mnist 12 13#(train_images, train_labels), (test_images, test_labels) = mnist.load_data() 14import image_dataset 15train_images ,train_labels, test_images ,test_labels = image_dataset.make('C:/Users/cv/dataset',img_size = 32, train_num=10000 , test_num =1000) 16 17train_images.shape 18 19print(train_images.shape, train_labels.shape) 20 21#plt.figure() 22#plt.imshow(train_images[0], cmap='gray') 23#plt.colorbar() 24#plt.grid(False) 25#試しに表示 26#plt.show() 27 28len(train_labels) 29train_labels 30test_images.shape 31len(test_labels) 32 33#データの前処理 34#plt.figure() 35#plt.imshow(train_images[0]) 36#plt.colorbar() 37#plt.grid(False) 38#plt.show() 39 40train_images = train_images / 255.0 41test_images = test_images / 255.0 42 43model = keras.Sequential([ 44 keras.layers.Dense(128, activation='relu'), 45 keras.layers.Dense(10, activation='softmax') 46]) 47#モデルのコンパイル 48model.compile(optimizer='adam', 49 loss='sparse_categorical_crossentropy', 50 metrics=['accuracy']) 51#モデルの訓練 52model.fit(train_images, train_labels, epochs=5) 53 54# save model 55model.save("model_cnn.h5") 56 57test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2) 58#正解率の評価 59print('\nTest accuracy:', test_acc) 60 61print("end") 62

Flatten実行の行を消して実行した結果

2021-02-17 10:05:53.420778: 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-17 10:05:53.428672: 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 ~中略~ (10, 3072) (10, 10) 2021-02-17 10:05:59.694157: I tensorflow/compiler/jit/xla_cpu_device.cc:41] Not creating XLA devices, tf_xla_enable_xla_devices not set 2021-02-17 10:05:59.706703: W tensorflow/stream_executor/platform/default/dso_loader.cc:60] Could not load dynamic library 'nvcuda.dll'; dlerror: nvcuda.dll not found 2021-02-17 10:05:59.718986: W tensorflow/stream_executor/cuda/cuda_driver.cc:326] failed call to cuInit: UNKNOWN ERROR (303) 2021-02-17 10:05:59.799102: I tensorflow/stream_executor/cuda/cuda_diagnostics.cc:169] retrieving CUDA diagnostic information for host: CVPC-0164 2021-02-17 10:05:59.806406: I tensorflow/stream_executor/cuda/cuda_diagnostics.cc:176] hostname: CVPC-0164 2021-02-17 10:05:59.811840: I tensorflow/core/platform/cpu_feature_guard.cc:142] This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN) to use t he following CPU instructions in performance-critical operations: AVX2 To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags. 2021-02-17 10:05:59.820411: I tensorflow/compiler/jit/xla_gpu_device.cc:99] Not creating XLA devices, tf_xla_enable_xla_devices not set 2021-02-17 10:06:00.102449: I tensorflow/compiler/mlir/mlir_graph_optimization_pass.cc:116] None of the MLIR optimization passes are enabled (registered 2) Epoch 1/5 Traceback (most recent call last): File "cnn_image.py", line 53, in <module> model.fit(train_images, train_labels, epochs=5) File "C:\Users\anaconda3\envs\tensorflow-cpu\lib\site-packages\tensorflow\python\keras\engine\training.py", line 1100, in fit tmp_logs = self.train_function(iterator) File "C:\Users\anaconda3\envs\tensorflow-cpu\lib\site-packages\tensorflow\python\eager\def_function.py", line 828, in __call__ result = self._call(*args, **kwds) File "C:\Users\anaconda3\envs\tensorflow-cpu\lib\site-packages\tensorflow\python\eager\def_function.py", line 888, in _call return self._stateless_fn(*args, **kwds) File "C:\Users\anaconda3\envs\tensorflow-cpu\lib\site-packages\tensorflow\python\eager\function.py", line 2942, in __call__ return graph_function._call_flat( File "C:\Users\anaconda3\envs\tensorflow-cpu\lib\site-packages\tensorflow\python\eager\function.py", line 1918, in _call_flat return self._build_call_outputs(self._inference_function.call( File "C:\Users\anaconda3\envs\tensorflow-cpu\lib\site-packages\tensorflow\python\eager\function.py", line 555, in call outputs = execute.execute( File "C:\Users\anaconda3\envs\tensorflow-cpu\lib\site-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:53) ]] [Op:__inference_train_ function_528] Function call stack: train_function PS C:\Users\cv>

print(train_images.shape, train_labels.shape)の結果

(10, 2352) (10, 10)

python3.7
Tensorflow2.4.1

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

DaiGuard

2021/02/16 03:51

はじめましてエラーを見る限り `train_images`の配列形状に問題があるかもしれないので `print(train_images.shape, train_labels.shape)`の結果を 出してもらうことはできますか?
tanuki_

2021/02/16 04:05

承知致しました。少々お待ち下さいませ
tanuki_

2021/02/16 04:09

DaiGuardさん 結果になります。 (10, 2352) (10, 10)
guest

回答3

0

自己解決

当初のエラーはお2方のご教示で解決致しましたのでこちらはクローズと致します。

投稿2021/02/17 04:21

tanuki_

総合スコア31

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

0

今回使われているモデルは
以下のようなデータ形状の変更を行います
すでにtrain_imagesがフラットな形状になっているようなので
Flattenの行を消して動くと思います

Python

1keras.layers.Flatten(input_shape=(28, 28)), # (28, 28) -> (784) 2 keras.layers.Dense(128, activation='relu'), # (784) -> (128) 3 keras.layers.Dense(10, activation='softmax') # (128) -> (10)

投稿2021/02/16 22:47

DaiGuard

総合スコア159

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

tanuki_

2021/02/17 00:40

ありがとうございます。 これから試してみます。
tanuki_

2021/02/17 01:11

試してみたのですが別のエラーが発生して学習が動きませんでした。 質問を更新しますのでご教示頂けると幸いです。
guest

0

ニューラルネットの入力のshapeが次のように28x28=784のデータなのに対して、

python

1 keras.layers.Flatten(input_shape=(28, 28)),

train_imagesのshapeの2次元目は2352(=32x32x3)になってしまっています。

読み込んでいる画像ファイルはRGBのカラー画像ですか?
もしカラー画像なら、
関数def make()で32x32に画像をリサイズしているようですので、

python

1 keras.layers.Flatten(input_shape=(32, 32, 3)),

とすれば良いと思います。

投稿2021/02/16 13:22

aipy2020

総合スコア35

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

tanuki_

2021/02/17 00:38

ありがとうございます。 これから試してみます。
tanuki_

2021/02/17 02:25

読み込んでいる画像ファイルはRGBのカラー画像です。 keras.layers.Flatten(input_shape=(32, 32, 3)), とした所、別のエラーに直面しました。 ご教示頂けると幸いです。
aipy2020

2021/02/17 08:15

お役に立てず申し訳ありません。 Flatten消して、最初のDenseに、input_shape=(2352, )をつけるのが正解でしたかね。 私に勘違いがあり、誤った回答をしてしまい申し訳ありません。 また、2352は28x28x3ですね。2重に間違っていました。
tanuki_

2021/02/18 01:32

aipy2020さん 十分に助けて頂きました。 ありがとうございました。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.50%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問