Список работ

Атака на нейронную сеть

Содержание

Примеры атак на НС

В [1 и 2] приводится пример, в котором после незначительного изменения изображения (рис. 1 и 2) нейронная сеть (НС) GoogLeNet, обученная на ImageNet [3], начинает неверно классифицировать измененное изображение, хотя визуально оно практически неотличимо от исходного.

panda two

Рис. 1. Исходное (слева) и измененное изображения

Иное название GoogLeNet – Inception V1 [4]. Эта НС (рис. 2 и 3) включает начальные модули (inception modules).

Inception

Рис. 2. Начальный модуль GoogLeNet.

Inception_

Рис. 3. Начальный модуль GoogLeNet с уменьшением размерности.

Подобные изменения приводят в качестве примеров успешной атаки на НС.
В [2] показан пример успешной атаки на НС AlexNet [5], так же обученной на ImageNet: после изменения одного пикселя изображения эта НС меняет свой прогноз (рис .4).

One pixel

Рис. 4. Однопиксельные атаки на AlexNet

Атака НС, обученных на ImageNet (разд. 2), выполняется с применением изображения, показанного на рис. 5 справа.

Cups

Рис. 5. Исходное и атакующее изображения

Такие атаки, однако, эффективные для одной НС проходят совершенно бесследно для НС с другой архитектурой.
Один из способов сделать атаки более универсальными – это применение атакующих шумов [6]. Примеры таких шумов, взятые из [6], приведены на рис. 6.

Noises

Рис. 6. Примеры атакующих шумов:
а – AlexNet; б – VGG19; в – ResNet152; г – DenseNet; д – GoogLeNet; е – MobileNet; ж – VGG11; з – ResNet18.

Визуально исходное и зашумленные изображения малоразличимы, но точность классификации зашумленных изображений существенно ниже, чем исходных [6].
Пример употребления шума при подготовке атаки удачной на НС AlexNet [7] показан на рис. 7.

Alex noise

Рис. 7. Пример употребления шума для атаки удачной на AlexNet

Эффективность атак на НС, обученных на ImageNet

Проверяется, насколько токсичны зашумленные изображения (табл. 1), приведенные на рис. 1, 5 и 7 для следующих обученных на ImageNet НС:

Прогноз НС выводит программа, приведенная в прил.

Таблица 1. Прогнозы НС

