Windows環境下におけるTensorlow実行時に発生する 'Call to CreateProcess failed. Error code: 2' に関しての質問
解決したいこと
まずは質問を閲覧してくださりありがとうございます。
Windows環境下におけるAnaconda仮想環境においてTensorflowによるDeeplearningを実行しようとしたところ、
表題のように Call to CreateProcess failed. Error code: 2 が発生しました。
Deeplearning自体は実行できているのですが、その後に保存した重みを用いてGrad Camを行ったところ、適切なヒートマップが表示されなくて困っています。
従って、質問として以下の2点を挙げさせていただきます。
1)Call to CreateProcess failed. Error code: 2 の原因または解決策
2)Grad camにおけるヒートマップが機能していない(すべて均一のインテンシティで表示されている)問題の原因または解決策
また、開発環境などはこのようになっています。
OS:Windows10
GPU:RTX3080
環境:Anaconda仮想環境
ライブラリ等バージョン:
Python3.7
Tensor2.4
Cuda11.1
CuDnn8
環境の構築は参考文献(https://medium.com/analytics-vidhya/install-tensorflow-gpu-2-4-0-with-cuda-11-0-and-cudnn-8-using-anaconda-8c6472c9653f)
をもとに行いました。
1)に関しては以下のようなエラーコードがでていますが、ACC・Lossの値が変動・収束していることからDeeplearningの処理自体はできているように思えます。
2021-03-22 13:02:37.319063: E tensorflow/core/platform/windows/subprocess.cc:283] Call to CreateProcess failed. Error code: 2
2021-03-22 13:02:37.321041: E tensorflow/core/platform/windows/subprocess.cc:283] Call to CreateProcess failed. Error code: 2
2021-03-22 13:02:37.322864: E tensorflow/core/platform/windows/subprocess.cc:283] Call to CreateProcess failed. Error code: 2
2021-03-22 13:02:37.324809: E tensorflow/core/platform/windows/subprocess.cc:283] Call to CreateProcess failed. Error code: 2
2021-03-22 13:02:37.326522: E tensorflow/core/platform/windows/subprocess.cc:283] Call to CreateProcess failed. Error code: 2
2021-03-22 13:02:37.328371: E tensorflow/core/platform/windows/subprocess.cc:283] Call to CreateProcess failed. Error code: 2
また、ソースコードはこのようになっています。
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 15 20:36:36 2021
@author: Server2021
"""
import tensorflow as tf
# ヘルパーライブラリのインポート
import numpy as np
import matplotlib.pyplot as plt
import numpy as np
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
import os
import re
import glob
def list_pictures(directory, ext='jpg|jpeg|bmp|png|ppm'):
return [os.path.join(root, f)
for root, _, files in os.walk(directory) for f in files
if re.match(r'([\w]+\.(?:' + ext + '))', f.lower())]
from tensorflow.keras import layers, models
gpus = tf.config.experimental.list_physical_devices('GPU')
if gpus:
# Restrict TensorFlow to only allocate 1GB of memory on the first GPU
try:
tf.config.experimental.set_virtual_device_configuration(
gpus[0],
[tf.config.experimental.VirtualDeviceConfiguration(memory_limit=1024*5)])
logical_gpus = tf.config.experimental.list_logical_devices('GPU')
print(len(gpus), "Physical GPUs,", len(logical_gpus), "Logical GPUs")
except RuntimeError as e:
# Virtual devices must be set before GPUs have been initialized
print(e)
X = []
Y = []
files1 = glob.glob('C:/Users/File/*.bmp')
for picture in files1:
img = tf.keras.preprocessing.image.img_to_array(tf.keras.preprocessing.image.load_img(picture, target_size=(200,200)))
X.append(img)
Y.append(0)
# 画像2
files2 = glob.glob('C:/Users/File/*.bmp')
for picture in files2:
img = tf.keras.preprocessing.image.img_to_array(tf.keras.preprocessing.image.load_img(picture, target_size=(200,200)))
X.append(img)
Y.append(1)
# 画像3
files3 = glob.glob('C:/Users/File/*.bmp')
for picture in files3:
img = tf.keras.preprocessing.image.img_to_array(tf.keras.preprocessing.image.load_img(picture, target_size=(200,200)))
X.append(img)
Y.append(2)
# 画像4
files4 = glob.glob('C:/Users/File*.bmp')
for picture in files2:
img = tf.keras.preprocessing.image.img_to_array(tf.keras.preprocessing.image.load_img(picture, target_size=(200,200)))
X.append(img)
Y.append(3)
# 行列に変換
X = np.asarray(X)
Y = np.asarray(Y)
# 画素値を0から1の範囲に変換(正規化)
X = X.astype('float32')
X = X / 255.0
# クラスの形式を変換
Y = tf.keras.utils.to_categorical(Y, 4)
# 学習用データとテストデータを総データから分ける
X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.2, random_state=128)
model = models.Sequential()
model.add(layers.Conv2D(32, (5, 5), activation='relu', input_shape=(200, 200, 3)))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Dropout(0.3))
model.add(layers.Conv2D(32, (5, 5), activation='relu'))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
model.add(layers.Dropout(0.3))
model.add(layers.Flatten())
model.add(layers.Dense(64, activation='relu'))
model.add(layers.Dense(4, activation='softmax'))
model.compile(optimizer='adam',
loss='categorical_crossentropy',
metrics=['accuracy'])
history = model.fit(X_train, y_train, batch_size = 24, epochs=50,
validation_data = (X_test, y_test), verbose = 0)
test_loss, test_acc = model.evaluate(X_test, y_test, verbose=2)
print('\nTest accuracy:', test_acc)
print(model.evaluate(X_test, y_test))
plt.plot(history.history['accuracy'])
plt.plot(history.history['val_accuracy'])
plt.title('model accuracy')
plt.xlabel('epoch')
plt.ylabel('accuracy')
plt.legend(['acc', 'val_acc'], loc='lower right')
plt.show()
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('Model loss')
plt.ylabel('Loss')
plt.xlabel('Epoch')
plt.legend(['Train', 'Test'], loc='upper right')
plt.show()
model.summary()
model.save('C:/Users/File/4class.h5')
また、2)に関してのソースコードは以下になります。エラーとしては1)が起きた後にヒートマップ作製がうまくいかないようになります。(画像自体は出力される)
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 17 13:45:05 2021
@author: Server2021
"""
import cv2
import numpy as np
import tensorflow as tf
gpus = tf.config.experimental.list_physical_devices('GPU')
if gpus:
# Restrict TensorFlow to only allocate 1GB of memory on the first GPU
try:
tf.config.experimental.set_virtual_device_configuration(
gpus[0],
[tf.config.experimental.VirtualDeviceConfiguration(memory_limit=1024*5)])
logical_gpus = tf.config.experimental.list_logical_devices('GPU')
print(len(gpus), "Physical GPUs,", len(logical_gpus), "Logical GPUs")
except RuntimeError as e:
# Virtual devices must be set before GPUs have been initialized
print(e)
IMAGE_PATH ='C:/Users/File/1.bmp'
LAYER_NAME = 'conv2d_5'
CAT_CLASS_INDEX = 3
img = tf.keras.preprocessing.image.load_img(IMAGE_PATH, target_size=(200, 200))
img = tf.keras.preprocessing.image.img_to_array(img)
model = tf.keras.models.load_model('C:/Users/File/4class.h5')
grad_model = tf.keras.models.Model([model.inputs], [model.get_layer(LAYER_NAME).output, model.output])
with tf.GradientTape() as tape:
conv_outputs, predictions = grad_model(np.array([img]))
loss = predictions[:, CAT_CLASS_INDEX]
output = conv_outputs[0]
grads = tape.gradient(loss, conv_outputs)[0]
gate_f = tf.cast(output > 0, 'float32')
gate_r = tf.cast(grads > 0, 'float32')
guided_grads = tf.cast(output > 0, 'float32') * tf.cast(grads > 0, 'float32') * grads
weights = tf.reduce_mean(guided_grads, axis=(0, 1))
cam = np.ones(output.shape[0: 2], dtype = np.float32)
for i, w in enumerate(weights):
cam += w * output[:, :, i]
cam = cv2.resize(cam.numpy(), (200, 200))
cam = np.maximum(cam, 0)
heatmap = (cam - cam.min()) / (cam.max() - cam.min())
cam = cv2.applyColorMap(np.uint8(255*heatmap), cv2.COLORMAP_JET)
output_image = cv2.addWeighted(cv2.cvtColor(img.astype('uint8'), cv2.COLOR_RGB2BGR), 0.5, cam, 1, 0)
cv2.imwrite('C:/Users/File', output_image)
自分で試したこと
以下の2点を試しましたが効果はありませんでした。
・環境及び端末自体の再起動
・仮想環境の再構成(中身の構成は同一)
・Tensorflowアンインストール➡インストール
Pathが通っていない・・・?のかとおもいましたが、自分の力ではどのようにすればよいのかわからなかったため質問させていただきました。
追記なども可能ですので、憶測で構いませんのでコメントお願いします。