顔認証のプログラムを実行したのですがエラーが複数発生し原因がよくわからないです。原因と解決方法をご教示お願いいたします。
環境は
tensorflow 2.2.0
keras 2.4.3
python 3.7.6
です。
以下が実行したコードになります。
from future import print_function
from keras.utils.np_utils import to_categorical
from keras.layers import Activation, Conv2D, Dense, Flatten, MaxPooling2D
from keras.models import Sequential
import numpy as np
import shutil
import random
import cv2
import glob
import os
import matplotlib.pyplot as plt
'''顔認識したい人の名前を定義する'''
---顔認識する対象を決定(検索ワードを入力)---
SearchName = ["A","B","C","D"]
---画像の取得枚数の上限---
ImgNumber =100
---CNNで学習するときの画像のサイズを設定(サイズが大きいと学習に時間がかかる)---
ImgSize=(128,128)
input_shape=(128,128,3)
for name in SearchName:
in_dir = "./FaceEdited/"+name+"/*"
in_jpg=glob.glob(in_dir)
img_file_name_list=os.listdir("./FaceEdited/"+name+"/")
---img_file_name_listをシャッフル、そのうち2割をtest_imageディテクトリに入れる---
random.shuffle(in_jpg)
os.makedirs('./test/' + name, exist_ok=True)
for t in range(len(in_jpg)//5):
shutil.move(str(in_jpg[t]), "./test/"+name)
X_train = []
Y_train = []
for i in range(len(SearchName)):
img_file_name_list=os.listdir("./FaceEdited/"+SearchName[i])
print("{}:トレーニング用の写真の数は{}枚です。".format(SearchName[i],len(img_file_name_list)))
for j in range(0,len(img_file_name_list)-1): n=os.path.join("./FaceEdited/"+SearchName[i]+"/",img_file_name_list[j]) img = cv2.imread(n) if img is None: print('image' + str(j) + ':NoImage') continue else: r,g,b = cv2.split(img) img = cv2.merge([r,g,b]) X_train.append(img) Y_train.append(i)
print("")
---テストデータのラベル付け---
X_test = [] ---画像データ読み込み---
Y_test = [] ---ラベル(名前)---
for i in range(len(SearchName)):
img_file_name_list=os.listdir("./test/"+SearchName[i])
print("{}:テスト用の写真の数は{}枚です。".format(SearchName[i],len(img_file_name_list)))
for j in range(0,len(img_file_name_list)-1):
n=os.path.join("./test/"+SearchName[i]+"/",img_file_name_list[j])
img = cv2.imread(n)
if img is None:
print('image' + str(j) + ':NoImage')
continue
else:
r,g,b = cv2.split(img)
img = cv2.merge([r,g,b])
X_test.append(img)
Y_test.append(i)
X_train=np.array(X_train)
X_test=np.array(X_test)
y_train = to_categorical(Y_train)
y_test = to_categorical(Y_test)
model = Sequential()
model.add(Conv2D(input_shape=input_shape, filters=32,kernel_size=(3, 3),
strides=(1, 1), padding="same"))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(filters=32, kernel_size=(3, 3),
strides=(1, 1), padding="same"))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(filters=32, kernel_size=(3, 3),
strides=(1, 1), padding="same"))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Flatten())
model.add(Dense(256))
model.add(Activation("sigmoid"))
model.add(Dense(128))
model.add(Activation('sigmoid'))
---分類したい人数を入れる---
model.add(Dense(len(SearchName)))
model.add(Activation('softmax'))
---コンパイル---
model.compile(optimizer='sgd',
loss='categorical_crossentropy',
metrics=['accuracy'])
history = model.fit(X_train, y_train, batch_size=70,
epochs=50, verbose=1, validation_data=(X_test, y_test))
---汎化制度の評価・表示---
score = model.evaluate(X_test, y_test, batch_size=32, verbose=0)
print('validation loss:{0[0]}\nvalidation accuracy:{0[1]}'.format(score))
---acc, val_accのプロット---
plt.plot(history.history["accuracy"], label="accuracy", ls="-", marker="o")
plt.plot(history.history["val_accuracy"], label="val_accuracy", ls="-", marker="x")
plt.ylabel("accuracy")
plt.xlabel("epoch")
plt.legend(loc="best")
plt.show()
---モデルを保存---
model.save("MyModel.h5")
.
.
.
.
.
.
.
結果が以下になります
.
.
.
.
.
.
.
ImportError Traceback (most recent call last)
C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\pywrap_tensorflow.py in <module>
57
---> 58 from tensorflow.python.pywrap_tensorflow_internal import *
59
C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py in <module>
27 return _mod
---> 28 _pywrap_tensorflow_internal = swig_import_helper()
29 del swig_import_helper
C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py in swig_import_helper()
23 try:
---> 24 _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description)
25 finally:
C:\ProgramData\Anaconda3\lib\imp.py in load_module(name, file, filename, details)
241 else:
--> 242 return load_dynamic(name, filename, file)
243 elif type_ == PKG_DIRECTORY:
C:\ProgramData\Anaconda3\lib\imp.py in load_dynamic(name, path, file)
341 name=name, loader=loader, origin=path)
--> 342 return _load(spec)
343
ImportError: DLL load failed: 指定されたモジュールが見つかりません。
During handling of the above exception, another exception occurred:
ImportError Traceback (most recent call last)
C:\ProgramData\Anaconda3\lib\site-packages\keras_init_.py in <module>
2 try:
----> 3 from tensorflow.keras.layers.experimental.preprocessing import RandomRotation
4 except ImportError:
C:\ProgramData\Anaconda3\lib\site-packages\tensorflow_init_.py in <module>
40
---> 41 from tensorflow.python.tools import module_util as _module_util
42 from tensorflow.python.util.lazy_loader import LazyLoader as _LazyLoader
C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python_init_.py in <module>
49
---> 50 from tensorflow.python import pywrap_tensorflow
51
C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\pywrap_tensorflow.py in <module>
68 above this error message when asking for help.""" % traceback.format_exc()
---> 69 raise ImportError(msg)
70
ImportError: Traceback (most recent call last):
File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 58, in <module>
from tensorflow.python.pywrap_tensorflow_internal import *
File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 28, in <module>
_pywrap_tensorflow_internal = swig_import_helper()
File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 24, in swig_import_helper
_mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description)
File "C:\ProgramData\Anaconda3\lib\imp.py", line 242, in load_module
return load_dynamic(name, filename, file)
File "C:\ProgramData\Anaconda3\lib\imp.py", line 342, in load_dynamic
return _load(spec)
ImportError: DLL load failed: 指定されたモジュールが見つかりません。
Failed to load the native TensorFlow runtime.
See https://www.tensorflow.org/install/errors
for some common reasons and solutions. Include the entire stack trace
above this error message when asking for help.
During handling of the above exception, another exception occurred:
ImportError Traceback (most recent call last)
<ipython-input-4-62c0e9c49cfc> in <module>
1 from future import print_function
----> 2 from keras.utils.np_utils import to_categorical
3 from keras.layers import Activation, Conv2D, Dense, Flatten, MaxPooling2D
4 from keras.models import Sequential
5 import numpy as np
C:\ProgramData\Anaconda3\lib\site-packages\keras_init_.py in <module>
4 except ImportError:
5 raise ImportError(
----> 6 'Keras requires TensorFlow 2.2 or higher. '
7 'Install TensorFlow via pip install tensorflow
')
8
ImportError: Keras requires TensorFlow 2.2 or higher. Install TensorFlow via pip install tensorflow