НСПрогнозы для изображений
ИсходноеЗашумленное
ПрогнозВесПрогнозВес
Панда
Xceptiongiant_panda0.8934532giant_panda0.8685231
indri0.006895099indri0.012549218
VGG16giant_panda0.29531986giant_panda0.49855888
gibbon0.20835872toy_poodle0.12609173
VGG19giant_panda0.9475259giant_panda0.85687333
gibbon0.01658522indri0.07732392
ResNet50giant_panda0.99900997giant_panda0.9984341
indri0.0004465563indri0.00094144914
ResNet101giant_panda0.9800418giant_panda0.928511
toy_poodle0.004540715indri0.030445982
ResNet152giant_panda0.9794937giant_panda0.98116606
indri0.019208707indri0.017197827
ResNet50V2giant_panda0.9999914giant_panda0.999948
indri5.141379e-06indri2.7761647e-05
ResNet101V2giant_panda0.9999256giant_panda0.99954647
indri7.1417715e-05indri0.0004399426
ResNet152V2giant_panda0.99737144giant_panda0.9877182
indri0.0019275275indri0.010348079
InceptionV3giant_panda0.78640085giant_panda0.69644904
indri0.0059863715indri0.009347004
InceptionResNetV2giant_panda0.87451833giant_panda0.88990486
indri0.0035678335indri0.0034128423
MobileNetgiant_panda0.9963903giant_panda0.9833499
indri0.00154353indri0.0147644915
MobileNetV2giant_panda0.91432685giant_panda0.9175715
indri0.004121284indri0.0028103911
DenseNet121giant_panda0.6411652giant_panda0.35457098
gibbon0.16831161gibbon0.27123645
DenseNet169giant_panda0.99348277giant_panda0.9934942
gibbon0.0014070828indri0.0043741534
DenseNet201giant_panda0.86581695giant_panda0.89746433
indri0.03975411indri0.031577703
NASNetMobilegiant_panda0.9232004giant_panda0.91260135
indri0.001689267indri0.0022836388
NASNetLargegiant_panda0.9162965giant_panda0.910803
lesser_panda0.0013859468lesser_panda0.0012689099
ConvNeXtTinygiant_panda0.83502537giant_panda0.81756246
indri0.004105052indri0.014787479
ConvNeXtSmallgiant_panda0.8786456giant_panda0.8769419
indri0.0034498249indri0.004605325
ConvNeXtLargegiant_panda0.9321051giant_panda0.932334
lesser_panda0.0033918915lesser_panda0.002519659
ConvNeXtXLargegiant_panda0.95751643giant_panda0.95650977
lesser_panda0.0048588356lesser_panda0.005052445
EfficientNetB0giant_panda0.7300266giant_panda0.6690231
indri0.032585632indri0.029188804
EfficientNetB1giant_panda0.950511giant_panda0.9585726
gibbon0.005032844lesser_panda0.0034036357
EfficientNetB2giant_panda0.54397595giant_panda0.8525239
lesser_panda0.0942573lesser_panda0.010274735
EfficientNetB3giant_panda0.5946984giant_panda0.71859056
indri0.06545867indri0.055300258
EfficientNetB4giant_panda0.6508244giant_panda0.6376153
gibbon0.025846625gibbon0.020103889
EfficientNetB5giant_panda0.81070524giant_panda0.79697144
lesser_panda0.008972366indri0.014907344
EfficientNetB6giant_panda0.83647615giant_panda0.82969284
indri0.009402118indri0.015815089
EfficientNetB7giant_panda0.8115224giant_panda0.80586946
lesser_panda0.0040551303lesser_panda0.002662837
EfficientNetV2B0giant_panda0.8198102giant_panda0.78598225
lesser_panda0.006843959indri0.007068597
EfficientNetV2B1giant_panda0.905874giant_panda0.87956053
lesser_panda0.010039191indri0.010512123
EfficientNetV2B2giant_panda0.87766695giant_panda0.8547733
indri0.0064418796indri0.014298057
EfficientNetV2B3giant_panda0.9379393giant_panda0.9322769
lesser_panda0.0024651065lesser_panda0.0024217644
EfficientNetV2Sgiant_panda0.870769giant_panda0.84205574
indri0.007501943indri0.016715052
EfficientNetV2Mgiant_panda0.72141683giant_panda0.6123171
indri0.03916026indri0.09327198
EfficientNetV2Lgiant_panda0.8231075giant_panda0.7771141
indri0.007467236indri0.016257575
Чаша с бульоном
Xceptionconsomme0.4769622eggnog0.26429173
eggnog0.369737consomme0.20811778
VGG16espresso0.29913118eggnog0.4284617
eggnog0.28693104espresso0.09198572
VGG19eggnog0.40479746eggnog0.55078036
espresso0.14222756candle0.13904397
ResNet50eggnog0.610125eggnog0.73905134
consomme0.19917005candle0.1121889
ResNet101eggnog0.44710666candle0.9581977
espresso0.26310477eggnog0.023749026
ResNet152eggnog0.49946448candle0.5919975
consomme0.29502374eggnog0.37803417
ResNet50V2consomme0.7435905consomme0.55259335
espresso0.09107772candle0.2439611
ResNet101V2eggnog0.69917256eggnog0.42238367
espresso0.17949456consomme0.1465741
ResNet152V2consomme0.56592834consomme0.42126563
eggnog0.35111922eggnog0.28072673
InceptionV3eggnog0.8450097eggnog0.8930665
consomme0.10611778consomme0.046935618
InceptionResNetV2eggnog0.61004436eggnog0.8671397
consomme0.25859842consomme0.059002116
MobileNeteggnog0.3772939consomme0.36373577
consomme0.3723965candle0.30248508
MobileNetV2eggnog0.74664634eggnog0.818449
consomme0.19889948consomme0.110172115
DenseNet121eggnog0.6716637eggnog0.7523846
consomme0.15843609consomme0.04910938
DenseNet169eggnog0.6745572eggnog0.80882406
consomme0.21082787consomme0.08539948
DenseNet201eggnog0.5806987eggnog0.5637367
consomme0.37859577consomme0.22350387
NASNetMobileconsomme0.37425083consomme0.5366754
eggnog0.28989267eggnog0.1794022
NASNetLargeeggnog0.8903488eggnog0.9094321
cup0.0048674275consomme0.0049209073
ConvNeXtTinyeggnog0.77363735eggnog0.8174946
soup_bowl0.05341066cup0.032327835
ConvNeXtSmalleggnog0.7953768eggnog0.71390885
consomme0.046404447cup0.068947665
ConvNeXtLargeeggnog0.64079994eggnog0.4498356
soup_bowl0.13861178consomme0.15918107
ConvNeXtXLargeeggnog0.6320851consomme0.36625546
consomme0.19811822eggnog0.31976825
EfficientNetB0eggnog0.3809768eggnog0.6290149
consomme0.14101312consomme0.078249924
EfficientNetB1eggnog0.60376394eggnog0.41322622
consomme0.11916207candle0.3276879
EfficientNetB2eggnog0.34833598eggnog0.44046506
espresso0.16403706espresso0.10790814
EfficientNetB3eggnog0.28097656eggnog0.6935557
soup_bowl0.23056771consomme0.094831824
EfficientNetB4eggnog0.4320463eggnog0.33854678
consomme0.21700177consomme0.2933674
EfficientNetB5eggnog0.27524996eggnog0.6045266
consomme0.2478749consomme0.17794715
EfficientNetB6eggnog0.27092734eggnog0.47768772
consomme0.1779286consomme0.18869795
EfficientNetB7consomme0.25540447eggnog0.44616348
soup_bowl0.18963791consomme0.304498
EfficientNetV2B0eggnog0.7116632eggnog0.7732018
consomme0.13334379consomme0.057252146
EfficientNetV2B1eggnog0.62781626eggnog0.64746225
consomme0.10121088candle0.16391389
EfficientNetV2B2eggnog0.24424511eggnog0.28804588
soup_bowl0.19228119cup0.17587207
EfficientNetV2B3eggnog0.5526559eggnog0.6179782
consomme0.16055174consomme0.13450757
EfficientNetV2Seggnog0.78391105eggnog0.52456164
consomme0.05584524consomme0.22690299
EfficientNetV2Meggnog0.64184594eggnog0.44421917
consomme0.07962157cup0.031200623
EfficientNetV2Leggnog0.46971226eggnog0.5862437
consomme0.24500662consomme0.08160363
Птица (rbs – red-backed_sandpiper)
Xceptionrbs0.9373782rbs0.9421061
dowitcher0.0009936722dowitcher0.006671094
VGG16rbs0.99296546rbs0.95829177
dowitcher0.0065512755dowitcher0.034031138
VGG19rbs0.98258233rbs0.76117235
dowitcher0.015454282brambling0.1649745
ResNet50rbs0.9945057rbs0.8463953
dowitcher0.004733121dowitcher0.11212878
ResNet101rbs0.99510777rbs0.70046127
dowitcher0.003608791dowitcher0.26891673
ResNet152rbs0.9982114rbs0.97655004
dowitcher0.0013238922dowitcher0.014266697
ResNet50V2rbs0.9906026rbs0.98387384
dowitcher0.008500421dowitcher0.014791488
ResNet101V2rbs0.9997391rbs0.9987062
dowitcher0.00020983515dowitcher0.0012432294
ResNet152V2rbs0.9999851rbs0.9999176
dowitcher1.9361084e-06dowitcher5.1032715e-05
InceptionV3rbs0.92500746rbs0.9272541
dowitcher0.00485395dowitcher0.017696658
InceptionResNetV2rbs0.9272363rbs0.93487924
dowitcher0.0016747853dowitcher0.002409931
MobileNetrbs0.97926563rbs0.97908795
dowitcher0.018759424dowitcher0.011371828
MobileNetV2rbs0.8973367rbs0.72216326
ruddy_turnstone0.015419056dowitcher0.09924709
DenseNet121rbs0.97185004rbs0.65919155
dowitcher0.026844697dowitcher0.32818854
DenseNet169rbs0.9965913rbs0.8583146
dowitcher0.0029490215dowitcher0.13460773
DenseNet201rbs0.994795rbs0.98502433
dowitcher0.0028738263dowitcher0.009322146
NASNetMobilerbs0.92656285rbs0.87028766
dowitcher0.0076086614dowitcher0.022089344
NASNetLargerbs0.9210256rbs0.8988672
dowitcher0.0018086635dowitcher0.016565517
ConvNeXtTinyrbs0.8871051rbs0.80185235
dowitcher0.004807195dowitcher0.0050164973
ConvNeXtSmallrbs0.90524435rbs0.8725227
dowitcher0.0026886899crossword_puzzle0.006224967
ConvNeXtSmallrbs0.90524435rbs0.8725227
dowitcher0.0026886899crossword_puzzle0.006224967
ConvNeXtLargerbs0.9365929rbs0.9214403
dowitcher0.00709174dowitcher0.009951768
ConvNeXtXLargerbs0.9616423rbs0.9498634
dowitcher0.0026674685dowitcher0.005683166
EfficientNetB0rbs0.9329818rbs0.9495701
ruddy_turnstone0.006443314dowitcher0.015777139
EfficientNetB1rbs0.9059463rbs0.90166867
dowitcher0.0063025053dowitcher0.011085955
EfficientNetB2rbs0.9058235rbs0.88913435
dowitcher0.0013199622dowitcher0.013959255
EfficientNetB3rbs0.9134904rbs0.9149238
dowitcher0.0019892226dowitcher0.0055353707
EfficientNetB4rbs0.75999826rbs0.7595083
dowitcher0.0016400524dowitcher0.00415613
EfficientNetB5rbs0.86962rbs0.858953
dowitcher0.0044280756dowitcher0.010272025
EfficientNetB6rbs0.7415047rbs0.77854013
dowitcher0.004406076dowitcher0.007087492
EfficientNetB7rbs0.80603844rbs0.7811539
dowitcher0.005759541dowitcher0.008795305
EfficientNetV2B0rbs0.9352422rbs0.9352263
ruddy_turnstone0.0026096187dowitcher0.0038579428
EfficientNetV2B1rbs0.94026804rbs0.94414705
dowitcher0.006028206dowitcher0.012713395
EfficientNetV2B2rbs0.93339777rbs0.9421321
dowitcher0.0029742066dowitcher0.006107013
EfficientNetV2B3rbs0.9359722rbs0.92271745
dowitcher0.001212289dowitcher0.0030449282
EfficientNetV2Srbs0.8817812rbs0.89386517
dowitcher0.0042605316dowitcher0.006788064
EfficientNetV2Mrbs0.70686203rbs0.4808183
dowitcher0.009289558dowitcher0.011369884
EfficientNetV2Lrbs0.6183409rbs0.68018055
dowitcher0.011672224dowitcher0.013342938

