import os
os.environ["KERAS_BACKEND"] = "torch"
os.environ["CUDA_VISIBLE_DEVICES"] = ""
import keras
import numpy as np
import torch
torch.set_num_threads(1)
keras.utils.set_random_seed(2027)
import matplotlib.pyplot as plt
# 외부 사진 파일 없이 색상과 윤곽선이 있는 입력을 만듭니다.
image = np.zeros((224, 224, 3), dtype="float32")
image[40:180, 60:160] = [220, 140, 80]
image[80:140, 20:200, 1] = 240
model = keras.applications.VGG16(weights="imagenet", include_top=False)
conv_layers = [layer for layer in model.layers if "conv" in layer.name]
activation_model = keras.Model(model.input, [layer.output for layer in conv_layers])
inputs = keras.applications.vgg16.preprocess_input(image[None].copy())
activations = activation_model.predict(inputs, verbose=0)
for layer, activation in zip(conv_layers, activations):
print(layer.name, activation.shape)
# 첫 8개 채널을 비교합니다. 상수 채널도 0으로 안전하게 정규화합니다.
fig, axes = plt.subplots(1, 8, figsize=(12, 2))
for channel, ax in enumerate(axes):
values = activation[0, :, :, channel]
values = (values - values.mean()) / (values.std() + 1e-8)
ax.imshow(values, cmap="viridis"); ax.axis("off")
fig.suptitle(layer.name); plt.show(); plt.close(fig)