sumple_cnn_classificationという機械学習のプログラムを作り、その重みを使って、画像の判別機を造ってみたのですが、pathとして設定した画像を読み込もうとするとエラーが出てきてしまうので、対処法を教えていただきたいです。
コードを読めばどのように出力したいかがわかると思いますが、今回は次郎ではありませんと表示したいです。
sumple_cnn_classificationのコード
from keras.layers import Conv2D, MaxPooling2D from keras.layers import Dense, Dropout, Flatten from keras.models import Sequential import keras from sklearn.model_selection import train_test_split from keras.preprocessing import image import numpy as np import tensorflow as tf import random as rn import os from keras import backend as K import matplotlib.pyplot as plt os.environ['PYTHONHASHSEED'] = '0' np.random.seed(0) rn.seed(0) session_conf = tf.compat.v1.ConfigProto( intra_op_parallelism_threads=1, inter_op_parallelism_threads=1) tf.set_random_seed(0) sess = tf.Session(graph=tf.get_default_graph(), config=session_conf) K.set_session(sess) sess = tf.Session(config=tf.ConfigProto(device_count={'GPU': 0})) input_shape = (224, 224, 3) batch_size = 128 epochs = 100 num_classes = 2 x = [] y = [] for f in os.listdir("jiro"): if f == ".DS_Store": continue x.append(image.img_to_array(image.load_img( "jiro/"+f, target_size=input_shape[:2]))) y.append(0) for f in os.listdir("not-jiro"): if f == ".DS_Store": continue x.append(image.img_to_array(image.load_img( "not-jiro/"+f, target_size=input_shape[:2]))) y.append(1) x = np.asarray(x) x /= 255 y = np.asarray(y) y = keras.utils.to_categorical(y, num_classes) x_train, x_test, y_train, y_test = train_test_split( x, y, test_size=0.33, random_state=3) model = Sequential() model.add(Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=input_shape)) model.add(Conv2D(64, (3, 3), activation='relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Dropout(0.25)) model.add(Flatten()) model.add(Dense(128, activation='relu')) model.add(Dropout(0.5)) model.add(Dense(num_classes, activation='softmax')) model.compile(loss=keras.losses.categorical_crossentropy, optimizer="SGD", metrics=['accuracy']) history = model.fit(x_train, y_train, batch_size=batch_size, epochs=epochs, verbose=1, validation_data=(x_test, y_test)) model.save_weights('param.hdfs') acc = history.history["accuracy"] val_acc = history.history["val_accuracy"] loss = history.history["loss"] val_loss = history.history["val_loss"] epochs = range(1, len(acc) + 1) plt.plot(history.history["accuracy"], label="Training Acc") plt.plot(history.history["val_accuracy"], label="Validation Acc") plt.ylabel('Accuracy') plt.xlabel('Epoch') plt.grid() plt.legend(['Train', 'Validation'], loc = 'upper left') plt.savefig('acc.png') plt.figure() plt.plot(history.history["loss"], label="Training Loss") plt.plot(history.history["val_loss"], label="Validation Loss") plt.ylabel('Loss') plt.xlabel('Epoch') plt.grid() plt.legend(['Train', 'Validation'], loc = 'upper left') plt.savefig('loss.png') plt.figure() plt.show()
prediction.pyのコード
import keras import numpy as np from keras.layers import Conv2D, MaxPooling2D from keras.layers import Dense, Dropout, Flatten from keras.models import Sequential from PIL import Image imsize = (224, 224) testpick = "./not-jiro1.jpg" keras_param = "./param.hdfs" def load_image(path): img = Image.open(path) img = img.convert('RGB') img = img.resize(imsize) img = np.asarray(img) img = img / 255.0 return img def create_model(): input_shape = (224 ,224 , 3) num_classes = 2 model = Sequential() model.add(Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=input_shape)) model.add(Conv2D(64, (3, 3), activation='relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Dropout(0.25)) model.add(Flatten()) model.add(Dense(128, activation='relu')) model.add(Dropout(0.5)) model.add(Dense(num_classes, activation='softmax')) model.compile(loss=keras.losses.categorical_crossentropy, optimizer="SGD", metrics=['accuracy']) return model if __name__ == "__main__": model = create_model() model.load_weights('./param.hdfs') img = load_image(testpick) prd = model.predict(np.array([img])) print(prd) prelabel = np.argmax(prd, axis=1) if prelabel == 0: print("次郎です") elif prelabel == 1: print("次郎ではありません")
エラー文
(base) xxxx@xxxx image-classfication-jiro % /opt/anaconda3/bin/python /Users/xxxxx/Downloads/image-classfication-jiro/prediction.py Using TensorFlow backend. /opt/anaconda3/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:516: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_qint8 = np.dtype([("qint8", np.int8, 1)]) /opt/anaconda3/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:517: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_quint8 = np.dtype([("quint8", np.uint8, 1)]) /opt/anaconda3/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:518: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_qint16 = np.dtype([("qint16", np.int16, 1)]) /opt/anaconda3/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:519: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_quint16 = np.dtype([("quint16", np.uint16, 1)]) /opt/anaconda3/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:520: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_qint32 = np.dtype([("qint32", np.int32, 1)]) /opt/anaconda3/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:525: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. np_resource = np.dtype([("resource", np.ubyte, 1)]) /opt/anaconda3/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:541: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_qint8 = np.dtype([("qint8", np.int8, 1)]) /opt/anaconda3/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:542: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_quint8 = np.dtype([("quint8", np.uint8, 1)]) /opt/anaconda3/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:543: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_qint16 = np.dtype([("qint16", np.int16, 1)]) /opt/anaconda3/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:544: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_quint16 = np.dtype([("quint16", np.uint16, 1)]) /opt/anaconda3/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:545: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_qint32 = np.dtype([("qint32", np.int32, 1)]) /opt/anaconda3/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:550: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. np_resource = np.dtype([("resource", np.ubyte, 1)]) WARNING:tensorflow:From /opt/anaconda3/lib/python3.7/site-packages/keras/backend/tensorflow_backend.py:4070: The name tf.nn.max_pool is deprecated. Please use tf.nn.max_pool2d instead. 2020-07-21 00:41:03.368652: I tensorflow/core/platform/cpu_feature_guard.cc:145] This TensorFlow binary is optimized with Intel(R) MKL-DNN to use the following CPU instructions in performance critical operations: SSE4.1 SSE4.2 AVX AVX2 FMA To enable them in non-MKL-DNN operations, rebuild TensorFlow with the appropriate compiler flags. 2020-07-21 00:41:03.370393: I tensorflow/core/common_runtime/process_util.cc:115] Creating new thread pool with default inter op setting: 8. Tune using inter_op_parallelism_threads for best performance. Traceback (most recent call last): File "/Users/yusuke.a/Downloads/image-classfication-jiro/prediction.py", line 45, in <module> img = load_image(testpick) File "/Users/yusuke.a/Downloads/image-classfication-jiro/prediction.py", line 14, in load_image img = Image.open(path) File "/opt/anaconda3/lib/python3.7/site-packages/PIL/Image.py", line 2809, in open fp = builtins.open(filename, "rb") FileNotFoundError: [Errno 2] No such file or directory: './not-jiro1.jpg'
画像のnot-jiroの中にnot-jiro1.jpgという画像があります。
この際、画像の名前を手動でnot-jiro1.jpgと変更いたしました。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2020/07/21 00:43
2020/07/21 01:43
2020/07/21 03:28