Замечание. В табл. 1 использовано сокращение: rbs – red-backed_sandpiper.

Приведенный выше код, если параметр get_cls = 0, получает значения следующих показателей различия/сходства изображений:

Таблица 2. Оценки различия изображений (исходного и зашумленного)

ПоказательРазличие
Панда, рис. 1
MSE0.001933
PSNR-27.13794
1 - SSIM0.066128
E_dist17.05736
Cos_dist0.003859
Чаша с бульоном, рис. 5
MSE0.002427
PSNR-26.149346
1 - SSIM0.024277
E_dist19.11353
Cos_dist0.003058
Птица, рис. 7
MSE0.003869
PSNR-24.124062
1 - SSIM0.203142
E_dist24.132683
Cos_dist0.007075

Приложение. Код получения прогноза НС, обученных на ImageNet

Прогноз НС выводит следующий код:

from sys import exit
import numpy as np
from keras.preprocessing import image
import matplotlib.pyplot as plt
get_cls = 1
mdl_no = 0
mdl_lst = ['Xception', 'VGG16', 'VGG19', 'ResNet50', 'ResNet101', 'ResNet152', # 0 - 5
           'ResNet50V2', 'ResNet101V2', 'ResNet152V2', 'InceptionV3', # 6 - 9
           'InceptionResNetV2', 'MobileNet', 'MobileNetV2', # 10 - 12
           'MobileNetV3Small', 'MobileNetV3Large', # 13 - 14
           'DenseNet121', 'DenseNet169', 'DenseNet201', # 15 - 17
           'NASNetMobile', 'NASNetLarge', 'ConvNeXtTiny', 'ConvNeXtSmall', # 18 - 21
           'ConvNeXtBase', 'ConvNeXtLarge', 'ConvNeXtXLarge', # 22 - 24
           'EfficientNetB0', 'EfficientNetB1', 'EfficientNetB2', # 25 - 27
           'EfficientNetB3', 'EfficientNetB4', 'EfficientNetB5', # 28 - 30
           'EfficientNetB6', 'EfficientNetB7', 'EfficientNetV2B0', # 31 - 33
           'EfficientNetV2B1', 'EfficientNetV2B2', 'EfficientNetV2B3', # 34 - 36
           'EfficientNetV2S', 'EfficientNetV2M', 'EfficientNetV2L'] # 37 - 39
