前提・実現したいこと
初心者の質問となります。ご容赦ください。
今回、趣味で初めてAIのプログラミングを作成しようと思い、とあるサイトを拝見しながら進めておりました。
そこで、以下のようなメッセージが発生し、混乱しております。
発生している問題・エラーメッセージ
2021-12-16 21:29:41.599768: I tensorflow/core/platform/cpu_feature_guard.cc:151] This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN) to use the following CPU instructions in performance-critical operations: AVX AVX2
To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags.
2021-12-16 21:29:42.112226: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1525] Created device /job:localhost/replica:0/task:0/device:GPU:0 with 2151 MB memory: -> device: 0, name: NVIDIA GeForce GTX 1650, pci bus id: 0000:01:00.0, compute capability: 7.5
C:\Users\kita3\AppData\Local\Programs\Python\Python38\lib\site-packages\keras\optimizer_v2\adam.py:105: UserWarning: The lr
argument is deprecated, use learning_rate
instead.
super(Adam, self).init(name, **kwargs)
Found 250 images belonging to 2 classes.
Found 106 images belonging to 2 classes.
data batch shape: (1, 256, 256, 1)
labels batch shape: (1,)
class weight: {0: 1.0, 1: 7.68}
Epoch 1/100
2021-12-16 21:29:52.728238: W tensorflow/core/common_runtime/bfc_allocator.cc:462] Allocator (GPU_0_bfc) ran out of memory trying to allocate 676.00MiB (rounded to 708837376)requested by op Fill
If the cause is memory fragmentation maybe the environment variable 'TF_GPU_ALLOCATOR=cuda_malloc_async' will improve the situation.
Current allocation summary follows.
Current allocation summary follows.
一部省略
2021-12-16 21:29:52.848758: I tensorflow/core/common_runtime/bfc_allocator.cc:1080] total_region_allocated_bytes_: 2255958784 memory_limit_: 2255958836 available bytes: 52 curr_region_allocation_bytes_: 4511918080
2021-12-16 21:29:52.849160: I tensorflow/core/common_runtime/bfc_allocator.cc:1086] Stats:
Limit: 2255958836
InUse: 1565999872
MaxInUse: 2233994496
NumAllocs: 99
MaxAllocSize: 800602880
Reserved: 0
PeakReserved: 0
LargestFreeBlock: 0
2021-12-16 21:29:52.849383: W tensorflow/core/common_runtime/bfc_allocator.cc:474] **********************************______________________________********************************xxxx
2021-12-16 21:29:52.850154: W tensorflow/core/framework/op_kernel.cc:1745] OP_REQUIRES failed at constant_op.cc:175 : RESOURCE_EXHAUSTED: OOM when allocating tensor with shape[346112,512] and type float on /job:localhost/replica:0/task:0/device:GPU:0 by allocator GPU_0_bfc
Traceback (most recent call last):
File "stock_ai.py", line 92, in <module>
history = model.fit(
File "C:\Users\コンピュータ名\AppData\Local\Programs\Python\Python38\lib\site-packages\keras\utils\traceback_utils.py", line 67, in error_handler
raise e.with_traceback(filtered_tb) from None
File "C:\Users\コンピュータ名\AppData\Local\Programs\Python\Python38\lib\site-packages\tensorflow\python\framework\func_graph.py", line 1129, in autograph_handler
raise e.ag_error_metadata.to_exception(e)
tensorflow.python.framework.errors_impl.ResourceExhaustedError: in user code:
File "C:\Users\コンピュータ名\AppData\Local\Programs\Python\Python38\lib\site-packages\keras\engine\training.py", line 878, in train_function * return step_function(self, iterator) File "C:\Users\コンピュータ名\AppData\Local\Programs\Python\Python38\lib\site-packages\keras\engine\training.py", line 867, in step_function ** outputs = model.distribute_strategy.run(run_step, args=(data,)) File "C:\Users\コンピュータ名\AppData\Local\Programs\Python\Python38\lib\site-packages\keras\engine\training.py", line 860, in run_step ** outputs = model.train_step(data) File "C:\Users\コンピュータ名\AppData\Local\Programs\Python\Python38\lib\site-packages\keras\engine\training.py", line 816, in train_step self.optimizer.minimize(loss, self.trainable_variables, tape=tape) File "C:\Users\コンピュータ名\AppData\Local\Programs\Python\Python38\lib\site-packages\keras\optimizer_v2\optimizer_v2.py", line 532, in minimize return self.apply_gradients(grads_and_vars, name=name) File "C:\Users\コンピュータ名\AppData\Local\Programs\Python\Python38\lib\site-packages\keras\optimizer_v2\optimizer_v2.py", line 639, in apply_gradients self._create_all_weights(var_list) File "C:\Users\コンピュータ名\AppData\Local\Programs\Python\Python38\lib\site-packages\keras\optimizer_v2\optimizer_v2.py", line 830, in _create_all_weights self._create_slots(var_list) File "C:\Users\コンピュータ名\AppData\Local\Programs\Python\Python38\lib\site-packages\keras\optimizer_v2\adam.py", line 119, in _create_slots self.add_slot(var, 'v') File "C:\Users\コンピュータ名\AppData\Local\Programs\Python\Python38\lib\site-packages\keras\optimizer_v2\optimizer_v2.py", line 916, in add_slot weight = tf.Variable( File "C:\Users\コンピュータ名\AppData\Local\Programs\Python\Python38\lib\site-packages\keras\initializers\initializers_v2.py", line 144, in __call__ return tf.zeros(shape, dtype) ResourceExhaustedError: OOM when allocating tensor with shape[346112,512] and type float on /job:localhost/replica:0/task:0/device:GPU:0 by allocator GPU_0_bfc [Op:Fill]
該当のソースコード
from tensorflow.keras import layers
from tensorflow.keras import models
from tensorflow.keras import optimizers
from tensorflow.keras.callbacks import ModelCheckpoint
from tensorflow.keras.preprocessing.image import ImageDataGenerator
import matplotlib.pyplot as plt
import os
import math
data_dir = 'data/chart' #データフォルダの名前
base_dir = "data/" #ログ出力用
def_batch_size = 1 #バッチサイズ
def weight(classes_name, dir_name):
data_element_num = {}
max_buf = 0
for class_name in classes_name:
class_dir = dir_name + os.sep + class_name
files = os.listdir(class_dir)
data_element_num[class_name] = len(files)
if max_buf < len(files):
max_buf = len(files)
weights = {}
count = 0
for class_name in classes_name:
weights[count] = round(float(math.pow(data_element_num[class_name]/max_buf, -1)), 2)
count = count + 1
return weights
model = models.Sequential()
model.add(layers.Conv2D(32, (3, 3), activation='relu',
input_shape=(256, 256, 1)))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
model.add(layers.Conv2D(128, (3, 3), activation='relu'))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Dropout(0.5))
model.add(layers.Conv2D(256, (3, 3), activation='relu'))
model.add(layers.Conv2D(512, (3, 3), activation='relu'))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Dropout(0.5))
model.add(layers.Conv2D(512, (3, 3), activation='relu'))
model.add(layers.Flatten())
model.add(layers.Dense(512, activation='relu'))
model.add(layers.Dropout(0.5))
model.add(layers.Dense(1, activation='sigmoid'))
model.compile(loss='binary_crossentropy',
optimizer=optimizers.Adam(lr=1e-4),
metrics=['acc'])
datagen = ImageDataGenerator(validation_split=0.3, rescale=1./255)
train_generator = datagen.flow_from_directory(
data_dir,
batch_size=def_batch_size,
class_mode='binary',
target_size=(256, 256),
color_mode='grayscale',
subset='training')
validation_generator = datagen.flow_from_directory(
data_dir,
batch_size=def_batch_size,
class_mode='binary',
target_size=(256, 256),
color_mode='grayscale',
subset='validation')
for data_batch, labels_batch in train_generator:
print('data batch shape:', data_batch.shape)
print('labels batch shape:', labels_batch.shape)
break
fpath = base_dir + 'chart.{epoch:02d}.h5'
modelCheckpoint = ModelCheckpoint(filepath = fpath,
monitor='val_loss',
verbose=1,
save_best_only=True,
save_weights_only=False,
mode='min',
save_freq='epoch')
class_weights = weight(classes_name = ['down', 'up'], dir_name = data_dir)
print('class weight:', class_weights)
history = model.fit(
train_generator,
steps_per_epoch=train_generator.samples // def_batch_size,
validation_data = validation_generator,
epochs = 100,
validation_steps=validation_generator.samples // def_batch_size,
class_weight=class_weights,
callbacks=[modelCheckpoint])
acc = history.history['acc']
val_acc = history.history['val_acc']
loss = history.history['loss']
val_loss = history.history['val_loss']
epochs = range(len(acc))
fig = plt.figure()
plt.plot(epochs, acc, 'bo', label='Training acc')
plt.plot(epochs, val_acc, 'b', label='Validation acc')
plt.title('Training and validation accuracy')
plt.legend()
plt.savefig(base_dir + 'accuracy.png')
plt.close()
fig = plt.figure()
plt.plot(epochs, loss, 'bo', label='Training loss')
plt.plot(epochs, val_loss, 'b', label='Validation loss')
plt.title('Training and validation loss')
plt.legend()
plt.savefig(base_dir + 'loss.png')
plt.close()
試したこと
同様のメッセージが出ているかの検索
→ResourceExhaustedError の部分に問題を感じております。
ソースコード内の変更がございましたらご教授いただきたいです。
Batch sizeの変更方法もご教授いただきたいです。
補足情報(FW/ツールのバージョンなど)
Winows 11
python --version: 3.8.6
CUDA 11.5
TensorFlow 2.7.0
NVIDIA グラフィックスドライバー 497.09
稚拙な文になり申し訳ないです。
よろしくお願いいたします。