{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import pandas as pd\nfrom pydicom.pixel_data_handlers.util import apply_voi_lut\nfrom matplotlib import pyplot as plt, cm\nimport seaborn as sns \nimport time, copy, pydot, os, cv2, torch\nimport shutil\nimport glob\nimport numpy as np\nimport shutil\nimport pickle\nfrom tqdm import tqdm\nfrom PIL import Image\nimport math, glob, re\nimport pydicom as dicom\nimport tensorflow as tf\nfrom pathlib import Path\nfrom random import shuffle\nimport torch.nn.modules as nn\nfrom joblib import Parallel, delayed\nfrom tqdm.keras import TqdmCallback\n\nfrom tensorflow.keras.applications.resnet_v2 import ResNet50V2\nfrom tensorflow.keras.optimizers import RMSprop\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.layers import Dense, GlobalAveragePooling2D, Dropout\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras.models import load_model\n\nfrom keras.utils.vis_utils import plot_model, model_to_dot\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import classification_report, confusion_matrix, pairwise_distances\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.cluster import KMeans\n\nfrom tensorflow.keras import models, metrics\n\nimport networkx as nx\n\nfrom skimage.segmentation import slic\nfrom skimage.color import rgb2lab\nfrom skimage.segmentation import mark_boundaries\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom matplotlib import colors\nfrom skimage.color import rgb2gray, rgb2hsv, hsv2rgb\nfrom skimage.io import imread, imshow\nfrom sklearn.cluster import KMeans","metadata":{"execution":{"iopub.status.busy":"2023-06-17T00:30:49.335521Z","iopub.execute_input":"2023-06-17T00:30:49.336006Z","iopub.status.idle":"2023-06-17T00:31:04.73173Z","shell.execute_reply.started":"2023-06-17T00:30:49.335963Z","shell.execute_reply":"2023-06-17T00:31:04.730469Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"RSNA_512_path='/kaggle/input/rsna-breast-cancer-512-pngs'","metadata":{"execution":{"iopub.status.busy":"2023-06-17T00:31:04.733779Z","iopub.execute_input":"2023-06-17T00:31:04.735174Z","iopub.status.idle":"2023-06-17T00:31:04.741403Z","shell.execute_reply.started":"2023-06-17T00:31:04.735123Z","shell.execute_reply":"2023-06-17T00:31:04.739866Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train=pd.read_csv('/kaggle/input/rsna-breast-cancer-detection/train.csv')\ndf_train.head(3)","metadata":{"execution":{"iopub.status.busy":"2023-06-17T00:31:04.742781Z","iopub.execute_input":"2023-06-17T00:31:04.743213Z","iopub.status.idle":"2023-06-17T00:31:04.918062Z","shell.execute_reply.started":"2023-06-17T00:31:04.743173Z","shell.execute_reply":"2023-06-17T00:31:04.916674Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train.loc[:, ['age', 'biopsy', 'implant', 'cancer']].corr()","metadata":{"execution":{"iopub.status.busy":"2023-06-15T14:03:34.588143Z","iopub.execute_input":"2023-06-15T14:03:34.591134Z","iopub.status.idle":"2023-06-15T14:03:34.618933Z","shell.execute_reply.started":"2023-06-15T14:03:34.591074Z","shell.execute_reply":"2023-06-15T14:03:34.617746Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"fig, ax = plt.subplots(figsize=(15, 5))\ndf_train.groupby('age').agg(Количество_класса_1 = ('cancer', lambda x: len(x[x == 1])), \n                           Количество_класса_0 = ('cancer', lambda x: len(x[x == 0])))\\\n                           .plot(kind='bar', ax=ax, alpha=0.5, width=0.7)\nax.grid(axis='y', ls='--')","metadata":{"execution":{"iopub.status.busy":"2023-06-15T10:38:20.823704Z","iopub.execute_input":"2023-06-15T10:38:20.824154Z","iopub.status.idle":"2023-06-15T10:38:22.321538Z","shell.execute_reply.started":"2023-06-15T10:38:20.824102Z","shell.execute_reply":"2023-06-15T10:38:22.319991Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data = pd.DataFrame(np.concatenate([['Total'] * len(df_train) , \n                                    ['1 Cancer'] *  len(df_train[df_train['cancer'] == 1]), \n                                    ['0 Cancer'] *  len(df_train[(df_train['cancer'] == 0)])]), columns = [\"class\"])\nsns.countplot(x='class', data=data)\nprint('Всего наблюдений', len(df_train))\nprint('Наблюдения без рака', len(df_train[df_train['cancer'] == 0]))\nprint('Наблюдения с раком', len(df_train[df_train['cancer'] == 1]))","metadata":{"execution":{"iopub.status.busy":"2023-06-15T10:38:22.323638Z","iopub.execute_input":"2023-06-15T10:38:22.324086Z","iopub.status.idle":"2023-06-15T10:38:22.678236Z","shell.execute_reply.started":"2023-06-15T10:38:22.324026Z","shell.execute_reply":"2023-06-15T10:38:22.676291Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"DF_train = df_train[df_train['biopsy'] == 1].reset_index(drop = True)\nDF_train = DF_train.groupby(['cancer']).apply(lambda x: x.sample(1158, replace = True)\n                                                      ).reset_index(drop = True)\n# DF_train2 = df_train[df_train['biopsy'] == 0].iloc[:3000]\n# DF_train = pd.concat([DF_train, DF_train2], axis=0).reset_index(drop = True)\nprint('New Data Size:', DF_train.shape[0])","metadata":{"execution":{"iopub.status.busy":"2023-06-17T00:31:04.920829Z","iopub.execute_input":"2023-06-17T00:31:04.921262Z","iopub.status.idle":"2023-06-17T00:31:04.957351Z","shell.execute_reply.started":"2023-06-17T00:31:04.921219Z","shell.execute_reply":"2023-06-17T00:31:04.95457Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"DF_train\n# 10102_1241778584","metadata":{"execution":{"iopub.status.busy":"2023-06-15T03:43:11.737449Z","iopub.execute_input":"2023-06-15T03:43:11.737929Z","iopub.status.idle":"2023-06-15T03:43:11.768403Z","shell.execute_reply.started":"2023-06-15T03:43:11.737886Z","shell.execute_reply":"2023-06-15T03:43:11.767286Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for i in range(len(DF_train)):\n    DF_train.loc[i, 'path'] = os.path.join(RSNA_512_path + '/' + str(DF_train.loc[i, 'patient_id']) + '_' + str(DF_train.loc[i, 'image_id']) + '.png')","metadata":{"execution":{"iopub.status.busy":"2023-06-17T00:31:04.959013Z","iopub.execute_input":"2023-06-17T00:31:04.960019Z","iopub.status.idle":"2023-06-17T00:31:06.083709Z","shell.execute_reply.started":"2023-06-17T00:31:04.959961Z","shell.execute_reply":"2023-06-17T00:31:06.08259Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"img=cv2.imread(DF_train.loc[0, 'path'])\nplt.imshow(img, cmap='gray')","metadata":{"execution":{"iopub.status.busy":"2023-06-14T10:41:01.418731Z","iopub.execute_input":"2023-06-14T10:41:01.419264Z","iopub.status.idle":"2023-06-14T10:41:01.779843Z","shell.execute_reply.started":"2023-06-14T10:41:01.419205Z","shell.execute_reply":"2023-06-14T10:41:01.778802Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df, val_df= train_test_split(\n    DF_train,\n    test_size=0.3, \n    random_state=2023,\n    stratify=DF_train['cancer']\n)\n\nprint(f\"Train:{train_df.shape[0]} Validation: {val_df.shape[0]}\")\nprint(f\"Train: {train_df['cancer'].value_counts()}\")\nprint(f\"Validation: {val_df['cancer'].value_counts()}\")","metadata":{"execution":{"iopub.status.busy":"2023-06-17T00:31:06.085283Z","iopub.execute_input":"2023-06-17T00:31:06.085767Z","iopub.status.idle":"2023-06-17T00:31:06.100949Z","shell.execute_reply.started":"2023-06-17T00:31:06.085717Z","shell.execute_reply":"2023-06-17T00:31:06.099628Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df_normal=train_df[train_df['cancer']==0].reset_index(drop=True)\ntrain_df_cancer=train_df[train_df['cancer']==1].reset_index(drop=True)\nval_df_normal=val_df[val_df['cancer']==0].reset_index(drop=True)\nval_df_cancer = val_df[val_df['cancer'] == 1].reset_index(drop = True)","metadata":{"execution":{"iopub.status.busy":"2023-06-17T00:31:06.102853Z","iopub.execute_input":"2023-06-17T00:31:06.103266Z","iopub.status.idle":"2023-06-17T00:31:06.114313Z","shell.execute_reply.started":"2023-06-17T00:31:06.103229Z","shell.execute_reply":"2023-06-17T00:31:06.113289Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def fit_image(fname, destination_dir_sub):\n    X = cv2.imread(fname)\n    \n    # Some images have narrow exterior \"frames\" that complicate selection of the main data. Cutting off the frame\n    X = X[5:-5, 5:-5]\n    \n    # regions of non-empty pixels\n    output= cv2.connectedComponentsWithStats((X > 20).astype(np.uint8)[:, :, 0], 8, cv2.CV_32S)\n\n    # stats.shape == (N, 5), where N is the number of regions, 5 dimensions correspond to:\n    # left, top, width, height, area_size\n    stats = output[2]\n\n    # finding max area which always corresponds to the breast data. \n    idx = stats[1:, 4].argmax() + 1\n    x1, y1, w, h = stats[idx][:4]\n    x2 = x1 + w\n    y2 = y1 + h\n    \n    # cutting out the breast data\n    X_fit = X[y1: y2, x1: x2]\n    \n    patient_id, im_id = re.findall('(\\d+)_(\\d+).png', os.path.basename(fname))[0]\n#     os.makedirs(patient_id, exist_ok=True)\n    cv2.imwrite(f'{destination_dir_sub}/{patient_id}_{im_id}.png', X_fit[:, :, 0])\n\ndef fit_all_images(all_images):\n    with ProcessPoolExecutor(4) as p:\n        for i in tqdm(p.map(fit_image, all_images), total=len(all_images)):\n            pass","metadata":{"execution":{"iopub.status.busy":"2023-06-14T10:41:01.822966Z","iopub.execute_input":"2023-06-14T10:41:01.823526Z","iopub.status.idle":"2023-06-14T10:41:02.108693Z","shell.execute_reply.started":"2023-06-14T10:41:01.823466Z","shell.execute_reply":"2023-06-14T10:41:02.107331Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"rm -r train","metadata":{"execution":{"iopub.status.busy":"2023-06-16T14:01:48.192048Z","iopub.execute_input":"2023-06-16T14:01:48.192918Z","iopub.status.idle":"2023-06-16T14:01:49.372246Z","shell.execute_reply.started":"2023-06-16T14:01:48.192865Z","shell.execute_reply":"2023-06-16T14:01:49.370794Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"rm -r val","metadata":{"execution":{"iopub.status.busy":"2023-06-16T14:01:49.374938Z","iopub.execute_input":"2023-06-16T14:01:49.376143Z","iopub.status.idle":"2023-06-16T14:01:50.527059Z","shell.execute_reply.started":"2023-06-16T14:01:49.376076Z","shell.execute_reply":"2023-06-16T14:01:50.5251Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"destination_dir = '/kaggle/working/train'\ndestination_dir_sub = '/kaggle/working/train/0normal'\n\nif not os.path.exists(destination_dir):\n    os.makedirs(destination_dir)\n\nif not os.path.exists(destination_dir_sub):\n    os.makedirs(destination_dir_sub)   \n    \nfor path in train_df_normal['path']:\n#     fit_image(path, destination_dir_sub)\n    shutil.copy2(path, destination_dir_sub)    ","metadata":{"execution":{"iopub.status.busy":"2023-06-17T00:31:06.118117Z","iopub.execute_input":"2023-06-17T00:31:06.118715Z","iopub.status.idle":"2023-06-17T00:31:14.860517Z","shell.execute_reply.started":"2023-06-17T00:31:06.118657Z","shell.execute_reply":"2023-06-17T00:31:14.858933Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"destination_dir = '/kaggle/working/val'\ndestination_dir_sub = '/kaggle/working/val/0normal'\n\nif not os.path.exists(destination_dir):\n    os.makedirs(destination_dir)\n\nif not os.path.exists(destination_dir_sub):\n    os.makedirs(destination_dir_sub)   \n    \nfor path in val_df_normal['path']:\n#     fit_image(path, destination_dir_sub)    \n    shutil.copy2(path, destination_dir_sub)","metadata":{"execution":{"iopub.status.busy":"2023-06-17T00:31:14.862081Z","iopub.execute_input":"2023-06-17T00:31:14.862469Z","iopub.status.idle":"2023-06-17T00:31:17.438865Z","shell.execute_reply.started":"2023-06-17T00:31:14.862433Z","shell.execute_reply":"2023-06-17T00:31:17.437695Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"destination_dir = '/kaggle/working/train'\ndestination_dir_sub = '/kaggle/working/train/1cancer'\n\nif not os.path.exists(destination_dir):\n    os.makedirs(destination_dir)\n\nif not os.path.exists(destination_dir_sub):\n    os.makedirs(destination_dir_sub)   \n    \nfor path in train_df_cancer['path']:\n#     fit_image(path, destination_dir_sub)\n    shutil.copy2(path, destination_dir_sub)    ","metadata":{"execution":{"iopub.status.busy":"2023-06-17T00:31:17.441577Z","iopub.execute_input":"2023-06-17T00:31:17.442486Z","iopub.status.idle":"2023-06-17T00:31:24.712625Z","shell.execute_reply.started":"2023-06-17T00:31:17.442444Z","shell.execute_reply":"2023-06-17T00:31:24.711337Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"destination_dir = '/kaggle/working/val'\ndestination_dir_sub = '/kaggle/working/val/1cancer'\n\nif not os.path.exists(destination_dir):\n    os.makedirs(destination_dir)\n\nif not os.path.exists(destination_dir_sub):\n    os.makedirs(destination_dir_sub)   \n    \nfor path in val_df_cancer['path']:\n#     fit_image(path, destination_dir_sub)    \n    shutil.copy2(path, destination_dir_sub)    ","metadata":{"execution":{"iopub.status.busy":"2023-06-17T00:31:24.715408Z","iopub.execute_input":"2023-06-17T00:31:24.715803Z","iopub.status.idle":"2023-06-17T00:31:26.626061Z","shell.execute_reply.started":"2023-06-17T00:31:24.715767Z","shell.execute_reply":"2023-06-17T00:31:26.624962Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"normal_train_images = glob.glob('/kaggle/working/train/normal/*.png')\ncancer_train_images = glob.glob('/kaggle/working/train/cancer/*.png')","metadata":{"execution":{"iopub.status.busy":"2023-06-17T00:31:26.62768Z","iopub.execute_input":"2023-06-17T00:31:26.628452Z","iopub.status.idle":"2023-06-17T00:31:26.634929Z","shell.execute_reply.started":"2023-06-17T00:31:26.628407Z","shell.execute_reply":"2023-06-17T00:31:26.633639Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"fig, axes= plt.subplots(nrows=2, ncols=5, figsize=(15,10), subplot_kw={'xticks': [], 'yticks': []})\nfor i, ax in enumerate(axes.flat):\n    img=cv2.imread(normal_train_images[i])\n    ax.imshow(img)\n    ax.set_title('Normal')\nfig.tight_layout()\n\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-06-15T03:43:45.668933Z","iopub.execute_input":"2023-06-15T03:43:45.669649Z","iopub.status.idle":"2023-06-15T03:43:46.969326Z","shell.execute_reply.started":"2023-06-15T03:43:45.669609Z","shell.execute_reply":"2023-06-15T03:43:46.968363Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"fig, axes= plt.subplots(nrows=2, ncols=5, figsize=(15,10), subplot_kw={'xticks': [], 'yticks': []})\nfor i, ax in enumerate(axes.flat):\n    img=cv2.imread(cancer_train_images[i])\n    ax.imshow(img)\n    ax.set_title('Cancer')\nfig.tight_layout()\n\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-06-15T03:43:46.970727Z","iopub.execute_input":"2023-06-15T03:43:46.971284Z","iopub.status.idle":"2023-06-15T03:43:48.4075Z","shell.execute_reply.started":"2023-06-15T03:43:46.971248Z","shell.execute_reply":"2023-06-15T03:43:48.406499Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_datagen=ImageDataGenerator(\n                                rescale=1./255.,\n                                zoom_range=0.2,\n#                                 vertical_flip=True,\n#                                 rotation_range=70\n                                )\nval_datagen=ImageDataGenerator(rescale=1./255.)","metadata":{"execution":{"iopub.status.busy":"2023-06-16T14:02:09.248937Z","iopub.execute_input":"2023-06-16T14:02:09.249422Z","iopub.status.idle":"2023-06-16T14:02:09.272804Z","shell.execute_reply.started":"2023-06-16T14:02:09.249368Z","shell.execute_reply":"2023-06-16T14:02:09.271186Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# train_path = '/kaggle/working/train'\n# val_path = '/kaggle/working/val'\n\n# train_generator=train_datagen.flow_from_directory(\n#     train_path,\n#     target_size=(512,512),\n#     batch_size=32,\n#     class_mode='binary'\n# )\n# validation_generator=val_datagen.flow_from_directory(\n#     val_path,\n#     target_size=(512,512),\n#     batch_size=32,\n#     class_mode='binary'\n# )\ntrain_path = '/kaggle/working/train'\nval_path = '/kaggle/working/val'\n\ntrain_generator = train_datagen.flow_from_directory(\n    train_path,\n    target_size = (512, 512),\n    batch_size = 32,\n    class_mode = 'binary'\n)\nvalidation_generator = val_datagen.flow_from_directory(\n        val_path,\n        target_size = (512, 512),\n        batch_size = 16,\n        class_mode = 'binary'\n)","metadata":{"execution":{"iopub.status.busy":"2023-06-16T14:02:09.277503Z","iopub.execute_input":"2023-06-16T14:02:09.278369Z","iopub.status.idle":"2023-06-16T14:02:09.497697Z","shell.execute_reply.started":"2023-06-16T14:02:09.278326Z","shell.execute_reply":"2023-06-16T14:02:09.496395Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\nbase_model=ResNet50V2(weights='imagenet', input_shape=(512,512,3), include_top=False)\n\nfor layer in base_model.layers:\n    layer.trainable=False\n    \nmodel= Sequential()\nmodel.add(base_model)\nmodel.add(GlobalAveragePooling2D())\nmodel.add(Dense(128, activation='relu'))\nmodel.add(Dropout(0.2))\nmodel.add(Dense(1, activation='sigmoid'))\n\nmodel.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy',metrics.Precision(),metrics.Recall()])","metadata":{"execution":{"iopub.status.busy":"2023-06-14T10:41:41.71404Z","iopub.execute_input":"2023-06-14T10:41:41.714473Z","iopub.status.idle":"2023-06-14T10:41:49.286894Z","shell.execute_reply.started":"2023-06-14T10:41:41.714431Z","shell.execute_reply":"2023-06-14T10:41:49.28566Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"base_model = ResNet50V2(weights = 'imagenet', input_shape = (512, 512, 3), include_top = False)\n\nfor layer in base_model.layers:\n    layer.trainable = False\n    \nmodel = Sequential()\nmodel.add(base_model)\nmodel.add(GlobalAveragePooling2D())\nmodel.add(Dense(128, activation = 'relu'))\nmodel.add(Dropout(0.2))\nmodel.add(Dense(1, activation = 'sigmoid'))\n\nmodel.compile(optimizer = \"adam\", loss = 'binary_crossentropy', metrics = [\"accuracy\"])","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plot_model(model, show_dtype=True, show_layer_activations=True, show_shapes=True, show_layer_names=True,\n          to_file='model.png', dpi=100)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"callback=tf.keras.callbacks.EarlyStopping(monitor='val_loss', mode='min', patience=4)\ncheckpoint_callback_lstm = tf.keras.callbacks.ModelCheckpoint(\n    '/kaggle/working/model3.h5',\n    monitor='val_loss',\n    save_best_only=True,\n    save_weights_only=False,\n    verbose=1\n)","metadata":{"execution":{"iopub.status.busy":"2023-06-14T00:44:41.806702Z","iopub.execute_input":"2023-06-14T00:44:41.807129Z","iopub.status.idle":"2023-06-14T00:44:41.815965Z","shell.execute_reply.started":"2023-06-14T00:44:41.807081Z","shell.execute_reply":"2023-06-14T00:44:41.814516Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history = model.fit(train_generator, \n                    validation_data = validation_generator, \n                    steps_per_epoch = 20, epochs = 15, \n                    callbacks =[callback,\n               TqdmCallback(verbose=0),\n               checkpoint_callback_lstm])","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history=model.fit(\n    train_generator,\n    validation_data=validation_generator,\n    steps_per_epoch=20,\n    epochs=30,\n    callbacks=[callback,\n               TqdmCallback(verbose=0),\n               checkpoint_callback_lstm]\n)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"","metadata":{}},{"cell_type":"code","source":"with open('/kaggle/working/history_lstm_classificator3', 'wb') as handle:\n    pickle.dump(history.history, handle)","metadata":{"execution":{"iopub.status.busy":"2023-06-14T03:35:12.716487Z","iopub.execute_input":"2023-06-14T03:35:12.717604Z","iopub.status.idle":"2023-06-14T03:35:12.724586Z","shell.execute_reply.started":"2023-06-14T03:35:12.717547Z","shell.execute_reply":"2023-06-14T03:35:12.723496Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# model.save('/kaggle/working/model1.h5')","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import pickle","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"with open('/kaggle/input/history/history_lstm_classificator3', 'rb') as handle:\n    history = pickle.load(handle)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from keras.models import load_model\n\nmodel = load_model('/kaggle/input/other2/mammography_pred_model.h5')\n\n# model = load_model('/kaggle/input/other5/mammography_pred_model (1).h5')\n\n# model = load_model('/kaggle/input/other2/mammography_pred_model.h5')\n# model = load_model('/kaggle/input/model-3/model3.h5')\n\n\n\n","metadata":{"execution":{"iopub.status.busy":"2023-06-17T00:31:26.636991Z","iopub.execute_input":"2023-06-17T00:31:26.637765Z","iopub.status.idle":"2023-06-17T00:31:31.925173Z","shell.execute_reply.started":"2023-06-17T00:31:26.637708Z","shell.execute_reply":"2023-06-17T00:31:31.924046Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# history.history","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"accuracy=history.history['accuracy']\nloss=history.history['loss']\nprecision=history.history['precision']\nrecall=history.history['recall']\nval_accuracy=history.history['val_accuracy']\nval_loss=history.history['val_loss']\nval_precision=history.history['val_precision']\nval_recall=history.history['val_recall']","metadata":{"execution":{"iopub.status.busy":"2023-06-14T03:35:41.654071Z","iopub.execute_input":"2023-06-14T03:35:41.654617Z","iopub.status.idle":"2023-06-14T03:35:41.663346Z","shell.execute_reply.started":"2023-06-14T03:35:41.65456Z","shell.execute_reply":"2023-06-14T03:35:41.661991Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.figure(figsize = (15,10))\n\nplt.subplot(2, 2, 1)\nplt.plot(accuracy, label = \"Training Accuracy\", marker=\"o\")\nplt.plot(val_accuracy, label = \"Validation Accuracy\", marker=\"o\")\nplt.ylim(0.4, 1)\nplt.legend(['Train', 'Validation'], loc = 'upper left')\nplt.title(\"Training vs Validation Accuracy\")\nplt.xlabel('epoch')\nplt.ylabel('accuracy')\n\n\nplt.subplot(2, 2, 2)\nplt.plot(loss, label = \"Training Loss\", marker=\"o\")\nplt.plot(val_loss, label = \"Validation Loss\", marker=\"o\")\nplt.legend(['Train', 'Validation'], loc = 'upper left')\nplt.title(\"Training vs Validation Loss\")\nplt.xlabel('epoch')\nplt.ylabel('loss')","metadata":{"execution":{"iopub.status.busy":"2023-06-14T03:35:44.646053Z","iopub.execute_input":"2023-06-14T03:35:44.646474Z","iopub.status.idle":"2023-06-14T03:35:45.135553Z","shell.execute_reply.started":"2023-06-14T03:35:44.646436Z","shell.execute_reply":"2023-06-14T03:35:45.134246Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.figure(figsize = (15,10))\n\nplt.subplot(2, 2, 1)\nplt.plot(precision, label = \"Training precision\", marker=\"o\")\nplt.plot(val_precision, label = \"Validation precision\", marker=\"o\")\nplt.ylim(0.4, 1)\nplt.legend(['Train', 'Validation'], loc = 'upper left')\nplt.title(\"Training vs Validation precision\")\nplt.xlabel('epoch')\nplt.ylabel('precision')\n\n\nplt.subplot(2, 2, 2)\nplt.plot(recall, label = \"Training recall\", marker=\"o\")\nplt.plot(val_recall, label = \"Validation recall\", marker=\"o\")\nplt.legend(['Train', 'Validation'], loc = 'upper left')\nplt.title(\"Training vs Validation recall\")\nplt.xlabel('epoch')\nplt.ylabel('recall')","metadata":{"execution":{"iopub.status.busy":"2023-06-14T03:35:53.752104Z","iopub.execute_input":"2023-06-14T03:35:53.752828Z","iopub.status.idle":"2023-06-14T03:35:54.221537Z","shell.execute_reply.started":"2023-06-14T03:35:53.752757Z","shell.execute_reply":"2023-06-14T03:35:54.220536Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"pred=model.predict(validation_generator)","metadata":{"execution":{"iopub.status.busy":"2023-06-16T14:12:03.167129Z","iopub.execute_input":"2023-06-16T14:12:03.168454Z","iopub.status.idle":"2023-06-16T14:17:25.27138Z","shell.execute_reply.started":"2023-06-16T14:12:03.168398Z","shell.execute_reply":"2023-06-16T14:17:25.269812Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.datasets import make_classification\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import roc_curve, auc\nfrom sklearn.metrics import roc_auc_score\nfrom matplotlib import pyplot as plt\n\nlr_probs = pred","metadata":{"execution":{"iopub.status.busy":"2023-06-15T13:26:41.211297Z","iopub.execute_input":"2023-06-15T13:26:41.211604Z","iopub.status.idle":"2023-06-15T13:26:41.304512Z","shell.execute_reply.started":"2023-06-15T13:26:41.211577Z","shell.execute_reply":"2023-06-15T13:26:41.303227Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"lr_auc = roc_auc_score(validation_generator.classes, lr_probs)\nprint('LogisticRegression: ROC AUC=%.3f' % (lr_auc))\n\nfpr, tpr, treshold = roc_curve(validation_generator.classes, lr_probs)\nroc_auc = auc(fpr, tpr)\n\nplt.plot(fpr, tpr, color='darkorange',\n         label='ROC кривая (area = %0.2f)' % roc_auc)\nplt.plot([0, 1], [0, 1], color='navy', linestyle='--')\nplt.xlim([0.0, 1.0])\nplt.ylim([0.0, 1.05])\nplt.xlabel('False Positive Rate')\nplt.ylabel('True Positive Rate')\nplt.title('Пример ROC-кривой')\nplt.legend(loc=\"lower right\")\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-06-15T13:26:41.305704Z","iopub.execute_input":"2023-06-15T13:26:41.305997Z","iopub.status.idle":"2023-06-15T13:26:41.484438Z","shell.execute_reply.started":"2023-06-15T13:26:41.305969Z","shell.execute_reply":"2023-06-15T13:26:41.483301Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_true=validation_generator.classes","metadata":{"execution":{"iopub.status.busy":"2023-06-16T14:17:25.273941Z","iopub.execute_input":"2023-06-16T14:17:25.274469Z","iopub.status.idle":"2023-06-16T14:17:25.280523Z","shell.execute_reply.started":"2023-06-16T14:17:25.274427Z","shell.execute_reply":"2023-06-16T14:17:25.279102Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_pred=[]\n\nfor prob in pred:\n    if prob >= 0.5:\n        y_pred.append(1)\n    else:\n        y_pred.append(0)","metadata":{"execution":{"iopub.status.busy":"2023-06-16T14:17:25.282837Z","iopub.execute_input":"2023-06-16T14:17:25.283792Z","iopub.status.idle":"2023-06-16T14:17:25.298457Z","shell.execute_reply.started":"2023-06-16T14:17:25.283716Z","shell.execute_reply":"2023-06-16T14:17:25.296845Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"temp = pd.DataFrame([validation_generator.filenames, y_true, y_pred, pred]).T.rename({0:'path',1:'pred',2:'true', 3:'proba'}, axis=1)","metadata":{"execution":{"iopub.status.busy":"2023-06-16T14:17:25.301728Z","iopub.execute_input":"2023-06-16T14:17:25.302157Z","iopub.status.idle":"2023-06-16T14:17:25.346433Z","shell.execute_reply.started":"2023-06-16T14:17:25.302112Z","shell.execute_reply":"2023-06-16T14:17:25.345393Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"temp","metadata":{"execution":{"iopub.status.busy":"2023-06-16T14:17:25.348072Z","iopub.execute_input":"2023-06-16T14:17:25.348453Z","iopub.status.idle":"2023-06-16T14:17:25.370604Z","shell.execute_reply.started":"2023-06-16T14:17:25.348414Z","shell.execute_reply":"2023-06-16T14:17:25.369197Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"temp","metadata":{"execution":{"iopub.status.busy":"2023-06-16T14:07:23.15192Z","iopub.execute_input":"2023-06-16T14:07:23.152383Z","iopub.status.idle":"2023-06-16T14:07:23.175156Z","shell.execute_reply.started":"2023-06-16T14:07:23.15234Z","shell.execute_reply":"2023-06-16T14:07:23.173589Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"temp.loc[(temp.pred == 1) & (temp.true == 1)] ","metadata":{"execution":{"iopub.status.busy":"2023-06-16T14:07:43.510378Z","iopub.execute_input":"2023-06-16T14:07:43.510859Z","iopub.status.idle":"2023-06-16T14:07:43.536454Z","shell.execute_reply.started":"2023-06-16T14:07:43.510814Z","shell.execute_reply":"2023-06-16T14:07:43.534929Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"temp.loc[(temp.pred == 0) & (temp.true == 0)] ","metadata":{"execution":{"iopub.status.busy":"2023-06-16T14:07:27.89308Z","iopub.execute_input":"2023-06-16T14:07:27.893593Z","iopub.status.idle":"2023-06-16T14:07:27.920091Z","shell.execute_reply.started":"2023-06-16T14:07:27.893546Z","shell.execute_reply":"2023-06-16T14:07:27.918724Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tensorflow.keras.preprocessing.image import img_to_array\n","metadata":{"execution":{"iopub.status.busy":"2023-06-16T14:19:12.48428Z","iopub.execute_input":"2023-06-16T14:19:12.484994Z","iopub.status.idle":"2023-06-16T14:19:12.490921Z","shell.execute_reply.started":"2023-06-16T14:19:12.484947Z","shell.execute_reply":"2023-06-16T14:19:12.489823Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"DF_train","metadata":{"execution":{"iopub.status.busy":"2023-06-16T14:21:04.456537Z","iopub.execute_input":"2023-06-16T14:21:04.457139Z","iopub.status.idle":"2023-06-16T14:21:04.492783Z","shell.execute_reply.started":"2023-06-16T14:21:04.457087Z","shell.execute_reply":"2023-06-16T14:21:04.491406Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"execution":{"iopub.status.busy":"2023-06-16T15:18:15.915188Z","iopub.execute_input":"2023-06-16T15:18:15.91653Z","iopub.status.idle":"2023-06-16T15:18:15.935937Z","shell.execute_reply.started":"2023-06-16T15:18:15.916478Z","shell.execute_reply":"2023-06-16T15:18:15.934566Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"pd.DataFrame(true_value0, columns=['path', 'pred', 'pred_proba', 'true']).to_parquet('/kaggle/working/df0.parquet')\npd.DataFrame(true_value1, columns=['path', 'pred', 'pred_proba', 'true']).to_parquet('/kaggle/working/df1.parquet')","metadata":{"execution":{"iopub.status.busy":"2023-06-16T15:19:03.065725Z","iopub.execute_input":"2023-06-16T15:19:03.067052Z","iopub.status.idle":"2023-06-16T15:19:03.143314Z","shell.execute_reply.started":"2023-06-16T15:19:03.066999Z","shell.execute_reply":"2023-06-16T15:19:03.141895Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"pd.DataFrame(value, columns=['path', 'pred', 'pred_proba', 'true'])","metadata":{"execution":{"iopub.status.busy":"2023-06-17T01:09:08.657788Z","iopub.execute_input":"2023-06-17T01:09:08.658408Z","iopub.status.idle":"2023-06-17T01:09:08.68986Z","shell.execute_reply.started":"2023-06-17T01:09:08.65836Z","shell.execute_reply":"2023-06-17T01:09:08.688292Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"destination_dir = '/kaggle/working/df'\n\nif not os.path.exists(destination_dir):\n    os.makedirs(destination_dir)\n    \nfor val in DF_train.values.tolist()[:]:\n    shutil.copy2('/kaggle/input/rsna-breast-cancer-512-pngs/'+str(val[1])+'_'+str(val[2])+'.png', destination_dir)","metadata":{"execution":{"iopub.status.busy":"2023-06-17T01:35:34.970112Z","iopub.execute_input":"2023-06-17T01:35:34.972119Z","iopub.status.idle":"2023-06-17T01:35:38.906814Z","shell.execute_reply.started":"2023-06-17T01:35:34.97205Z","shell.execute_reply":"2023-06-17T01:35:38.90558Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!tar -cvf /kaggle/working/archive.tar.gz /kaggle/working/df","metadata":{"execution":{"iopub.status.busy":"2023-06-17T01:36:24.670164Z","iopub.execute_input":"2023-06-17T01:36:24.670719Z","iopub.status.idle":"2023-06-17T01:36:26.354161Z","shell.execute_reply.started":"2023-06-17T01:36:24.670676Z","shell.execute_reply":"2023-06-17T01:36:26.352165Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\nvalue = []\nval_datagen = ImageDataGenerator(rescale=1. / 255.)\nfor val in DF_train.values.tolist()[:]:\n    img = Image.open('/kaggle/input/rsna-breast-cancer-512-pngs/'+str(val[1])+'_'+str(val[2])+'.png').convert('RGB')\n    X = np.array([img_to_array(img)])\n    pred_proba = model.predict(val_datagen.flow(X))[0][0]\n    pred=0\n    if pred_proba >= 0.5:\n        pred = 1\n    else:\n        pred = 0\n    value.append(['/kaggle/input/rsna-breast-cancer-512-pngs/'+str(val[1])+'_'+str(val[2])+'.png', pred, pred_proba, val[6]])\n","metadata":{"execution":{"iopub.status.busy":"2023-06-17T00:34:52.43971Z","iopub.execute_input":"2023-06-17T00:34:52.44128Z","iopub.status.idle":"2023-06-17T00:54:26.210389Z","shell.execute_reply.started":"2023-06-17T00:34:52.441214Z","shell.execute_reply":"2023-06-17T00:54:26.208957Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# img = Image.open(\"/kaggle/input/rsna-breast-cancer-512-pngs/65530_1401303823.png\").convert('RGB')\nX = tf.reshape(cv2.imread(\"/kaggle/input/rsna-breast-cancer-512-pngs/65530_1401303823.png\",1), [1, 512, 512, 3])\nprint(model.predict(X))","metadata":{"execution":{"iopub.status.busy":"2023-06-15T14:41:53.670958Z","iopub.execute_input":"2023-06-15T14:41:53.671438Z","iopub.status.idle":"2023-06-15T14:41:54.126388Z","shell.execute_reply.started":"2023-06-15T14:41:53.671394Z","shell.execute_reply":"2023-06-15T14:41:54.125257Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"rm -r /kaggle/working/test","metadata":{"execution":{"iopub.status.busy":"2023-06-15T14:42:49.837427Z","iopub.execute_input":"2023-06-15T14:42:49.83787Z","iopub.status.idle":"2023-06-15T14:42:50.986931Z","shell.execute_reply.started":"2023-06-15T14:42:49.83783Z","shell.execute_reply":"2023-06-15T14:42:50.985009Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"destination_dir = '/kaggle/working/test'\ndestination_dir_sub = '/kaggle/working/test/0cancer'\n\nif not os.path.exists(destination_dir):\n    os.makedirs(destination_dir)\n\nif not os.path.exists(destination_dir_sub):\n    os.makedirs(destination_dir_sub)   \n\nshutil.copy2('/kaggle/input/rsna-breast-cancer-512-pngs/10884_829440179.png', destination_dir_sub)\n# shutil.copy2('/kaggle/input/rsna-breast-cancer-512-pngs/9559_1047452753.png', destination_dir_sub)    ","metadata":{"execution":{"iopub.status.busy":"2023-06-16T13:59:22.018815Z","iopub.execute_input":"2023-06-16T13:59:22.019247Z","iopub.status.idle":"2023-06-16T13:59:22.033578Z","shell.execute_reply.started":"2023-06-16T13:59:22.019209Z","shell.execute_reply":"2023-06-16T13:59:22.032007Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"val_datagen=ImageDataGenerator(rescale=1./255.)\nvalidation_generator = val_datagen.flow_from_directory(\n        '/kaggle/working/test/',\n        target_size = (512, 512),\n        batch_size = 1,\n        class_mode = 'binary'\n)","metadata":{"execution":{"iopub.status.busy":"2023-06-16T13:59:26.820011Z","iopub.execute_input":"2023-06-16T13:59:26.820448Z","iopub.status.idle":"2023-06-16T13:59:26.930218Z","shell.execute_reply.started":"2023-06-16T13:59:26.820411Z","shell.execute_reply":"2023-06-16T13:59:26.929073Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.predict(validation_generator)","metadata":{"execution":{"iopub.status.busy":"2023-06-16T13:59:28.021904Z","iopub.execute_input":"2023-06-16T13:59:28.022691Z","iopub.status.idle":"2023-06-16T13:59:29.289973Z","shell.execute_reply.started":"2023-06-16T13:59:28.022621Z","shell.execute_reply":"2023-06-16T13:59:29.288659Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"validation_generator","metadata":{"execution":{"iopub.status.busy":"2023-06-16T13:34:53.824658Z","iopub.execute_input":"2023-06-16T13:34:53.825829Z","iopub.status.idle":"2023-06-16T13:34:53.835404Z","shell.execute_reply.started":"2023-06-16T13:34:53.825777Z","shell.execute_reply":"2023-06-16T13:34:53.83385Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tensorflow.keras.preprocessing.image import img_to_array\n","metadata":{"execution":{"iopub.status.busy":"2023-06-17T00:34:19.381554Z","iopub.execute_input":"2023-06-17T00:34:19.3829Z","iopub.status.idle":"2023-06-17T00:34:19.388679Z","shell.execute_reply.started":"2023-06-17T00:34:19.382826Z","shell.execute_reply":"2023-06-17T00:34:19.38734Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"np.array([img_to_array(img)])","metadata":{"execution":{"iopub.status.busy":"2023-06-16T13:29:59.09692Z","iopub.execute_input":"2023-06-16T13:29:59.097382Z","iopub.status.idle":"2023-06-16T13:29:59.109789Z","shell.execute_reply.started":"2023-06-16T13:29:59.097338Z","shell.execute_reply":"2023-06-16T13:29:59.108082Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"img = Image.open(\"/kaggle/input/rsna-breast-cancer-512-pngs/10884_829440179.png\").convert('RGB')\nX = np.array([img_to_array(img)])\nprint(int(not int(model.predict(val_datagen.flow(X))[0][0])))\n\n","metadata":{"execution":{"iopub.status.busy":"2023-06-16T14:00:02.002546Z","iopub.execute_input":"2023-06-16T14:00:02.003127Z","iopub.status.idle":"2023-06-16T14:00:02.504233Z","shell.execute_reply.started":"2023-06-16T14:00:02.003076Z","shell.execute_reply":"2023-06-16T14:00:02.503205Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"int(not 1)","metadata":{"execution":{"iopub.status.busy":"2023-06-16T13:58:51.594958Z","iopub.execute_input":"2023-06-16T13:58:51.596208Z","iopub.status.idle":"2023-06-16T13:58:51.603614Z","shell.execute_reply.started":"2023-06-16T13:58:51.59616Z","shell.execute_reply":"2023-06-16T13:58:51.602365Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X = tf.reshape(rotate, [1, 512, 512, 3])\nprint(model.predict(X)[0][0])","metadata":{"execution":{"iopub.status.busy":"2023-06-15T13:41:51.714223Z","iopub.execute_input":"2023-06-15T13:41:51.714612Z","iopub.status.idle":"2023-06-15T13:41:52.093438Z","shell.execute_reply.started":"2023-06-15T13:41:51.714578Z","shell.execute_reply":"2023-06-15T13:41:52.092694Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.metrics import precision_recall_curve\nprs, recs, _ = precision_recall_curve(y_true, lr_probs)\n\nplt.plot(recs, prs)\nplt.ylim([0, 1.1])\nplt.xlim([0, 1.1])\nplt.xlabel('Recall')\nplt.ylabel('Precision')\nplt.title('PR_curve')\n","metadata":{"execution":{"iopub.status.busy":"2023-06-15T13:27:10.657194Z","iopub.execute_input":"2023-06-15T13:27:10.6576Z","iopub.status.idle":"2023-06-15T13:27:10.820142Z","shell.execute_reply.started":"2023-06-15T13:27:10.657563Z","shell.execute_reply":"2023-06-15T13:27:10.818764Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\nfrom sklearn.metrics import auc\nprint(auc(recs, prs))","metadata":{"execution":{"iopub.status.busy":"2023-06-15T13:27:14.005706Z","iopub.execute_input":"2023-06-15T13:27:14.006833Z","iopub.status.idle":"2023-06-15T13:27:14.013613Z","shell.execute_reply.started":"2023-06-15T13:27:14.006787Z","shell.execute_reply":"2023-06-15T13:27:14.012484Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_pred=[]\n\nfor prob in pred:\n    if prob >= 0.5:\n        y_pred.append(1)\n    else:\n        y_pred.append(0)","metadata":{"execution":{"iopub.status.busy":"2023-06-15T13:27:15.149332Z","iopub.execute_input":"2023-06-15T13:27:15.149709Z","iopub.status.idle":"2023-06-15T13:27:15.15728Z","shell.execute_reply.started":"2023-06-15T13:27:15.149673Z","shell.execute_reply":"2023-06-15T13:27:15.155523Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"cm=confusion_matrix(y_true,y_pred)","metadata":{"execution":{"iopub.status.busy":"2023-06-15T13:27:15.920268Z","iopub.execute_input":"2023-06-15T13:27:15.920722Z","iopub.status.idle":"2023-06-15T13:27:15.927126Z","shell.execute_reply.started":"2023-06-15T13:27:15.92066Z","shell.execute_reply":"2023-06-15T13:27:15.925824Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class_names=['Normal','Cancer']\n\nax=sns.heatmap(cm, annot=True, fmt='.0f', cmap='PiYG', annot_kws={'size':16}, xticklabels=class_names, yticklabels=class_names)\n\n\nax.set_xlabel('Prediction')\nax.set_ylabel('Truth')","metadata":{"execution":{"iopub.status.busy":"2023-06-15T13:27:16.449352Z","iopub.execute_input":"2023-06-15T13:27:16.449742Z","iopub.status.idle":"2023-06-15T13:27:16.657445Z","shell.execute_reply.started":"2023-06-15T13:27:16.449713Z","shell.execute_reply":"2023-06-15T13:27:16.655888Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(classification_report(y_true, y_pred))","metadata":{"execution":{"iopub.status.busy":"2023-06-15T13:27:29.719918Z","iopub.execute_input":"2023-06-15T13:27:29.720304Z","iopub.status.idle":"2023-06-15T13:27:29.733151Z","shell.execute_reply.started":"2023-06-15T13:27:29.720272Z","shell.execute_reply":"2023-06-15T13:27:29.731806Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"DF_train","metadata":{"execution":{"iopub.status.busy":"2023-06-15T03:52:46.9263Z","iopub.execute_input":"2023-06-15T03:52:46.926792Z","iopub.status.idle":"2023-06-15T03:52:46.960044Z","shell.execute_reply.started":"2023-06-15T03:52:46.926745Z","shell.execute_reply":"2023-06-15T03:52:46.958803Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"DF_train = df_train.copy()\nfor i in range(len(DF_train)):\n    DF_train.loc[i, 'path'] = os.path.join(RSNA_512_path + '/' + \n                                           str(DF_train.loc[i, 'patient_id']) + '_' + \n                                           str(DF_train.loc[i, 'image_id']) + '.png')","metadata":{"execution":{"iopub.status.busy":"2023-06-14T08:07:14.481433Z","iopub.execute_input":"2023-06-14T08:07:14.482066Z","iopub.status.idle":"2023-06-14T08:09:03.907364Z","shell.execute_reply.started":"2023-06-14T08:07:14.482033Z","shell.execute_reply":"2023-06-14T08:09:03.906038Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = load_model('/kaggle/input/other2/mammography_pred_model.h5')\n","metadata":{"execution":{"iopub.status.busy":"2023-06-14T07:23:57.584098Z","iopub.execute_input":"2023-06-14T07:23:57.585268Z","iopub.status.idle":"2023-06-14T07:24:00.204239Z","shell.execute_reply.started":"2023-06-14T07:23:57.585196Z","shell.execute_reply":"2023-06-14T07:24:00.202112Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tensorflow.keras.preprocessing.image import img_to_array\n","metadata":{"execution":{"iopub.status.busy":"2023-06-15T13:29:05.37212Z","iopub.execute_input":"2023-06-15T13:29:05.372513Z","iopub.status.idle":"2023-06-15T13:29:05.37802Z","shell.execute_reply.started":"2023-06-15T13:29:05.372479Z","shell.execute_reply":"2023-06-15T13:29:05.376559Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"pathcheck='/kaggle/input/rsna-breast-cancer-512-pngs/12918_610792199.png'","metadata":{"execution":{"iopub.status.busy":"2023-06-15T04:14:52.707323Z","iopub.execute_input":"2023-06-15T04:14:52.7078Z","iopub.status.idle":"2023-06-15T04:14:52.713925Z","shell.execute_reply.started":"2023-06-15T04:14:52.707757Z","shell.execute_reply":"2023-06-15T04:14:52.712373Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"pathche='12918_610792199.png'","metadata":{"execution":{"iopub.status.busy":"2023-06-15T04:15:58.814624Z","iopub.execute_input":"2023-06-15T04:15:58.81576Z","iopub.status.idle":"2023-06-15T04:15:58.821689Z","shell.execute_reply.started":"2023-06-15T04:15:58.815705Z","shell.execute_reply":"2023-06-15T04:15:58.82038Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# for path in glob.glob('train/normal/*'):\n# #     print(path[13:])\n#     if path[13:]==pathche:\n#         print(path)\n#         break\nimg = Image.open(\"/kaggle/input/rsna-breast-cancer-512-pngs/1261_1921378782.png\").convert('RGB')\nX = tf.reshape(img_to_array(img), [1, 512, 512, 3])\nprint(model.predict(X)[0][0])","metadata":{"execution":{"iopub.status.busy":"2023-06-15T13:29:07.011065Z","iopub.execute_input":"2023-06-15T13:29:07.011426Z","iopub.status.idle":"2023-06-15T13:29:08.060195Z","shell.execute_reply.started":"2023-06-15T13:29:07.011392Z","shell.execute_reply":"2023-06-15T13:29:08.058804Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"DF.shape","metadata":{"execution":{"iopub.status.busy":"2023-06-14T08:11:07.861285Z","iopub.execute_input":"2023-06-14T08:11:07.861954Z","iopub.status.idle":"2023-06-14T08:11:07.875001Z","shell.execute_reply.started":"2023-06-14T08:11:07.8619Z","shell.execute_reply":"2023-06-14T08:11:07.87379Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"DF_train.loc[DF_train.cancer == 0].shape","metadata":{"execution":{"iopub.status.busy":"2023-06-14T08:07:01.982168Z","iopub.execute_input":"2023-06-14T08:07:01.982657Z","iopub.status.idle":"2023-06-14T08:07:01.995844Z","shell.execute_reply.started":"2023-06-14T08:07:01.98261Z","shell.execute_reply":"2023-06-14T08:07:01.994006Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"val_df_cancer = DF.loc[DF.cancer == 0].reset_index(drop = True)\ndestination_dir = '/kaggle/working/test'\ndestination_dir_sub = '/kaggle/working/test/normal'\n\nif not os.path.exists(destination_dir):\n    os.makedirs(destination_dir)\n\nif not os.path.exists(destination_dir_sub):\n    os.makedirs(destination_dir_sub)   \n    \nfor path in val_df_cancer['path']:\n    shutil.copy2(path, destination_dir_sub)    \n    #     fit_image(path, destination_dir_sub)    \n","metadata":{"execution":{"iopub.status.busy":"2023-06-14T08:11:55.148816Z","iopub.execute_input":"2023-06-14T08:11:55.15077Z","iopub.status.idle":"2023-06-14T08:11:59.696799Z","shell.execute_reply.started":"2023-06-14T08:11:55.150659Z","shell.execute_reply":"2023-06-14T08:11:59.694453Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"DF.shape","metadata":{"execution":{"iopub.status.busy":"2023-06-14T08:12:24.267483Z","iopub.execute_input":"2023-06-14T08:12:24.268072Z","iopub.status.idle":"2023-06-14T08:12:24.279093Z","shell.execute_reply.started":"2023-06-14T08:12:24.268023Z","shell.execute_reply":"2023-06-14T08:12:24.276817Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tensorflow.keras.preprocessing.image import img_to_array\n","metadata":{"execution":{"iopub.status.busy":"2023-06-14T07:22:56.034453Z","iopub.execute_input":"2023-06-14T07:22:56.034983Z","iopub.status.idle":"2023-06-14T07:22:56.042534Z","shell.execute_reply.started":"2023-06-14T07:22:56.034935Z","shell.execute_reply":"2023-06-14T07:22:56.040553Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"img = Image.open(DF_train.iloc[4, -1]).convert('RGB')\nX = tf.reshape(img_to_array(img), [1, 512, 512, 3])\nprint(model.predict(X)[0][0])\n","metadata":{"execution":{"iopub.status.busy":"2023-06-14T07:24:26.832116Z","iopub.execute_input":"2023-06-14T07:24:26.832587Z","iopub.status.idle":"2023-06-14T07:24:28.944486Z","shell.execute_reply.started":"2023-06-14T07:24:26.832542Z","shell.execute_reply":"2023-06-14T07:24:28.942638Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_datagen=ImageDataGenerator(\n                                rescale=1./255.,\n                                zoom_range=0.2,\n                                )\nval_datagen=ImageDataGenerator(rescale=1./255.)\n# train_path = '/kaggle/working/train'\nval_path = '/kaggle/working/val'\n\n# train_generator = train_datagen.flow_from_directory(\n#     train_path,\n#     target_size = (512, 512),\n#     batch_size = 32,\n#     class_mode = 'binary'\n# )\nvalidation_generator = val_datagen.flow_from_directory(\n        val_path,\n        target_size = (512, 512),\n        batch_size = 16,\n        class_mode = 'binary'\n)","metadata":{"execution":{"iopub.status.busy":"2023-06-14T08:13:04.050798Z","iopub.execute_input":"2023-06-14T08:13:04.052527Z","iopub.status.idle":"2023-06-14T08:13:04.171096Z","shell.execute_reply.started":"2023-06-14T08:13:04.052461Z","shell.execute_reply":"2023-06-14T08:13:04.169026Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"pred=model.predict(validation_generator)","metadata":{"execution":{"iopub.status.busy":"2023-06-14T08:14:48.518566Z","iopub.execute_input":"2023-06-14T08:14:48.519102Z","iopub.status.idle":"2023-06-14T08:26:12.541155Z","shell.execute_reply.started":"2023-06-14T08:14:48.519061Z","shell.execute_reply":"2023-06-14T08:26:12.538043Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_pred=[]\n\nfor prob in pred:\n    if prob >= 0.5:\n        y_pred.append(1)\n    else:\n        y_pred.append(0)","metadata":{"execution":{"iopub.status.busy":"2023-06-14T08:28:33.112343Z","iopub.execute_input":"2023-06-14T08:28:33.112805Z","iopub.status.idle":"2023-06-14T08:28:33.121593Z","shell.execute_reply.started":"2023-06-14T08:28:33.112771Z","shell.execute_reply":"2023-06-14T08:28:33.120445Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"len(validation_generator.filenames)","metadata":{"execution":{"iopub.status.busy":"2023-06-14T08:29:46.167158Z","iopub.execute_input":"2023-06-14T08:29:46.168287Z","iopub.status.idle":"2023-06-14T08:29:46.177468Z","shell.execute_reply.started":"2023-06-14T08:29:46.168237Z","shell.execute_reply":"2023-06-14T08:29:46.175226Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"temp_df = pd.DataFrame([y_pred, validation_generator.filenames]).rename({0:'pred', 1:'path'}).T","metadata":{"execution":{"iopub.status.busy":"2023-06-14T08:31:54.454557Z","iopub.execute_input":"2023-06-14T08:31:54.455161Z","iopub.status.idle":"2023-06-14T08:31:54.527087Z","shell.execute_reply.started":"2023-06-14T08:31:54.455109Z","shell.execute_reply":"2023-06-14T08:31:54.525559Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"temp_df.loc[temp_df.pred == 0]","metadata":{"execution":{"iopub.status.busy":"2023-06-14T08:32:09.202208Z","iopub.execute_input":"2023-06-14T08:32:09.202686Z","iopub.status.idle":"2023-06-14T08:32:09.219937Z","shell.execute_reply.started":"2023-06-14T08:32:09.202643Z","shell.execute_reply":"2023-06-14T08:32:09.218188Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"null_true = []","metadata":{"execution":{"iopub.status.busy":"2023-06-14T07:20:17.65962Z","iopub.execute_input":"2023-06-14T07:20:17.660118Z","iopub.status.idle":"2023-06-14T07:20:17.666214Z","shell.execute_reply.started":"2023-06-14T07:20:17.660073Z","shell.execute_reply":"2023-06-14T07:20:17.664814Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_datagen=ImageDataGenerator(\n                                rescale=1./255.,\n                                zoom_range=0.2,\n                                )\nval_datagen=ImageDataGenerator(rescale=1./255.)\nval_path = '/kaggle/input/rsna-breast-cancer-512-pngs/10442_1119390120.png'\n\nvalidation_generator = val_datagen.flow_from_directory(\n        val_path,\n        target_size = (512, 512),\n        batch_size = 16,\n        class_mode = 'binary'\n)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"rm -r  /kaggle/working/test_test","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"ls ","metadata":{"execution":{"iopub.status.busy":"2023-06-14T09:02:14.501909Z","iopub.execute_input":"2023-06-14T09:02:14.50246Z","iopub.status.idle":"2023-06-14T09:02:14.897376Z","shell.execute_reply.started":"2023-06-14T09:02:14.502407Z","shell.execute_reply":"2023-06-14T09:02:14.894379Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"val_df_cancer = DF.loc[DF.cancer == 0].reset_index(drop = True)\ndestination_dir = '/kaggle/working/test_test'\ndestination_dir_sub = '/kaggle/working/test_test/normal/'\n\nif not os.path.exists(destination_dir):\n    os.makedirs(destination_dir)\n\nif not os.path.exists(destination_dir_sub):\n    os.makedirs(destination_dir_sub)   \n    \nfor path in val_df_cancer['path']:\n    shutil.copy2('/kaggle/input/rsna-breast-cancer-512-pngs/10442_1119390120.png', destination_dir_sub)       \n    #     fit_image(path, destination_dir_sub)    \n","metadata":{"execution":{"iopub.status.busy":"2023-06-14T09:02:20.186278Z","iopub.execute_input":"2023-06-14T09:02:20.186851Z","iopub.status.idle":"2023-06-14T09:02:22.174214Z","shell.execute_reply.started":"2023-06-14T09:02:20.186802Z","shell.execute_reply":"2023-06-14T09:02:22.172227Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"ls test_test/normal","metadata":{"execution":{"iopub.status.busy":"2023-06-14T09:02:30.186761Z","iopub.execute_input":"2023-06-14T09:02:30.187191Z","iopub.status.idle":"2023-06-14T09:02:30.554631Z","shell.execute_reply.started":"2023-06-14T09:02:30.187156Z","shell.execute_reply":"2023-06-14T09:02:30.553006Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\nval_datagen=ImageDataGenerator(rescale=1./255.)\nval_path = '/kaggle/working/test_test'\n\nvalidation_generator = val_datagen.flow_from_directory(\n        val_path,\n        target_size = (512, 512),\n        batch_size = 1,\n        class_mode = 'binary'\n)","metadata":{"execution":{"iopub.status.busy":"2023-06-14T09:02:34.492266Z","iopub.execute_input":"2023-06-14T09:02:34.492735Z","iopub.status.idle":"2023-06-14T09:02:34.607158Z","shell.execute_reply.started":"2023-06-14T09:02:34.492655Z","shell.execute_reply":"2023-06-14T09:02:34.605451Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"validation_generator.filenames","metadata":{"execution":{"iopub.status.busy":"2023-06-14T09:02:37.090414Z","iopub.execute_input":"2023-06-14T09:02:37.090902Z","iopub.status.idle":"2023-06-14T09:02:37.102718Z","shell.execute_reply.started":"2023-06-14T09:02:37.09086Z","shell.execute_reply":"2023-06-14T09:02:37.101435Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.predict(validation_generator)","metadata":{"execution":{"iopub.status.busy":"2023-06-14T09:02:39.215213Z","iopub.execute_input":"2023-06-14T09:02:39.215694Z","iopub.status.idle":"2023-06-14T09:02:39.748406Z","shell.execute_reply.started":"2023-06-14T09:02:39.215653Z","shell.execute_reply":"2023-06-14T09:02:39.746607Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for i in tqdm(range(len(DF_train))):\n    img = Image.open(DF_train.iloc[i, -1]).convert('RGB')\n    X = tf.reshape(img_to_array(img), [1, 512, 512, 3])\n    if not bool(model.predict(X)[0][0]):\n        print(DF_train.iloc[i, -1])\n        null_true.append(DF_train.iloc[i, -1])","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"DF_train = df_train.loc[(df_train.cancer == 1) & (df_train.biopsy == 1)].reset_index()\nfor i in range(len(DF_train)):\n    DF_train.loc[i, 'path'] = os.path.join(RSNA_512_path + '/' + str(DF_train.loc[i, 'patient_id']) + '_' + str(DF_train.loc[i, 'image_id']) + '.png')","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def image_to_pandas(image):\n    df = pd.DataFrame([image[:,:,0].flatten(),\n                       image[:,:,1].flatten(),\n                       image[:,:,2].flatten()]).T\n    df.columns = ['Red_Channel','Green_Channel','Blue_Channel']\n    return df","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"temp = []\nfor index, path_img in enumerate(DF_train.path.iloc[:]):\n    print(path_img)\n    rgb_img = np.array(Image.open(path_img).convert('RGB'))\n    imshow(rgb_img)\n    df_rgb_img = image_to_pandas(rgb_img)\n    if not index:\n        kmeans = KMeans(n_clusters = 3, random_state = 42).fit(df_rgb_img)\n    result = kmeans.labels_.reshape(rgb_img.shape[0],rgb_img.shape[1])\n    fig, axes = plt.subplots(1,3, figsize=(15, 12))\n    for n, ax in enumerate(axes.flatten()):\n        img = Image.open(path_img).convert('RGB')\n        dog = np.array(img)\n        dog[:, :, 0] = dog[:, :, 0]*(result==[n])\n        dog[:, :, 1] = dog[:, :, 1]*(result==[n])\n        dog[:, :, 2] = dog[:, :, 2]*(result==[n])\n        temp.append(dog)\n        ax.imshow(dog);\n        ax.set_axis_off()\n    fig.tight_layout()\n    plt.show()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"temp_dog = dog\ntemp_dog = temp_dog[:, :, 1]*2000\nplt.imshow(dog)\nplt.show()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def pixel_plotter(df):\n    x_3d = df['Red_Channel']\n    y_3d = df['Green_Channel']\n    z_3d = df['Blue_Channel']\n    \n    color_list = list(zip(df['Red_Channel'].to_list(),\n                          df['Blue_Channel'].to_list(),\n                          df['Green_Channel'].to_list()))\n    norm = colors.Normalize(vmin=0,vmax=1.)\n    norm.autoscale(color_list)\n    p_color = norm(color_list).tolist()\n    \n    fig = plt.figure(figsize=(12,10))\n    ax_3d = plt.axes(projection='3d')\n    ax_3d.scatter3D(xs = x_3d, ys =  y_3d, zs = z_3d, \n                    c = p_color, alpha = 0.55);\n    \n    ax_3d.set_xlim3d(0, x_3d.max())\n    ax_3d.set_ylim3d(0, y_3d.max())\n    ax_3d.set_zlim3d(0, z_3d.max())\n    ax_3d.invert_zaxis()\n    \n    \n    ax_3d.view_init(-165, 60)\npixel_plotter(df_rgb_img)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_rgb_img['cluster'] = result.flatten()\ndef pixel_plotter_clusters(df):\n    x_3d = df['Red_Channel']\n    y_3d = df['Green_Channel']\n    z_3d = df['Blue_Channel']\n    \n    fig = plt.figure(figsize=(12,10))\n    ax_3d = plt.axes(projection='3d')\n    ax_3d.scatter3D(xs = x_3d, ys =  y_3d, zs = z_3d, \n                    c = df['cluster'], alpha = 0.55);\n    \n    ax_3d.set_xlim3d(0, x_3d.max())\n    ax_3d.set_ylim3d(0, y_3d.max())\n    ax_3d.set_zlim3d(0, z_3d.max())\n    ax_3d.invert_zaxis()\n    \n    \n    ax_3d.view_init(-165, 60)\npixel_plotter_clusters(df_rgb_img)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.figure(num=None, figsize=(8, 6), dpi=80)\nkmeans = KMeans(n_clusters=  4, random_state = 42).fit(df_doggo)\nresult = kmeans.labels_.reshape(dog.shape[0],dog.shape[1])\nimshow(result, cmap='viridis')\nplt.show()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"fig, axes = plt.subplots(2,2, figsize=(12, 12))\nfor n, ax in enumerate(axes.flatten()):\n    ax.imshow(result==[n], cmap='gray');\n    ax.set_axis_off()\n    \nfig.tight_layout()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"fig, axes = plt.subplots(1,3, figsize=(15, 12))\nfor n, ax in enumerate(axes.flatten()):\n#     dog = imread(img_path)\n    img = Image.open(img_path).convert('RGB')\n    dog = np.array(img)\n    dog[:, :, 0] = dog[:, :, 0]*(result==[n])\n    dog[:, :, 1] = dog[:, :, 1]*(result==[n])\n    dog[:, :, 2] = dog[:, :, 2]*(result==[n])\n    ax.imshow(dog);\n    ax.set_axis_off()\nfig.tight_layout()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}