show_summary = 0
show_img = 0
img_nm1 = 'panda_true.png'
img_nm2 = 'panda_noise.png'
img_nm1 = 'cup_true.png' # cup.png, teapot.png, as_cheetah.png
img_nm2 = 'cup_hole.png'
# img_nm1 = 'bird_true.png' # Песочник с красной спинкой
# img_nm2 = 'bird_noise.png' # или американский бекасовидный веретенник
imgs_list = [img_nm1, img_nm2]
# imgs_list = ['elephant.jpg', 'wolf.jpg', 'amur_tiger.jpg']
imgs_loaded = []
def show_pics(imgs_list, imgs_loaded):
    n_imgs = len(imgs_list)
    _, axs = plt.subplots(1, n_imgs, figsize = (7, 4))
    for i in range(n_imgs):
        ax1 = axs[i]
        ax1.set_axis_off()
        ax1.set_title(imgs_list[i])
        ax1.imshow(imgs_loaded[i])
    plt.show()
if get_cls == 0:
    from skimage.metrics import mean_squared_error
    import cv2, scipy
    from skimage.metrics import structural_similarity as ssim
    from scipy.spatial.distance import euclidean as e_dist
    for img_nm in imgs_list:
        img = image.load_img(img_nm, target_size = (224, 224))
        img = image.img_to_array(img) # Массив формы (224, 224, 3)
        img /= 255
        imgs_loaded.append(img)
    if show_img:
        show_pics(imgs_list, imgs_loaded)
    # Средняя квадратическая ошибка
    image1 = imgs_loaded[0]
    image2 = imgs_loaded[1]
    mse = mean_squared_error(image1, image2)
    # mse2 = ((image1 - image2) ** 2).mean()
    # Пиковое отношение сигнала к шуму
    # https://habr.com/ru/articles/126848/
    psnr = cv2.PSNR(image1, image2, mse)
    # Индекс структурного сходства
    # https://habr.com/ru/articles/126848/
    # https://scikit-image.org/docs/stable/auto_examples/transform/plot_ssim.html
    # score_ssim, diff = ssim(image1, image2, full = True, multichannel = True)
    # или (в зависимости от версии)
    dr1 = image1.max() - image1.min()
    dr2 = image2.max() - image2.min()
    dr = max(dr1, dr2)
    # score_ssim, diff = ssim(image1, image2, full = True, channel_axis = 2, data_range = dr)
    score_ssim2, diff = ssim(image1.flatten(), image2.flatten(), full = True, data_range = dr)
    # Евклидово расстояние
    ec_dst = np.linalg.norm(image1 - image2)
    # ec_dst2 = e_dist(image1.flatten(), image2.flatten())
    # Косинусное расстояние между векторами
    # https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.cosine.html
    cs_dst = scipy.spatial.distance.cosine(image1.flatten(), image2.flatten())
    print('mse =', round(mse, 6))
    # print('mse2 =', round(mse2, 6))
    print('psnr =', round(psnr, 6))
    # print('1 - ssim =', round(1 - score_ssim, 6))
    print('1 - ssim2 =', round(1 - score_ssim2, 6))
    print('ec_dst =', round(ec_dst, 6))
    # print('ec_dst2 =', round(ec_dst2, 6))
    print('cs_dst =', round(cs_dst, 6))
