画像判別のプログラムを正常に動かしたい
Google Colabratory上でPythonを用いて画像判別を行っています。
結果をだす過程で以下のエラーメッセージが発生しました。
いろいろなサイトを参考にさせていただき、なんとか訓練データの結果は得られるようになったと思うのですが、テスト結果や図の表示など、その先がうまく行きません。
よろしければ、直した方が良い点を指摘していただければ幸いです。どうかよろしくお願いします。
発生している問題・エラーメッセージ
OverflowError Traceback (most recent call last) <ipython-input-54-1cd9c70489aa> in <module>() 136 137 # モデルを評価 --- (*5) --> 138 score = model_cnn.evaluate(X_test, y_test, verbose=1) 139 print('正解率=', score[1], 'loss=', score[0]) 140 4 frames /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/training.py in evaluate(self, x, y, batch_size, verbose, sample_weight, steps, callbacks, max_queue_size, workers, use_multiprocessing, return_dict) 1394 callbacks.on_test_batch_end(end_step, logs) 1395 logs = tf_utils.to_numpy_or_python_type(logs) -> 1396 callbacks.on_test_end(logs=logs) 1397 1398 if return_dict: /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/callbacks.py in on_test_end(self, logs) 560 for callback in self.callbacks: 561 if getattr(callback, '_supports_tf_logs', False): --> 562 callback.on_test_end(logs) 563 else: 564 if numpy_logs is None: # Only convert once. /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/callbacks.py in on_test_end(self, logs) 1033 def on_test_end(self, logs=None): 1034 if not self._called_in_fit: -> 1035 self._finalize_progbar(logs, self._test_step) 1036 1037 def on_predict_end(self, logs=None): /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/callbacks.py in _finalize_progbar(self, logs, counter) 1094 self.target = counter or self.seen 1095 self.progbar.target = self.target -> 1096 self.progbar.update(self.target, list(logs.items()), finalize=True) 1097 1098 /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/utils/generic_utils.py in update(self, current, values, finalize) 581 582 if self.target is not None: --> 583 numdigits = int(np.log10(self.target)) + 1 584 bar = ('%' + str(numdigits) + 'd/%d [') % (current, self.target) 585 prog = float(current) / self.target OverflowError: cannot convert float infinity to integer
該当のソースコード
Python
1# CNNでMNISTの分類問題に挑戦 2import keras 3from keras.models import Sequential 4from keras.layers import Dense, Dropout, Flatten 5from keras.layers import Conv2D, MaxPooling2D 6import matplotlib.pyplot as plt 7import os 8import cv2 9import random 10import numpy as np 11 12# Google driveをマウントする (既にマウントしていたら飛ばしてOK) 13from google.colab import drive 14drive.mount('/content/drive') 15 16 17DATADIR = "/content/drive/MyDrive/Colab Notebooks/Galaxy_Zoo/Train_Image" 18CATEGORIES = ["face-on", "edge-on"] 19IMG_SIZE = 32 20training_data = [] 21 22def create_training_data(): 23 for class_num, category in enumerate(CATEGORIES): 24 path = os.path.join(DATADIR, category) 25 for image_name in os.listdir(path): 26 try: 27 img_array = cv2.imread(os.path.join(path, image_name), cv2.IMREAD_GRAYSCALE) # 画像読み込み 28 img_resize_array = cv2.resize(img_array, (IMG_SIZE, IMG_SIZE)) # 画像のリサイズ 29 training_data.append([img_resize_array, class_num]) # 画像データ、ラベル情報を追加 30 except Exception as e: 31 pass 32 33create_training_data() 34 35random.shuffle(training_data) # データをシャッフル 36 37X_train = [] # 画像データ 38y_train = [] # ラベル情報 39 40# データセット作成 41for feature, label in training_data: 42 X_train.append(feature) 43 y_train.append(label) 44 45 # numpy配列に変換 46X_train = np.array(X_train) 47y_train = np.array(y_train) 48 49DATADIR = "/content/drive/MyDrive/Colab Notebooks/Galaxy_Zoo/Test_Image" 50IMG_SIZE = 50 51test_data = [] 52 53def create_test_data(): 54 path = os.path.join(DATADIR) 55 for image_name in os.listdir(path): 56 try: 57 img_array = cv2.imread(os.path.join(path, image_name), cv2.IMREAD_GRAYSCALE) # 画像読み込み 58 img_resize_array = cv2.resize(img_array, (IMG_SIZE, IMG_SIZE)) # 画像のリサイズ 59 training_data.append([img_resize_array, class_num]) # 画像データ、ラベル情報を追加 60 except Exception as e: 61 pass 62 63create_test_data() 64 65random.shuffle(test_data) # データをシャッフル 66 67X_test = [] # 画像データ 68y_test = [] # ラベル情報 69 70# データセット作成 71for feature, label in test_data: 72 X_test.append(feature) 73 y_test.append(label) 74 75# numpy配列に変換 76X_test = np.array(X_test) 77y_test = np.array(y_test) 78 79xy = (X_train, X_test, y_train, y_test) 80#データを保存する(データの名前を「tea_data.npy」としている) 81np.save("/content/drive/MyDrive/Colab Notebooks/Galaxy_Zoo/galaxy_zoo.npy", xy) 82 83# 入力と出力を指定 84in_shape = (32, 32, 1) 85out_size = 2 86 87 88# データを(1, 28, 28)の三次元配列に変換 89X_train = X_train.reshape(X_train.shape[0], 32, 32, 1).astype('float32') / 255 90X_test = X_test.reshape(X_test.shape[0], 32, 32, 1).astype('float32') / 255 91 92 93# ラベルデータをone-hotベクトルに直す 94y_train = keras.utils.to_categorical(y_train.astype('int32'),2) 95y_test = keras.utils.to_categorical(y_test.astype('int32'),2) 96 97# CNNモデル構造を定義 --- (*2) 98model_cnn = Sequential() 99model_cnn.add(Conv2D(32, kernel_size=(3, 3), #畳み込み層 100 activation='relu', 101 input_shape=in_shape)) 102model_cnn.add(Conv2D(64, (3, 3), activation='relu')) 103model_cnn.add(MaxPooling2D(pool_size=(2, 2))) #プーリング層 104model_cnn.add(Dropout(0.25)) #ドロップアウトモジュール 105model_cnn.add(Flatten()) #入力をフラットにするモジュール 106model_cnn.add(Dense(128, activation='relu')) #活性化関数モジュール 107model_cnn.add(Dropout(0.5)) 108model_cnn.add(Dense(out_size, activation='softmax')) 109 110# モデルを構築 --- (*3) 111RMSprop=keras.optimizers.RMSprop(lr=0.001, rho=0.9, epsilon=None, decay=0.0) 112model_cnn.compile( 113 loss='categorical_crossentropy', 114 optimizer=RMSprop, 115 metrics=['accuracy']) 116 117# 学習を実行 --- (*4) 118hist = model_cnn.fit(X_train, y_train, 119 batch_size=32, #batch_size : 一回に計算するデータ数のこと 120 epochs=12, 121 verbose=1, #verbose : 1の場合はログをプログレスバーで標準出力 122 validation_data=(X_test, y_test)) #各エポックの損失関数や評価関数で用いられるタプル 123 124# モデルを評価 --- (*5) 125score = model_cnn.evaluate(X_test, y_test, verbose=1) 126print('正解率=', score[1], 'loss=', score[0]) 127 128# 学習の様子をグラフへ描画 --- (*6) 129# 正解率の推移をプロット 130plt.plot(hist.history['accuracy']) 131plt.plot(hist.history['val_accuracy']) 132plt.title('Accuracy') 133plt.legend(['train', 'test'], loc='upper left') 134plt.show() 135 136# ロスの推移をプロット 137plt.plot(hist.history['loss']) 138plt.plot(hist.history['val_loss']) 139plt.title('Loss') 140plt.legend(['train', 'test'], loc='upper left') 141plt.show()
結果
Drive already mounted at /content/drive; to attempt to forcibly remount, call drive.mount("/content/drive", force_remount=True). /usr/local/lib/python3.6/dist-packages/numpy/core/_asarray.py:136: VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If you meant to do this, you must specify 'dtype=object' when creating the ndarray return array(a, dtype, copy=False, order=order, subok=True) Epoch 1/12 63/63 [==============================] - 7s 104ms/step - loss: 0.5900 - accuracy: 0.7012 Epoch 2/12 63/63 [==============================] - 6s 102ms/step - loss: 0.4441 - accuracy: 0.8126 Epoch 3/12 63/63 [==============================] - 6s 102ms/step - loss: 0.3286 - accuracy: 0.8648 Epoch 4/12 63/63 [==============================] - 6s 102ms/step - loss: 0.3193 - accuracy: 0.8620 Epoch 5/12 63/63 [==============================] - 6s 101ms/step - loss: 0.2751 - accuracy: 0.8853 Epoch 6/12 63/63 [==============================] - 6s 102ms/step - loss: 0.2461 - accuracy: 0.9049 Epoch 7/12 63/63 [==============================] - 6s 101ms/step - loss: 0.2325 - accuracy: 0.9105 Epoch 8/12 63/63 [==============================] - 6s 102ms/step - loss: 0.2399 - accuracy: 0.8973 Epoch 9/12 63/63 [==============================] - 6s 102ms/step - loss: 0.2260 - accuracy: 0.9130 Epoch 10/12 63/63 [==============================] - 6s 102ms/step - loss: 0.1706 - accuracy: 0.9312 Epoch 11/12 63/63 [==============================] - 6s 101ms/step - loss: 0.1836 - accuracy: 0.9229 Epoch 12/12 63/63 [==============================] - 6s 101ms/step - loss: 0.1668 - accuracy: 0.9363 /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/utils/generic_utils.py:583: RuntimeWarning: divide by zero encountered in log10 numdigits = int(np.log10(self.target)) + 1
補足情報(FW/ツールのバージョンなど)
Python(ver. 3.6.9)
回答1件
あなたの回答
tips
プレビュー