else:
    from google.colab import drive
    drv = '/content/drive/'
    drive.mount(drv)
    # Путь к изображениям в Colab
    pathToData = drv + 'My Drive/imgs/'
    for mdl_no in range(len(mdl_lst)):
        print('mdl_name =', mdl_lst[mdl_no])
        target_size = (224, 224)
        if mdl_no in [13, 14, 22]: continue
        if mdl_no == 0: # Создание модели нейронной сети
            from keras.applications.xception import Xception as img_net
            from keras.applications.xception import preprocess_input as pri
            from keras.applications.xception import decode_predictions as dep
            target_size = (299, 299)
        elif mdl_no == 1:
            from keras.applications.vgg16 import VGG16 as img_net
            from keras.applications.vgg16 import preprocess_input as pri
            from keras.applications.vgg16 import decode_predictions as dep
        elif mdl_no == 2:
            from keras.applications.vgg19 import VGG19 as img_net
            from keras.applications.vgg19 import preprocess_input as pri
            from keras.applications.vgg19 import decode_predictions as dep
        elif mdl_no in [3, 4, 5]:
            if mdl_no == 3:
                from keras.applications.resnet import ResNet50 as img_net
            elif mdl_no == 4:
                from keras.applications.resnet import ResNet101 as img_net
            elif mdl_no == 5:
                from keras.applications.resnet import ResNet152 as img_net
            from keras.applications.resnet import preprocess_input as pri
            from keras.applications.resnet import decode_predictions as dep
        elif mdl_no in [6, 7, 8]:
            if mdl_no == 6:
                from keras.applications.resnet_v2 import ResNet50V2 as img_net
            elif mdl_no == 7:
                from keras.applications.resnet_v2 import ResNet101V2 as img_net
            elif mdl_no == 8:
                from keras.applications.resnet_v2 import ResNet152V2 as img_net
            from keras.applications.resnet_v2 import preprocess_input as pri
            from keras.applications.resnet_v2 import decode_predictions as dep
        elif mdl_no == 9:
            from keras.applications.inception_v3 import InceptionV3 as img_net
            from keras.applications.inception_v3 import preprocess_input as pri
            from keras.applications.inception_v3 import decode_predictions as dep
            target_size = (299, 299)
        elif mdl_no == 10:
            from keras.applications.inception_resnet_v2 import InceptionResNetV2 as img_net
            from keras.applications.inception_resnet_v2 import preprocess_input as pri
            from keras.applications.inception_resnet_v2 import decode_predictions as dep
            target_size = (299, 299)
        elif mdl_no == 11:
            from keras.applications.mobilenet import MobileNet as img_net
            from keras.applications.mobilenet import preprocess_input as pri
            from keras.applications.mobilenet import decode_predictions as dep
        elif mdl_no == 12:
            from keras.applications.mobilenet_v2 import MobileNetV2 as img_net
            from keras.applications.mobilenet_v2 import preprocess_input as pri
            from keras.applications.mobilenet_v2 import decode_predictions as dep
        elif mdl_no in [13, 14]:
            if mdl_no == 13:
                from keras.applications.mobilenet_v3 import MobileNetV3Small as img_net
            elif mdl_no == 14:
                from keras.applications.mobilenet_v3 import MobileNetV3Large as img_net
            from keras.applications.mobilenet_v3 import preprocess_input as pri
            from keras.applications.mobilenet_v3 import decode_predictions as dep
        elif mdl_no in [15, 16, 17]:
            if mdl_no == 15:
                from keras.applications.densenet import DenseNet121 as img_net
            elif mdl_no == 16:
                from keras.applications.densenet import DenseNet169 as img_net
            elif mdl_no == 17:
                from keras.applications.densenet import DenseNet201 as img_net
            from keras.applications.densenet import preprocess_input as pri
            from keras.applications.densenet import decode_predictions as dep
        elif mdl_no in [18, 19]:
            if mdl_no == 18:
                from keras.applications.nasnet import NASNetMobile as img_net
            elif mdl_no == 19:
                from keras.applications.nasnet import NASNetLarge as img_net
                target_size = (331, 331)
            from keras.applications.nasnet import preprocess_input as pri
            from keras.applications.nasnet import decode_predictions as dep
        elif mdl_no in [20, 21, 23, 24]:
            if mdl_no == 20:
                from keras.applications.convnext import ConvNeXtTiny as img_net
            elif mdl_no == 21:
                from keras.applications.convnext import ConvNeXtSmall as img_net
            elif mdl_no == 22:
                from keras.applications.convnext import ConvNeXtBase as img_net
            elif mdl_no == 23:
                from keras.applications.convnext import ConvNeXtLarge as img_net
            elif mdl_no == 24:
                from keras.applications.convnext import ConvNeXtXLarge as img_net
            from keras.applications.convnext import preprocess_input as pri
            from keras.applications.convnext import decode_predictions as dep
        elif mdl_no in [25, 26, 27, 28, 29, 30, 31, 32]: # efficientnet
            if mdl_no == 25:
                from keras.applications.efficientnet import EfficientNetB0 as img_net
            elif mdl_no == 26:
                from keras.applications.efficientnet import EfficientNetB1 as img_net
                target_size = (240, 240)
            elif mdl_no == 27:
                from keras.applications.efficientnet import EfficientNetB2 as img_net
                target_size = (260, 260)
            elif mdl_no == 28:
                from keras.applications.efficientnet import EfficientNetB3 as img_net
                target_size = (300, 300)
            elif mdl_no == 29:
                from keras.applications.efficientnet import EfficientNetB4 as img_net
                target_size = (380, 380)
            elif mdl_no == 30:
                from keras.applications.efficientnet import EfficientNetB5 as img_net
                target_size = (456, 456)
            elif mdl_no == 31:
                from keras.applications.efficientnet import EfficientNetB6 as img_net
                target_size = (528, 528)
            elif mdl_no == 32:
                from keras.applications.efficientnet import EfficientNetB7 as img_net
                target_size = (600, 600)
            from keras.applications.efficientnet import preprocess_input as pri
            from keras.applications.efficientnet import decode_predictions as dep
        elif mdl_no in [33, 34, 35, 36, 37, 38, 39]: # efficientnet_v2
            if mdl_no == 33:
                from keras.applications.efficientnet_v2 import EfficientNetV2B0 as img_net
            elif mdl_no == 34:
                from keras.applications.efficientnet_v2 import EfficientNetV2B1 as img_net
                target_size = (240, 240)
            elif mdl_no == 35:
                from keras.applications.efficientnet_v2 import EfficientNetV2B2 as img_net
                target_size = (260, 260)
            elif mdl_no == 36:
                from keras.applications.efficientnet_v2 import EfficientNetV2B3 as img_net
                target_size = (300, 300)
            elif mdl_no == 37:
                from keras.applications.efficientnet_v2 import EfficientNetV2S as img_net
                target_size = (384, 384)
            elif mdl_no == 38:
                from keras.applications.efficientnet_v2 import EfficientNetV2M as img_net
                target_size = (480, 480)
            elif mdl_no == 39:
                from keras.applications.efficientnet_v2 import EfficientNetV2L as img_net
                target_size = (480, 480)
            from keras.applications.efficientnet_v2 import preprocess_input as pri
            from keras.applications.efficientnet_v2 import decode_predictions as dep
        def predit(imgs, imgs_list):
            print('Прогноз:')
            top = 2 # Число прогнозов для каждого изображения
            k = -1
            for x in imgs:
                features = model.predict(x, verbose = 0) # features.shape: (1, 1000)
                dp = dep(features, top = top)[0]
                k += 1
                print(imgs_list[k])
                for p in dp:
                    print(p)
        # Функция возвращает список загруженных и обработанных изображений
        def load_imgs(pathToData, imgs_list):
            imgs_loaded = []
            imgs_for_show = []
            for img in imgs_list:
                    img_path = pathToData + img
                    img = image.load_img(img_path, target_size = target_size)
                    x = image.img_to_array(img) # Массив формы (224, 224, 3)
                    imgs_for_show.append(x / 255)
                    # Добавляем измерение протяженностью 1
                    x = np.expand_dims(x, axis = 0) # Массив формы (1, 224, 224, 3)
                    # Подготовка данных для передачи на вход нейронной сети VGG16
                    x = pri(x)
                    imgs_loaded.append(x)
            if show_img:
                show_pics(imgs_list, imgs_for_show)
                exit()
            return imgs_loaded
        # Загрузка изображений
        imgs_loaded = load_imgs(pathToData, imgs_list)
        model = img_net(weights = 'imagenet', include_top = True)
        if show_summary:
            model.summary() # Вывод сведений о слоях нейронной сети
        # Прогнозирование
        predit(imgs_loaded, imgs_list)

Источники

1. Исследование устойчивости сверточных нейросетей. https://habr.com/ru/companies/huawei/articles/509816/.
2. Арлазаров В. В., Лимонова Е. Е. Вопросы устойчивости искусственного интеллекта на основе нейронных сетей: теория и практика. (ФИЦ ИУ РАН) https://rutube.ru/video/3dd79744f919052709014475b8169bd2/.
3. ImageNet. https://image-net.org/index.php.
4. Understanding GoogLeNet Model – CNN Architecture. https://www.geeksforgeeks.org/understanding-googlenet-model-cnn-architecture/
5. AlexNet. https://en.wikipedia.org/wiki/AlexNet.
6. Карпенко А. П., Овчинников В. А. Как обмануть нейронную сеть? Синтез шума для уменьшения точности нейросетевой классификации изображений. Вестник МГТУ им. Н.Э. Баумана. Сер. Приборостроение, 2021, № 1 (134), с. 102–119. DOI: https://doi.org/10.18698/0236-3933-2021-1-102-119.
7. FA_Attack_on_AlexNet. https://github.com/Carco-git/FA_Attack_on_AlexNet.

Список работ

Рейтинг@Mail.ru