row_id
int64
0
48.4k
init_message
stringlengths
1
342k
conversation_hash
stringlengths
32
32
scores
dict
42,669
В следующем коде при изменении размера окна есть чёрные области. Как это исправить?: pygame.init() screen = pygame.display.set_mode((800, 600), pygame.RESIZABLE) # For borderless, use pygame.NOFRAME done = False fuchsia = (255, 0, 128) # Transparency color # Create layered window hwnd = pygame.display.get_wm_info()["window"] win32gui.SetWindowLong(hwnd, win32con.GWL_EXSTYLE, win32gui.GetWindowLong(hwnd, win32con.GWL_EXSTYLE) | win32con.WS_EX_LAYERED) # Set window transparency color win32gui.SetLayeredWindowAttributes(hwnd, win32api.RGB(*fuchsia), 0, win32con.LWA_COLORKEY) while not done: for event in pygame.event.get(): if event.type == pygame.QUIT: done = True elif event.type == pygame.VIDEORESIZE: screen.fill(fuchsia) pygame.display.update() screen.fill(fuchsia) # Transparent background pygame.display.update()
fcca696e6608a2e78a27785c9c582521
{ "intermediate": 0.4217310845851898, "beginner": 0.38580700755119324, "expert": 0.19246187806129456 }
42,670
В следующем коде обновление застывает при изменении размера окна. Как это исправить?: pygame.init() screen = pygame.display.set_mode((800, 600), pygame.RESIZABLE) # For borderless, use pygame.NOFRAME done = False fuchsia = (255, 0, 128) # Transparency color # Create layered window hwnd = pygame.display.get_wm_info()["window"] win32gui.SetWindowLong(hwnd, win32con.GWL_EXSTYLE, win32gui.GetWindowLong(hwnd, win32con.GWL_EXSTYLE) | win32con.WS_EX_LAYERED) # Set window transparency color win32gui.SetLayeredWindowAttributes(hwnd, win32api.RGB(*fuchsia), 0, win32con.LWA_COLORKEY) while not done: for event in pygame.event.get(): if event.type == pygame.QUIT: done = True elif event.type == pygame.VIDEORESIZE: pygame.display.update() screen.fill(fuchsia) # Transparent background pygame.display.update()
02c49425b58fd901d7dbf4ff025e5d0d
{ "intermediate": 0.4483437240123749, "beginner": 0.29666903614997864, "expert": 0.2549872100353241 }
42,671
My OS is openSUSE Tumbleweed, I am trying to install "checkinstall" but I am having problems, I tried using zypper but says package not found, tried to find it on the YaST2 software manager and couldn't, I tried to download the .ymp file and although it installs, it ends up with the output "Installation was only partially successful.", and then I checked in the terminal and it is not installed, checked in YaST2 software manager and there isn't there. What could be wrong? Why I can't install it and how can I do it correctly?
54582eb7831e207bcb7571f0417bf8da
{ "intermediate": 0.40797218680381775, "beginner": 0.3480278253555298, "expert": 0.24400001764297485 }
42,672
1_ Translate the following legal text into colloquial Farsi 2_ Place the Persian and English text side by side in the table 3_ From the beginning to the end of the text, there should be an English sentence on the left side and a Persian sentence on the right side. 4- Using legal language for Persian translation ._ Place the Farsi and English text line by line from one point to the first point next to each other in such a way that one line of English text is followed by two empty lines, followed by the Persian translation and continue this process until the end of the text.(b) Public Law Public Law comprises (i) Constitutional Law, (ii) Administrative Law, and (ii) Criminal Law. 1 Constitutional Law has been defined as the rules which regulate the structure of tbe principal organs of government and their relationship to each other, and determine their principal functions. This subject includes choice of monarch, his or her powers and prerogative; the constitution of the legislature; powers and privileges of Members of Parliament; the relationship between the separate chambers of Parliament; the status of Ministers; the civil service; the armed forces; the police; the relations between the central government and local authorities; the making of treaties; admission and rights of aliens; the courts of justice; liberties of speech, of meeting, of association; and voting rights. Administrative Law is defined as that body of legal principles wbich concerns the rights and duties arising from the impact upon the individ- ual of the actual functioning of the executive instruments of government. (C. K. Allen: Law and Orders.) For example, administrative law deter- mines the legal rights of a private citizen whose house a local authority intends to acquire compulsorily. Criminal Law has already been described, with its distinction from civil law.
75bf11eac723cbcad50bac635d5d0a5a
{ "intermediate": 0.32450252771377563, "beginner": 0.3969421684741974, "expert": 0.27855533361434937 }
42,673
My OS is openSUSE Tumbleweed, I am trying to install “checkinstall” but I am having problems, I tried using zypper but says package not found, tried to find it on the YaST2 software manager and couldn’t, I tried to download the .ymp file and although it installs, it ends up with the output “Installation was only partially successful.”, and then I checked in the terminal and it is not installed, checked in YaST2 software manager and there isn’t there. What could be wrong? Why I can’t install it and how can I do it correctly? I tried downloading the source and running make and I got errors (changed dollar sign for "<" because it is giving me errors when pasting it here) > make for file in locale/checkinstall-*.po ; do \ case >{file} in \ locale/checkinstall-template.po) ;; \ *) \ out=`echo >file | sed -s 's/po/mo/'` ; \ msgfmt -o >{out} >{file} ; \ if [ >? != 0 ] ; then \ exit 1 ; \ fi ; \ ;; \ esac ; \ done make -C installwatch make[1]: Entering directory '/home/myuser/checkinstall-1.6.2/installwatch' ./create-localdecls Checking truncate argument type... off_t Checking readlinkat result type... ssize_t Checking libc version... libc.so.6 Checking glibc subversion... Treated as glibc >= 2.1 (finger crossed) gcc -Wall -c -D_GNU_SOURCE -DPIC -fPIC -D_REENTRANT -DVERSION=\"0.7.0beta7\" installwatch.c installwatch.c: In function ‘true_stat’: installwatch.c:152:27: error: ‘_STAT_VER’ undeclared (first use in this function) 152 | return true_xstat(_STAT_VER,pathname,info); | ^~~~~~~~~ installwatch.c:152:27: note: each undeclared identifier is reported only once for each function it appears in installwatch.c: In function ‘true_mknod’: installwatch.c:156:28: error: ‘_MKNOD_VER’ undeclared (first use in this function) 156 | return true_xmknod(_MKNOD_VER,pathname,mode,&dev); | ^~~~~~~~~~ installwatch.c: In function ‘true_lstat’: installwatch.c:160:28: error: ‘_STAT_VER’ undeclared (first use in this function) 160 | return true_lxstat(_STAT_VER,pathname,info); | ^~~~~~~~~ installwatch.c: At top level: installwatch.c:2942:5: error: conflicting types for ‘readlink’; have ‘int(const char *, char *, size_t)’ {aka ‘int(const char *, char *, long unsigned int)’} 2942 | int readlink(const char *path,char *buf,size_t bufsiz) { | ^~~~~~~~ In file included from /usr/include/bits/sigstksz.h:24, from /usr/include/signal.h:328, from /usr/include/sys/param.h:28, from installwatch.c:31: /usr/include/unistd.h:838:16: note: previous declaration of ‘readlink’ with type ‘ssize_t(const char * restrict, char * restrict, size_t)’ {aka ‘long int(const char * restrict, char * restrict, long unsigned int)’} 838 | extern ssize_t readlink (const char *__restrict __path, | ^~~~~~~~ installwatch.c:3080:5: error: conflicting types for ‘scandir’; have ‘int(const char *, struct dirent ***, int (*)(const struct dirent *), int (*)(const void *, const void *))’ 3080 | int scandir( const char *dir,struct dirent ***namelist, | ^~~~~~~ In file included from installwatch.c:49: /usr/include/dirent.h:257:12: note: previous declaration of ‘scandir’ with type ‘int(const char * restrict, struct dirent *** restrict, int (*)(const struct dirent *), int (*)(const struct dirent **, const struct dirent **))’ 257 | extern int scandir (const char *__restrict __dir, | ^~~~~~~ installwatch.c:3692:5: error: conflicting types for ‘scandir64’; have ‘int(const char *, struct dirent64 ***, int (*)(const struct dirent64 *), int (*)(const void *, const void *))’ 3692 | int scandir64( const char *dir,struct dirent64 ***namelist, | ^~~~~~~~~ /usr/include/dirent.h:280:12: note: previous declaration of ‘scandir64’ with type ‘int(const char * restrict, struct dirent64 *** restrict, int (*)(const struct dirent64 *), int (*)(const struct dirent64 **, const struct dirent64 **))’ 280 | extern int scandir64 (const char *__restrict __dir, | ^~~~~~~~~ installwatch.c: In function ‘true_stat’: installwatch.c:153:1: warning: control reaches end of non-void function [-Wreturn-type] 153 | } | ^ installwatch.c: In function ‘true_lstat’: installwatch.c:161:1: warning: control reaches end of non-void function [-Wreturn-type] 161 | } | ^ installwatch.c: In function ‘true_mknod’: installwatch.c:157:1: warning: control reaches end of non-void function [-Wreturn-type] 157 | } | ^ make[1]: *** [Makefile:22: installwatch.o] Error 1 make[1]: Leaving directory '/home/myuser/checkinstall-1.6.2/installwatch' make: *** [Makefile:11: all] Error 2
746782834d123425f81024000c9a371d
{ "intermediate": 0.38071271777153015, "beginner": 0.43050044775009155, "expert": 0.18878687918186188 }
42,674
Ok I installed SDL-Mixer-X and it the make install output was this: $ sudo make install [sudo] password for root: [100%] Built target SDL2_mixer_ext_Static Install the project… – Install configuration: “Release” – Installing: /usr/local/lib64/libSDL2_mixer_ext.a – Installing: /usr/local/lib64/cmake/SDL2_mixer_ext/SDL2_mixer_ext-static-targets.cmake – Installing: /usr/local/lib64/cmake/SDL2_mixer_ext/SDL2_mixer_ext-static-targets-release.cmake – Installing: /usr/local/include/SDL2/SDL_mixer_ext.h – Installing: /usr/local/lib64/cmake/SDL2_mixer_ext/SDL2_mixer_extConfig.cmake – Installing: /usr/local/lib64/pkgconfig/SDL2_mixer_ext.pc So it looks like it worked perfectly, but two things: Since sudo make uninstall is not available and if I don't log this output, how can I get it again when I want to uninstall it? Do I have to keep this output in a file for in case I need to uninstall?
6f8f735128b798cbffd5b5e74e5ac593
{ "intermediate": 0.5419608354568481, "beginner": 0.23649534583091736, "expert": 0.22154384851455688 }
42,675
from statsforecast import StatsForecast from statsforecast.models import HoltWinters from statsforecast.utils import ConformalIntervals import numpy as np import polars as pl # Polars option to display all rows pl.Config.set_tbl_rows(None) # Initialize the models models = [ HoltWinters(season_length=4) ] # Initialize the StatsForecast model sf = StatsForecast(models=models, freq='1w', n_jobs=-1) # Perform cross-validation with a step size of 1 to mimic an expanding window crossvalidation_df = sf.cross_validation(df=y_cl4_over_19, h=4, step_size=1, n_windows=5, sort_df=True) # Calculate the ensemble mean ensemble = crossvalidation_df[['HoltWinters']].mean(axis=1) # Create a Series for the ensemble mean ensemble_series = pl.Series('Ensemble', ensemble) # Add the ensemble mean as a new column to the DataFrame crossvalidation_df = crossvalidation_df.with_columns(ensemble_series) def wmape(y_true, y_pred): return np.abs(y_true - y_pred).sum() / np.abs(y_true).sum() # Calculate the WMAPE for the ensemble model wmape_value = wmape(crossvalidation_df['y'], crossvalidation_df['Ensemble']) print('Average WMAPE for Ensemble: ', round(wmape_value, 4)) # Calculate the errors for the ensemble model errors = crossvalidation_df['y'] - crossvalidation_df['Ensemble'] # For an individual forecast individual_accuracy = 1 - (abs(crossvalidation_df['y'] - crossvalidation_df['Ensemble']) / crossvalidation_df['y']) individual_bias = (crossvalidation_df['Ensemble'] / crossvalidation_df['y']) - 1 # Add these calculations as new columns to DataFrame crossvalidation_df = crossvalidation_df.with_columns([ individual_accuracy.alias("individual_accuracy"), individual_bias.alias("individual_bias") ]) # Print the individual accuracy and bias for each week for row in crossvalidation_df.to_dicts(): id = row['unique_id'] date = row['ds'] accuracy = row['individual_accuracy'] bias = row['individual_bias'] print(f"{id}, {date}, Individual Accuracy: {accuracy:.4f}, Individual Bias: {bias:.4f}") # For groups of forecasts group_accuracy = 1 - (errors.abs().sum() / crossvalidation_df['y'].sum()) group_bias = (crossvalidation_df['Ensemble'].sum() / crossvalidation_df['y'].sum()) - 1 # Print the average group accuracy and group bias over all folds for the ensemble model print('Average Group Accuracy: ', round(group_accuracy, 4)) print('Average Group Bias: ', round(group_bias, 4)) 12519007_US01_8_1108349, 2023-11-13 00:00:00, Individual Accuracy: -0.4972, Individual Bias: 1.4972 12519007_US01_8_1108349, 2023-11-20 00:00:00, Individual Accuracy: 0.4678, Individual Bias: -0.5322 12519007_US01_8_1108349, 2023-11-06 00:00:00, Individual Accuracy: 0.9100, Individual Bias: -0.0900 12519007_US01_8_1108349, 2023-11-13 00:00:00, Individual Accuracy: -1.7148, Individual Bias: 2.7148 12519007_US01_8_1108349, 2023-11-20 00:00:00, Individual Accuracy: 0.6192, Individual Bias: -0.3808 12519007_US01_8_1108349, 2023-11-27 00:00:00, Individual Accuracy: -5.4835, Individual Bias: 6.4835 12519007_US01_8_5338737, 2023-07-31 00:00:00, Individual Accuracy: -97.3718, Individual Bias: 98.3718 12519007_US01_8_5338737, 2023-08-14 00:00:00, Individual Accuracy: -8.2802, Individual Bias: 9.2802 12519007_US01_8_5338737, 2023-08-28 00:00:00, Individual Accuracy: -14.6154, Individual Bias: 15.6154 12519007_US01_8_5338737, 2023-09-04 00:00:00, Individual Accuracy: 0.3744, Individual Bias: -0.6256 12519007_US01_8_5338737, 2023-08-14 00:00:00, Individual Accuracy: -4.6083, Individual Bias: 5.6083 12519007_US01_8_5338737, 2023-08-28 00:00:00, Individual Accuracy: -10.1394, Individual Bias: 11.1394 there are negative values in here leading to big spread on inidividual accuracy and bias calculations, is there a way to put a constraint on group accuracy and bias calculation to ignore individual accurray and individual bias with values greater than -15 or 15? , only at the group level # For groups of forecasts group_accuracy = 1 - (errors.abs().sum() / crossvalidation_df['y'].sum()) group_bias = (crossvalidation_df['Ensemble'].sum() / crossvalidation_df['y'].sum()) - 1
7dd7a6eea0679cfea9514a7699ea75d4
{ "intermediate": 0.4016927480697632, "beginner": 0.38177216053009033, "expert": 0.2165350615978241 }
42,676
could you help me to code an argument parser using Rust and the Clap crate with the derive feature? I want something like this: maintool [subcommand] [args for that subcommand]
683485eac6e2d32dfd67dd07d8d1f33a
{ "intermediate": 0.7033630013465881, "beginner": 0.08109043538570404, "expert": 0.21554657816886902 }
42,677
You are a Python expert who can provide clear, concise, high-quality code. " import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns import cv2 import random import tensorflow as tf from tensorflow.keras.optimizers import Adam, SGD, RMSprop, AdamW, Adadelta, Adagrad, Adamax, Adafactor, Nadam, Ftrl from tensorflow.keras.preprocessing.image import ImageDataGenerator from tqdm import tqdm import os from sklearn.utils import shuffle from sklearn.preprocessing import LabelEncoder from sklearn.model_selection import train_test_split from tensorflow.keras.models import Sequential, Model, load_model from tensorflow.keras.layers import ( GlobalAveragePooling2D, Dropout, Dense, Conv2D, MaxPooling2D, Flatten, Dropout, BatchNormalization, Activation, concatenate, Conv2DTranspose, Input, Reshape, UpSampling2D, ) from tensorflow.keras.applications import ( EfficientNetV2B0, EfficientNetV2B1, EfficientNetV2B2, EfficientNetV2B3, EfficientNetV2L, EfficientNetV2M, EfficientNetV2S, ) from tensorflow.keras.applications import Xception from tensorflow.keras.applications import VGG16, VGG19 from tensorflow.keras.applications import ResNet50, ResNet101, ResNet152, ResNetRS50, ResNetRS101 from tensorflow.keras.applications import InceptionResNetV2, ConvNeXtXLarge, ConvNeXtBase, DenseNet121, MobileNetV2, NASNetLarge, NASNetMobile from tensorflow.keras.utils import to_categorical from tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau, TensorBoard, ModelCheckpoint from sklearn.metrics import classification_report, confusion_matrix import ipywidgets as widgets import io from PIL import Image from IPython.display import display, clear_output from warnings import filterwarnings from google.colab import drive drive.mount("/content/gdrive") def load_data(data_folders): X_data = [] # Combined data y_class_labels = [] # Combined classification labels y_seg_labels = [] # Combined segmentation labels for folderPath in data_folders: for label in labels: label_folder_path = os.path.join(folderPath, label) for filename in tqdm(os.listdir(label_folder_path)): if filename.endswith(".jpg"): img = cv2.imread(os.path.join(label_folder_path, filename)) img = cv2.resize(img, (image_size, image_size)) X_data.append(img) y_class_labels.append(label) seg_filename = filename.split(".")[0] + ".png" seg_img = cv2.imread(os.path.join(label_folder_path, seg_filename), 0) seg_img = cv2.resize(seg_img, (image_size, image_size)) seg_img = np.where(seg_img > 0, 1, 0) # Convert segmentation mask to binary y_seg_labels.append(seg_img) X_data = np.array(X_data) y_class_labels = np.array(y_class_labels) y_seg_labels = np.array(y_seg_labels) X_data, y_class_labels, y_seg_labels = shuffle(X_data, y_class_labels, y_seg_labels, random_state=101) return X_data, y_class_labels, y_seg_labels def split_data(X_data, y_class_labels, y_seg_labels, train_ratio, val_ratio, test_ratio): num_samples = len(X_data) num_train_samples = int(train_ratio * num_samples) num_val_samples = int(val_ratio * num_samples) num_test_samples = int(test_ratio * num_samples) X_train = X_data[:num_train_samples] y_train_class = y_class_labels[:num_train_samples] y_train_seg = y_seg_labels[:num_train_samples] X_val = X_data[num_train_samples: num_train_samples + num_val_samples] y_val_class = y_class_labels[num_train_samples: num_train_samples + num_val_samples] y_val_seg = y_seg_labels[num_train_samples: num_train_samples + num_val_samples] X_test = X_data[num_train_samples + num_val_samples: num_train_samples + num_val_samples + num_test_samples] y_test_class = y_class_labels[num_train_samples + num_val_samples: num_train_samples + num_val_samples + num_test_samples] y_test_seg = y_seg_labels[num_train_samples + num_val_samples: num_train_samples + num_val_samples + num_test_samples] # Convert class labels to categorical label_encoder = LabelEncoder() y_train_class_encoded = label_encoder.fit_transform(y_train_class) y_train_class_categorical = to_categorical(y_train_class_encoded) y_val_class_encoded = label_encoder.transform(y_val_class) y_val_class_categorical = to_categorical(y_val_class_encoded) y_test_class_encoded = label_encoder.transform(y_test_class) y_test_class_categorical = to_categorical(y_test_class_encoded) return ( X_train, y_train_class_categorical, y_train_seg, X_val, y_val_class_categorical, y_val_seg, X_test, y_test_class_categorical, y_test_seg, ) def build_model(input_shape, num_classes): num_filter = 32 # 16/32 best, 8: best classification but no segment # Encoder (Done) inputs = Input(input_shape) conv1 = Conv2D(num_filter * 1, 3, activation="linear", padding="same", strides=1)(inputs) bn1 = BatchNormalization()(conv1) relu1 = Activation("relu")(bn1) conv2 = Conv2D(num_filter * 1, 3, activation="linear", padding="same", strides=1)(relu1) bn2 = BatchNormalization()(conv2) relu2 = Activation("relu")(bn2) down1 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu2) conv3 = Conv2D(num_filter * 2, 3, activation="linear", padding="same", strides=1)(down1) bn3 = BatchNormalization()(conv3) relu3 = Activation("relu")(bn3) conv4 = Conv2D(num_filter * 2, 3, activation="linear", padding="same", strides=1)(relu3) bn4 = BatchNormalization()(conv4) relu4 = Activation("relu")(bn4) down2 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu4) conv5 = Conv2D(num_filter * 4, 3, activation="linear", padding="same", strides=1)(down2) bn5 = BatchNormalization()(conv5) relu5 = Activation("relu")(bn5) conv6 = Conv2D(num_filter * 4, 3, activation="linear", padding="same", strides=1)(relu5) bn6 = BatchNormalization()(conv6) relu6 = Activation("relu")(bn6) down3 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu6) conv7 = Conv2D(num_filter * 8, 3, activation="linear", padding="same", strides=1)(down3) bn7 = BatchNormalization()(conv7) relu7 = Activation("relu")(bn7) conv8 = Conv2D(num_filter * 8, 3, activation="linear", padding="same", strides=1)(relu7) bn8 = BatchNormalization()(conv8) relu8 = Activation("relu")(bn8) # Middle down4 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu8) conv9 = Conv2D(num_filter * 16, 3, activation="linear", padding="same", strides=1)(down4) bn9 = BatchNormalization()(conv9) relu9 = Activation("relu")(bn9) conv10 = Conv2D(num_filter * 16, 3, activation="linear", padding="same", strides=1)(relu9) bn10 = BatchNormalization()(conv10) relu10 = Activation("relu")(bn10) up1 = UpSampling2D(size=(2, 2), interpolation="bilinear")(relu10) # Decoder (Done) concat1 = concatenate([up1, relu8], axis=-1) # , axis=3 conv11 = Conv2D(num_filter * 8, 3, activation="linear", padding="same", strides=1)(concat1) bn11 = BatchNormalization()(conv11) relu11 = Activation("relu")(bn11) conv12 = Conv2D(num_filter * 8, 3, activation="linear", padding="same", strides=1)(relu11) bn12 = BatchNormalization()(conv12) relu12 = Activation("relu")(bn12) up2 = UpSampling2D(size=(2, 2), interpolation="bilinear")(relu12) concat2 = concatenate([up2, relu6], axis=-1) # , axis=3 conv13 = Conv2D(num_filter * 4, 3, activation="linear", padding="same", strides=1)(concat2) bn13 = BatchNormalization()(conv13) relu13 = Activation("relu")(bn13) conv14 = Conv2D(num_filter * 4, 3, activation="linear", padding="same", strides=1)(relu13) bn14 = BatchNormalization()(conv14) relu14 = Activation("relu")(bn14) up3 = UpSampling2D(size=(2, 2), interpolation="bilinear")(relu14) concat3 = concatenate([up3, relu4], axis=-1) # , axis=3 conv15 = Conv2D(num_filter * 2, 3, activation="linear", padding="same", strides=1)(concat3) bn15 = BatchNormalization()(conv15) relu15 = Activation("relu")(bn15) conv16 = Conv2D(num_filter * 2, 3, activation="linear", padding="same", strides=1)(relu15) bn16 = BatchNormalization()(conv16) relu16 = Activation("relu")(bn16) up4 = UpSampling2D(size=(2, 2), interpolation="bilinear")(relu16) concat4 = concatenate([up4, relu2], axis=-1) # , axis=3 conv17 = Conv2D(num_filter * 1, 3, activation="linear", padding="same", strides=1)(concat4) bn17 = BatchNormalization()(conv17) relu17 = Activation("relu")(bn17) conv18 = Conv2D(num_filter * 1, 3, activation="linear", padding="same", strides=1)(relu17) bn18 = BatchNormalization()(conv18) relu18 = Activation("relu")(bn18) # Segmentation branch segmentation_output = Conv2D(1, 1, activation="sigmoid", name="segmentation_output")(relu18) # original # Classification branch (Not done) gap1 = GlobalAveragePooling2D()(relu8) gap2 = GlobalAveragePooling2D()(relu10) gap3 = GlobalAveragePooling2D()(relu12) conv20 = Conv2D(16, 3, activation="linear", padding="same", strides=1)(segmentation_output) bn20 = BatchNormalization()(conv20) relu20 = Activation("relu")(bn20) down5 = MaxPooling2D(pool_size=(4, 4), strides=4)(relu20) conv21 = Conv2D(32, 3, activation="linear", padding="same", strides=1)(down5) bn21 = BatchNormalization()(conv21) relu21 = Activation("relu")(bn21) down6 = MaxPooling2D(pool_size=(4, 4), strides=4)(relu21) conv22 = Conv2D(64, 3, activation="linear", padding="same", strides=1)(down6) bn22 = BatchNormalization()(conv22) relu22 = Activation("relu")(bn22) down7 = MaxPooling2D(pool_size=(4, 4), strides=4)(relu22) flatten1 = Flatten()(down7) concat5 = concatenate([gap1, gap2, gap3, flatten1], axis=-1) # FC layers fc1 = Dense(1024, activation="relu")(concat5) dropout1 = Dropout(0.5)(fc1) fc2 = Dense(1024, activation="relu")(dropout1) dropout2 = Dropout(0.5)(fc2) classification_output = Dense(num_classes, activation="softmax", name="classification_output")(dropout2) # Define the model model = Model(inputs=inputs, outputs=[classification_output, segmentation_output]) return model def segmentation_loss(y_true, y_pred): y_true = tf.cast(y_true, tf.float32) y_pred = tf.cast(y_pred, tf.float32) bce_loss = tf.keras.losses.binary_crossentropy(y_true, y_pred) smooth = 1e-5 intersection = tf.reduce_sum(y_true * y_pred) union = tf.reduce_sum(y_true) + tf.reduce_sum(y_pred) dice_loss = 1.0 - 2.0 * (intersection + smooth) / (union + smooth) segmentation_loss = bce_loss + 1 * dice_loss return segmentation_loss def train_model(model, X_train, y_train_class, y_train_seg, X_val, y_val_class, y_val_seg, batch_size, epochs): checkpoint = ModelCheckpoint( "multitask_best_weights.h5", monitor="val_classification_output_accuracy", save_best_only=True, mode="max", verbose=1,) reduce_lr = ReduceLROnPlateau( monitor="val_classification_output_accuracy", factor=0.3, patience=2, min_delta=0.001, mode="auto", verbose=1,) tensorboard = TensorBoard(log_dir="logs") model.compile( optimizer=Adam(lr=0.001), loss={"classification_output": "categorical_crossentropy", "segmentation_output": segmentation_loss}, metrics={"classification_output": "accuracy", "segmentation_output": "accuracy"}, loss_weights={"classification_output": 1, "segmentation_output": 1},) history = model.fit( X_train, {"classification_output": y_train_class, "segmentation_output": y_train_seg}, validation_data=(X_val, {"classification_output": y_val_class, "segmentation_output": y_val_seg}), epochs=epochs, verbose=1, batch_size=batch_size, callbacks=[checkpoint, reduce_lr, tensorboard],) return history def evaluate_model(model, X_test, y_test_class, y_test_seg): with tf.keras.utils.custom_object_scope({"segmentation_loss": segmentation_loss}): # Load the best model weights best_model = load_model("multitask_best_weights.h5") # Evaluate the model on test data test_loss, test_class_loss, test_seg_loss, test_class_acc, test_seg_acc = best_model.evaluate( X_test, {"classification_output": y_test_class, "segmentation_output": y_test_seg}) print("Test Classification Loss:", test_class_loss) print("Test Segmentation Loss:", test_seg_loss) print("Test Classification Accuracy:", test_class_acc) print("Test Segmentation Accuracy:", test_seg_acc) # Evaluate the model on validation data val_loss, val_class_loss, val_seg_loss, val_class_acc, val_seg_acc = best_model.evaluate( X_val, {'classification_output': y_val_class, 'segmentation_output': y_val_seg}) print("Validation Classification Loss:", val_class_loss) print("Validation Segmentation Loss:", val_seg_loss) print("Validation Classification Accuracy:", val_class_acc) print("Validation Segmentation Accuracy:", val_seg_acc) # Evaluate the model on training data train_loss, train_class_loss, train_seg_loss, train_class_acc, train_seg_acc = best_model.evaluate(X_train, {'classification_output': y_train_class, 'segmentation_output': y_train_seg}) print("Train Classification Loss:", train_class_loss) print("Train Segmentation Loss:", train_seg_loss) print("Train Classification Accuracy:", train_class_acc) print("Train Segmentation Accuracy:", train_seg_acc) # Return test classification accuracy return test_class_acc def plot_performance(history): # Plot classification accuracy classification_train_accuracy = history.history["classification_output_accuracy"] classification_val_accuracy = history.history["val_classification_output_accuracy"] plt.figure(figsize=(7, 3)) plt.plot(classification_train_accuracy, label="Training Accuracy") plt.plot(classification_val_accuracy, label="Validation Accuracy") plt.title("Classification Accuracy") plt.xlabel("Epochs") plt.ylabel("Accuracy") plt.legend() plt.show() # Plot classification loss classification_train_loss = history.history["classification_output_loss"] classification_val_loss = history.history["val_classification_output_loss"] plt.figure(figsize=(7, 3)) plt.plot(classification_train_loss, "b", label="Training Loss") plt.plot(classification_val_loss, "r", label="Validation Loss") plt.title("Classification Loss") plt.xlabel("Epochs") plt.ylabel("Loss") plt.legend() plt.show() # Plot segmentation accuracy segmentation_train_accuracy = history.history["segmentation_output_accuracy"] segmentation_val_accuracy = history.history["val_segmentation_output_accuracy"] plt.figure(figsize=(7, 3)) plt.plot(segmentation_train_accuracy, label="Training Accuracy") plt.plot(segmentation_val_accuracy, label="Validation Accuracy") plt.title("Segmentation Accuracy") plt.xlabel("Epochs") plt.ylabel("Accuracy") plt.legend() plt.show() # Plot segmentation loss segmentation_train_loss = history.history["segmentation_output_loss"] segmentation_val_loss = history.history["val_segmentation_output_loss"] plt.figure(figsize=(7, 3)) plt.plot(segmentation_train_loss, "b", label="Training Loss") plt.plot(segmentation_val_loss, "r", label="Validation Loss") plt.title("Segmentation Loss") plt.xlabel("Epochs") plt.ylabel("Loss") plt.legend() plt.show() # Set image size image_size = 224 # Define labels labels = ["bridge", "excess", "good"] # Set data folders data_folders = [ "/content/gdrive/MyDrive/Deep learning/FYP_2/4 Dataset Ratio 60 20 20/jit012/jit0/f_dip/train", "/content/gdrive/MyDrive/Deep learning/FYP_2/4 Dataset Ratio 60 20 20/jit012/jit0/f_dip/val", "/content/gdrive/MyDrive/Deep learning/FYP_2/4 Dataset Ratio 60 20 20/jit012/jit0/f_dip/test",] # Load data X_data, y_class_labels, y_seg_labels = load_data(data_folders) # Set image size image_size = 224 # Split data train_ratio = 0.1 val_ratio = 0.2 test_ratio = 0.6 X_train, y_train_class, y_train_seg, X_val, y_val_class, y_val_seg, X_test, y_test_class, y_test_seg = split_data( X_data, y_class_labels, y_seg_labels, train_ratio, val_ratio, test_ratio) # Build model input_shape = (image_size, image_size, 3) num_classes = len(labels) model = build_model(input_shape, num_classes) test_class_acc_list = [] for i in range(5): print(f"\nTrain {i+1}:\n") model = build_model(input_shape, num_classes) # Train model batch_size = 16 epochs = 50 history = train_model(model, X_train, y_train_class, y_train_seg, X_val, y_val_class, y_val_seg, batch_size, epochs) # Evaluate model on test data test_class_acc = evaluate_model(model, X_test, y_test_class, y_test_seg) plot_performance(history) test_class_acc_list.append(test_class_acc) # Calculate average test classification accuracy average_test_class_acc = sum(test_class_acc_list) / len(test_class_acc_list) print("Test Classification Accuracy List:", test_class_acc_list) print("Average Test Classification Accuracy:", average_test_class_acc) " The above is the Python code with Keras to do multi-task learning with binary segmentation and classification using one mult-task learning model. I have already loaded and separated the dataset (contain both images and ground truth segmentation masks) into train:val:test ratio of 10:20:60. Add the code to check the number of images of each class in the train,val,test set respectively, e.g.For train: bridge: 12, excess: 27, good:42,... Show full code.
02c21b563b0580498e57724992c1b857
{ "intermediate": 0.43294963240623474, "beginner": 0.3695805072784424, "expert": 0.1974697858095169 }
42,678
You are a Python expert who can provide clear, concise, high-quality code. " import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns import cv2 import random import tensorflow as tf from tensorflow.keras.optimizers import Adam, SGD, RMSprop, AdamW, Adadelta, Adagrad, Adamax, Adafactor, Nadam, Ftrl from tensorflow.keras.preprocessing.image import ImageDataGenerator from tqdm import tqdm import os from sklearn.utils import shuffle from sklearn.preprocessing import LabelEncoder from sklearn.model_selection import train_test_split from tensorflow.keras.models import Sequential, Model, load_model from tensorflow.keras.layers import ( GlobalAveragePooling2D, Dropout, Dense, Conv2D, MaxPooling2D, Flatten, Dropout, BatchNormalization, Activation, concatenate, Conv2DTranspose, Input, Reshape, UpSampling2D, ) from tensorflow.keras.applications import ( EfficientNetV2B0, EfficientNetV2B1, EfficientNetV2B2, EfficientNetV2B3, EfficientNetV2L, EfficientNetV2M, EfficientNetV2S, ) from tensorflow.keras.applications import Xception from tensorflow.keras.applications import VGG16, VGG19 from tensorflow.keras.applications import ResNet50, ResNet101, ResNet152, ResNetRS50, ResNetRS101 from tensorflow.keras.applications import InceptionResNetV2, ConvNeXtXLarge, ConvNeXtBase, DenseNet121, MobileNetV2, NASNetLarge, NASNetMobile from tensorflow.keras.utils import to_categorical from tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau, TensorBoard, ModelCheckpoint from sklearn.metrics import classification_report, confusion_matrix import ipywidgets as widgets import io from PIL import Image from IPython.display import display, clear_output from warnings import filterwarnings from google.colab import drive drive.mount("/content/gdrive") def load_data(data_folders): X_data = [] # Combined data y_class_labels = [] # Combined classification labels y_seg_labels = [] # Combined segmentation labels for folderPath in data_folders: for label in labels: label_folder_path = os.path.join(folderPath, label) for filename in tqdm(os.listdir(label_folder_path)): if filename.endswith(".jpg"): img = cv2.imread(os.path.join(label_folder_path, filename)) img = cv2.resize(img, (image_size, image_size)) X_data.append(img) y_class_labels.append(label) seg_filename = filename.split(".")[0] + ".png" seg_img = cv2.imread(os.path.join(label_folder_path, seg_filename), 0) seg_img = cv2.resize(seg_img, (image_size, image_size)) seg_img = np.where(seg_img > 0, 1, 0) # Convert segmentation mask to binary y_seg_labels.append(seg_img) X_data = np.array(X_data) y_class_labels = np.array(y_class_labels) y_seg_labels = np.array(y_seg_labels) X_data, y_class_labels, y_seg_labels = shuffle(X_data, y_class_labels, y_seg_labels, random_state=101) return X_data, y_class_labels, y_seg_labels def split_data(X_data, y_class_labels, y_seg_labels, train_ratio, val_ratio, test_ratio): num_samples = len(X_data) num_train_samples = int(train_ratio * num_samples) num_val_samples = int(val_ratio * num_samples) num_test_samples = int(test_ratio * num_samples) X_train = X_data[:num_train_samples] y_train_class = y_class_labels[:num_train_samples] y_train_seg = y_seg_labels[:num_train_samples] X_val = X_data[num_train_samples: num_train_samples + num_val_samples] y_val_class = y_class_labels[num_train_samples: num_train_samples + num_val_samples] y_val_seg = y_seg_labels[num_train_samples: num_train_samples + num_val_samples] X_test = X_data[num_train_samples + num_val_samples: num_train_samples + num_val_samples + num_test_samples] y_test_class = y_class_labels[num_train_samples + num_val_samples: num_train_samples + num_val_samples + num_test_samples] y_test_seg = y_seg_labels[num_train_samples + num_val_samples: num_train_samples + num_val_samples + num_test_samples] # Convert class labels to categorical label_encoder = LabelEncoder() y_train_class_encoded = label_encoder.fit_transform(y_train_class) y_train_class_categorical = to_categorical(y_train_class_encoded) y_val_class_encoded = label_encoder.transform(y_val_class) y_val_class_categorical = to_categorical(y_val_class_encoded) y_test_class_encoded = label_encoder.transform(y_test_class) y_test_class_categorical = to_categorical(y_test_class_encoded) return ( X_train, y_train_class_categorical, y_train_seg, X_val, y_val_class_categorical, y_val_seg, X_test, y_test_class_categorical, y_test_seg, ) def build_model(input_shape, num_classes): num_filter = 32 # 16/32 best, 8: best classification but no segment # Encoder (Done) inputs = Input(input_shape) conv1 = Conv2D(num_filter * 1, 3, activation="linear", padding="same", strides=1)(inputs) bn1 = BatchNormalization()(conv1) relu1 = Activation("relu")(bn1) conv2 = Conv2D(num_filter * 1, 3, activation="linear", padding="same", strides=1)(relu1) bn2 = BatchNormalization()(conv2) relu2 = Activation("relu")(bn2) down1 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu2) conv3 = Conv2D(num_filter * 2, 3, activation="linear", padding="same", strides=1)(down1) bn3 = BatchNormalization()(conv3) relu3 = Activation("relu")(bn3) conv4 = Conv2D(num_filter * 2, 3, activation="linear", padding="same", strides=1)(relu3) bn4 = BatchNormalization()(conv4) relu4 = Activation("relu")(bn4) down2 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu4) conv5 = Conv2D(num_filter * 4, 3, activation="linear", padding="same", strides=1)(down2) bn5 = BatchNormalization()(conv5) relu5 = Activation("relu")(bn5) conv6 = Conv2D(num_filter * 4, 3, activation="linear", padding="same", strides=1)(relu5) bn6 = BatchNormalization()(conv6) relu6 = Activation("relu")(bn6) down3 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu6) conv7 = Conv2D(num_filter * 8, 3, activation="linear", padding="same", strides=1)(down3) bn7 = BatchNormalization()(conv7) relu7 = Activation("relu")(bn7) conv8 = Conv2D(num_filter * 8, 3, activation="linear", padding="same", strides=1)(relu7) bn8 = BatchNormalization()(conv8) relu8 = Activation("relu")(bn8) # Middle down4 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu8) conv9 = Conv2D(num_filter * 16, 3, activation="linear", padding="same", strides=1)(down4) bn9 = BatchNormalization()(conv9) relu9 = Activation("relu")(bn9) conv10 = Conv2D(num_filter * 16, 3, activation="linear", padding="same", strides=1)(relu9) bn10 = BatchNormalization()(conv10) relu10 = Activation("relu")(bn10) up1 = UpSampling2D(size=(2, 2), interpolation="bilinear")(relu10) # Decoder (Done) concat1 = concatenate([up1, relu8], axis=-1) # , axis=3 conv11 = Conv2D(num_filter * 8, 3, activation="linear", padding="same", strides=1)(concat1) bn11 = BatchNormalization()(conv11) relu11 = Activation("relu")(bn11) conv12 = Conv2D(num_filter * 8, 3, activation="linear", padding="same", strides=1)(relu11) bn12 = BatchNormalization()(conv12) relu12 = Activation("relu")(bn12) up2 = UpSampling2D(size=(2, 2), interpolation="bilinear")(relu12) concat2 = concatenate([up2, relu6], axis=-1) # , axis=3 conv13 = Conv2D(num_filter * 4, 3, activation="linear", padding="same", strides=1)(concat2) bn13 = BatchNormalization()(conv13) relu13 = Activation("relu")(bn13) conv14 = Conv2D(num_filter * 4, 3, activation="linear", padding="same", strides=1)(relu13) bn14 = BatchNormalization()(conv14) relu14 = Activation("relu")(bn14) up3 = UpSampling2D(size=(2, 2), interpolation="bilinear")(relu14) concat3 = concatenate([up3, relu4], axis=-1) # , axis=3 conv15 = Conv2D(num_filter * 2, 3, activation="linear", padding="same", strides=1)(concat3) bn15 = BatchNormalization()(conv15) relu15 = Activation("relu")(bn15) conv16 = Conv2D(num_filter * 2, 3, activation="linear", padding="same", strides=1)(relu15) bn16 = BatchNormalization()(conv16) relu16 = Activation("relu")(bn16) up4 = UpSampling2D(size=(2, 2), interpolation="bilinear")(relu16) concat4 = concatenate([up4, relu2], axis=-1) # , axis=3 conv17 = Conv2D(num_filter * 1, 3, activation="linear", padding="same", strides=1)(concat4) bn17 = BatchNormalization()(conv17) relu17 = Activation("relu")(bn17) conv18 = Conv2D(num_filter * 1, 3, activation="linear", padding="same", strides=1)(relu17) bn18 = BatchNormalization()(conv18) relu18 = Activation("relu")(bn18) # Segmentation branch segmentation_output = Conv2D(1, 1, activation="sigmoid", name="segmentation_output")(relu18) # original # Classification branch (Not done) gap1 = GlobalAveragePooling2D()(relu8) gap2 = GlobalAveragePooling2D()(relu10) gap3 = GlobalAveragePooling2D()(relu12) conv20 = Conv2D(16, 3, activation="linear", padding="same", strides=1)(segmentation_output) bn20 = BatchNormalization()(conv20) relu20 = Activation("relu")(bn20) down5 = MaxPooling2D(pool_size=(4, 4), strides=4)(relu20) conv21 = Conv2D(32, 3, activation="linear", padding="same", strides=1)(down5) bn21 = BatchNormalization()(conv21) relu21 = Activation("relu")(bn21) down6 = MaxPooling2D(pool_size=(4, 4), strides=4)(relu21) conv22 = Conv2D(64, 3, activation="linear", padding="same", strides=1)(down6) bn22 = BatchNormalization()(conv22) relu22 = Activation("relu")(bn22) down7 = MaxPooling2D(pool_size=(4, 4), strides=4)(relu22) flatten1 = Flatten()(down7) concat5 = concatenate([gap1, gap2, gap3, flatten1], axis=-1) # FC layers fc1 = Dense(1024, activation="relu")(concat5) dropout1 = Dropout(0.5)(fc1) fc2 = Dense(1024, activation="relu")(dropout1) dropout2 = Dropout(0.5)(fc2) classification_output = Dense(num_classes, activation="softmax", name="classification_output")(dropout2) # Define the model model = Model(inputs=inputs, outputs=[classification_output, segmentation_output]) return model def segmentation_loss(y_true, y_pred): y_true = tf.cast(y_true, tf.float32) y_pred = tf.cast(y_pred, tf.float32) bce_loss = tf.keras.losses.binary_crossentropy(y_true, y_pred) smooth = 1e-5 intersection = tf.reduce_sum(y_true * y_pred) union = tf.reduce_sum(y_true) + tf.reduce_sum(y_pred) dice_loss = 1.0 - 2.0 * (intersection + smooth) / (union + smooth) segmentation_loss = bce_loss + 1 * dice_loss return segmentation_loss def train_model(model, X_train, y_train_class, y_train_seg, X_val, y_val_class, y_val_seg, batch_size, epochs): checkpoint = ModelCheckpoint( "multitask_best_weights.h5", monitor="val_classification_output_accuracy", save_best_only=True, mode="max", verbose=1,) reduce_lr = ReduceLROnPlateau( monitor="val_classification_output_accuracy", factor=0.3, patience=2, min_delta=0.001, mode="auto", verbose=1,) tensorboard = TensorBoard(log_dir="logs") model.compile( optimizer=Adam(lr=0.001), loss={"classification_output": "categorical_crossentropy", "segmentation_output": segmentation_loss}, metrics={"classification_output": "accuracy", "segmentation_output": "accuracy"}, loss_weights={"classification_output": 1, "segmentation_output": 1},) history = model.fit( X_train, {"classification_output": y_train_class, "segmentation_output": y_train_seg}, validation_data=(X_val, {"classification_output": y_val_class, "segmentation_output": y_val_seg}), epochs=epochs, verbose=1, batch_size=batch_size, callbacks=[checkpoint, reduce_lr, tensorboard],) return history def evaluate_model(model, X_test, y_test_class, y_test_seg): with tf.keras.utils.custom_object_scope({"segmentation_loss": segmentation_loss}): # Load the best model weights best_model = load_model("multitask_best_weights.h5") # Evaluate the model on test data test_loss, test_class_loss, test_seg_loss, test_class_acc, test_seg_acc = best_model.evaluate( X_test, {"classification_output": y_test_class, "segmentation_output": y_test_seg}) print("Test Classification Loss:", test_class_loss) print("Test Segmentation Loss:", test_seg_loss) print("Test Classification Accuracy:", test_class_acc) print("Test Segmentation Accuracy:", test_seg_acc) # Evaluate the model on validation data val_loss, val_class_loss, val_seg_loss, val_class_acc, val_seg_acc = best_model.evaluate( X_val, {'classification_output': y_val_class, 'segmentation_output': y_val_seg}) print("Validation Classification Loss:", val_class_loss) print("Validation Segmentation Loss:", val_seg_loss) print("Validation Classification Accuracy:", val_class_acc) print("Validation Segmentation Accuracy:", val_seg_acc) # Evaluate the model on training data train_loss, train_class_loss, train_seg_loss, train_class_acc, train_seg_acc = best_model.evaluate(X_train, {'classification_output': y_train_class, 'segmentation_output': y_train_seg}) print("Train Classification Loss:", train_class_loss) print("Train Segmentation Loss:", train_seg_loss) print("Train Classification Accuracy:", train_class_acc) print("Train Segmentation Accuracy:", train_seg_acc) # Return test classification accuracy return test_class_acc def plot_performance(history): # Plot classification accuracy classification_train_accuracy = history.history["classification_output_accuracy"] classification_val_accuracy = history.history["val_classification_output_accuracy"] plt.figure(figsize=(7, 3)) plt.plot(classification_train_accuracy, label="Training Accuracy") plt.plot(classification_val_accuracy, label="Validation Accuracy") plt.title("Classification Accuracy") plt.xlabel("Epochs") plt.ylabel("Accuracy") plt.legend() plt.show() # Plot classification loss classification_train_loss = history.history["classification_output_loss"] classification_val_loss = history.history["val_classification_output_loss"] plt.figure(figsize=(7, 3)) plt.plot(classification_train_loss, "b", label="Training Loss") plt.plot(classification_val_loss, "r", label="Validation Loss") plt.title("Classification Loss") plt.xlabel("Epochs") plt.ylabel("Loss") plt.legend() plt.show() # Plot segmentation accuracy segmentation_train_accuracy = history.history["segmentation_output_accuracy"] segmentation_val_accuracy = history.history["val_segmentation_output_accuracy"] plt.figure(figsize=(7, 3)) plt.plot(segmentation_train_accuracy, label="Training Accuracy") plt.plot(segmentation_val_accuracy, label="Validation Accuracy") plt.title("Segmentation Accuracy") plt.xlabel("Epochs") plt.ylabel("Accuracy") plt.legend() plt.show() # Plot segmentation loss segmentation_train_loss = history.history["segmentation_output_loss"] segmentation_val_loss = history.history["val_segmentation_output_loss"] plt.figure(figsize=(7, 3)) plt.plot(segmentation_train_loss, "b", label="Training Loss") plt.plot(segmentation_val_loss, "r", label="Validation Loss") plt.title("Segmentation Loss") plt.xlabel("Epochs") plt.ylabel("Loss") plt.legend() plt.show() # Set image size image_size = 224 # Define labels labels = ["bridge", "excess", "good"] # Set data folders data_folders = [ "/content/gdrive/MyDrive/Deep learning/FYP_2/4 Dataset Ratio 60 20 20/jit012/jit0/f_dip/train", "/content/gdrive/MyDrive/Deep learning/FYP_2/4 Dataset Ratio 60 20 20/jit012/jit0/f_dip/val", "/content/gdrive/MyDrive/Deep learning/FYP_2/4 Dataset Ratio 60 20 20/jit012/jit0/f_dip/test",] # Load data X_data, y_class_labels, y_seg_labels = load_data(data_folders) # Set image size image_size = 224 # Split data train_ratio = 0.1 val_ratio = 0.2 test_ratio = 0.6 X_train, y_train_class, y_train_seg, X_val, y_val_class, y_val_seg, X_test, y_test_class, y_test_seg = split_data( X_data, y_class_labels, y_seg_labels, train_ratio, val_ratio, test_ratio) # Build model input_shape = (image_size, image_size, 3) num_classes = len(labels) model = build_model(input_shape, num_classes) test_class_acc_list = [] for i in range(5): print(f"\nTrain {i+1}:\n") model = build_model(input_shape, num_classes) # Train model batch_size = 16 epochs = 50 history = train_model(model, X_train, y_train_class, y_train_seg, X_val, y_val_class, y_val_seg, batch_size, epochs) # Evaluate model on test data test_class_acc = evaluate_model(model, X_test, y_test_class, y_test_seg) plot_performance(history) test_class_acc_list.append(test_class_acc) # Calculate average test classification accuracy average_test_class_acc = sum(test_class_acc_list) / len(test_class_acc_list) print("Test Classification Accuracy List:", test_class_acc_list) print("Average Test Classification Accuracy:", average_test_class_acc) " The above is the Python code with Keras to do multi-task learning with binary segmentation and classification using one mult-task learning model. I have already loaded and separated the dataset (contain both images and ground truth segmentation masks) into train:val:test ratio of 10:20:60. Add the code to check the number of images of each class in the train,val,test set respectively, e.g.For train: bridge: 12, excess: 27, good:42,... Show full code.
21c927ab8a3566aa4006a42eeecf25f3
{ "intermediate": 0.43294963240623474, "beginner": 0.3695805072784424, "expert": 0.1974697858095169 }
42,679
Write c#
103ee8fd04178519a430c6b059ca7134
{ "intermediate": 0.35693463683128357, "beginner": 0.4770420491695404, "expert": 0.16602331399917603 }
42,680
Write c# scripts for unity game 3d, conceots of these game is simulator boxing game, focus on cpu vs cpu.. So player can watch as spectator. Begin by create the main menu, option and game fight. Please focus on scripts parts, for the modeling and all sound fx i will make. Make the boxer more realistic ai
d68662839fe41c5e330c57de1bf761e9
{ "intermediate": 0.4259982109069824, "beginner": 0.21957531571388245, "expert": 0.35442644357681274 }
42,681
You are a Python expert who can provide clear, concise, high-quality code. " import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns import cv2 import random import tensorflow as tf from tensorflow.keras.optimizers import Adam, SGD, RMSprop, AdamW, Adadelta, Adagrad, Adamax, Adafactor, Nadam, Ftrl from tensorflow.keras.preprocessing.image import ImageDataGenerator from tqdm import tqdm import os from sklearn.utils import shuffle from sklearn.preprocessing import LabelEncoder from sklearn.model_selection import train_test_split from tensorflow.keras.models import Sequential, Model, load_model from tensorflow.keras.layers import ( GlobalAveragePooling2D, Dropout, Dense, Conv2D, MaxPooling2D, Flatten, Dropout, BatchNormalization, Activation, concatenate, Conv2DTranspose, Input, Reshape, UpSampling2D, ) from tensorflow.keras.applications import ( EfficientNetV2B0, EfficientNetV2B1, EfficientNetV2B2, EfficientNetV2B3, EfficientNetV2L, EfficientNetV2M, EfficientNetV2S, ) from tensorflow.keras.applications import Xception from tensorflow.keras.applications import VGG16, VGG19 from tensorflow.keras.applications import ResNet50, ResNet101, ResNet152, ResNetRS50, ResNetRS101 from tensorflow.keras.applications import InceptionResNetV2, ConvNeXtXLarge, ConvNeXtBase, DenseNet121, MobileNetV2, NASNetLarge, NASNetMobile from tensorflow.keras.utils import to_categorical from tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau, TensorBoard, ModelCheckpoint from sklearn.metrics import classification_report, confusion_matrix import ipywidgets as widgets import io from PIL import Image from IPython.display import display, clear_output from warnings import filterwarnings from google.colab import drive drive.mount("/content/gdrive") def load_data(data_folders): X_data = [] # Combined data y_class_labels = [] # Combined classification labels y_seg_labels = [] # Combined segmentation labels for folderPath in data_folders: for label in labels: label_folder_path = os.path.join(folderPath, label) for filename in tqdm(os.listdir(label_folder_path)): if filename.endswith(".jpg"): img = cv2.imread(os.path.join(label_folder_path, filename)) img = cv2.resize(img, (image_size, image_size)) X_data.append(img) y_class_labels.append(label) seg_filename = filename.split(".")[0] + ".png" seg_img = cv2.imread(os.path.join(label_folder_path, seg_filename), 0) seg_img = cv2.resize(seg_img, (image_size, image_size)) seg_img = np.where(seg_img > 0, 1, 0) # Convert segmentation mask to binary y_seg_labels.append(seg_img) X_data = np.array(X_data) y_class_labels = np.array(y_class_labels) y_seg_labels = np.array(y_seg_labels) X_data, y_class_labels, y_seg_labels = shuffle(X_data, y_class_labels, y_seg_labels, random_state=101) return X_data, y_class_labels, y_seg_labels def split_data(X_data, y_class_labels, y_seg_labels, train_ratio, val_ratio, test_ratio): num_samples = len(X_data) num_train_samples = int(train_ratio * num_samples) num_val_samples = int(val_ratio * num_samples) num_test_samples = int(test_ratio * num_samples) X_train = X_data[:num_train_samples] y_train_class = y_class_labels[:num_train_samples] y_train_seg = y_seg_labels[:num_train_samples] X_val = X_data[num_train_samples: num_train_samples + num_val_samples] y_val_class = y_class_labels[num_train_samples: num_train_samples + num_val_samples] y_val_seg = y_seg_labels[num_train_samples: num_train_samples + num_val_samples] X_test = X_data[num_train_samples + num_val_samples: num_train_samples + num_val_samples + num_test_samples] y_test_class = y_class_labels[num_train_samples + num_val_samples: num_train_samples + num_val_samples + num_test_samples] y_test_seg = y_seg_labels[num_train_samples + num_val_samples: num_train_samples + num_val_samples + num_test_samples] # Convert class labels to categorical label_encoder = LabelEncoder() y_train_class_encoded = label_encoder.fit_transform(y_train_class) y_train_class_categorical = to_categorical(y_train_class_encoded) y_val_class_encoded = label_encoder.transform(y_val_class) y_val_class_categorical = to_categorical(y_val_class_encoded) y_test_class_encoded = label_encoder.transform(y_test_class) y_test_class_categorical = to_categorical(y_test_class_encoded) return ( X_train, y_train_class_categorical, y_train_seg, X_val, y_val_class_categorical, y_val_seg, X_test, y_test_class_categorical, y_test_seg, ) def build_model(input_shape, num_classes): num_filter = 32 # 16/32 best, 8: best classification but no segment # Encoder (Done) inputs = Input(input_shape) conv1 = Conv2D(num_filter * 1, 3, activation="linear", padding="same", strides=1)(inputs) bn1 = BatchNormalization()(conv1) relu1 = Activation("relu")(bn1) conv2 = Conv2D(num_filter * 1, 3, activation="linear", padding="same", strides=1)(relu1) bn2 = BatchNormalization()(conv2) relu2 = Activation("relu")(bn2) down1 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu2) conv3 = Conv2D(num_filter * 2, 3, activation="linear", padding="same", strides=1)(down1) bn3 = BatchNormalization()(conv3) relu3 = Activation("relu")(bn3) conv4 = Conv2D(num_filter * 2, 3, activation="linear", padding="same", strides=1)(relu3) bn4 = BatchNormalization()(conv4) relu4 = Activation("relu")(bn4) down2 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu4) conv5 = Conv2D(num_filter * 4, 3, activation="linear", padding="same", strides=1)(down2) bn5 = BatchNormalization()(conv5) relu5 = Activation("relu")(bn5) conv6 = Conv2D(num_filter * 4, 3, activation="linear", padding="same", strides=1)(relu5) bn6 = BatchNormalization()(conv6) relu6 = Activation("relu")(bn6) down3 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu6) conv7 = Conv2D(num_filter * 8, 3, activation="linear", padding="same", strides=1)(down3) bn7 = BatchNormalization()(conv7) relu7 = Activation("relu")(bn7) conv8 = Conv2D(num_filter * 8, 3, activation="linear", padding="same", strides=1)(relu7) bn8 = BatchNormalization()(conv8) relu8 = Activation("relu")(bn8) # Middle down4 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu8) conv9 = Conv2D(num_filter * 16, 3, activation="linear", padding="same", strides=1)(down4) bn9 = BatchNormalization()(conv9) relu9 = Activation("relu")(bn9) conv10 = Conv2D(num_filter * 16, 3, activation="linear", padding="same", strides=1)(relu9) bn10 = BatchNormalization()(conv10) relu10 = Activation("relu")(bn10) up1 = UpSampling2D(size=(2, 2), interpolation="bilinear")(relu10) # Decoder (Done) concat1 = concatenate([up1, relu8], axis=-1) # , axis=3 conv11 = Conv2D(num_filter * 8, 3, activation="linear", padding="same", strides=1)(concat1) bn11 = BatchNormalization()(conv11) relu11 = Activation("relu")(bn11) conv12 = Conv2D(num_filter * 8, 3, activation="linear", padding="same", strides=1)(relu11) bn12 = BatchNormalization()(conv12) relu12 = Activation("relu")(bn12) up2 = UpSampling2D(size=(2, 2), interpolation="bilinear")(relu12) concat2 = concatenate([up2, relu6], axis=-1) # , axis=3 conv13 = Conv2D(num_filter * 4, 3, activation="linear", padding="same", strides=1)(concat2) bn13 = BatchNormalization()(conv13) relu13 = Activation("relu")(bn13) conv14 = Conv2D(num_filter * 4, 3, activation="linear", padding="same", strides=1)(relu13) bn14 = BatchNormalization()(conv14) relu14 = Activation("relu")(bn14) up3 = UpSampling2D(size=(2, 2), interpolation="bilinear")(relu14) concat3 = concatenate([up3, relu4], axis=-1) # , axis=3 conv15 = Conv2D(num_filter * 2, 3, activation="linear", padding="same", strides=1)(concat3) bn15 = BatchNormalization()(conv15) relu15 = Activation("relu")(bn15) conv16 = Conv2D(num_filter * 2, 3, activation="linear", padding="same", strides=1)(relu15) bn16 = BatchNormalization()(conv16) relu16 = Activation("relu")(bn16) up4 = UpSampling2D(size=(2, 2), interpolation="bilinear")(relu16) concat4 = concatenate([up4, relu2], axis=-1) # , axis=3 conv17 = Conv2D(num_filter * 1, 3, activation="linear", padding="same", strides=1)(concat4) bn17 = BatchNormalization()(conv17) relu17 = Activation("relu")(bn17) conv18 = Conv2D(num_filter * 1, 3, activation="linear", padding="same", strides=1)(relu17) bn18 = BatchNormalization()(conv18) relu18 = Activation("relu")(bn18) # Segmentation branch segmentation_output = Conv2D(1, 1, activation="sigmoid", name="segmentation_output")(relu18) # original # Classification branch (Not done) gap1 = GlobalAveragePooling2D()(relu8) gap2 = GlobalAveragePooling2D()(relu10) gap3 = GlobalAveragePooling2D()(relu12) conv20 = Conv2D(16, 3, activation="linear", padding="same", strides=1)(segmentation_output) bn20 = BatchNormalization()(conv20) relu20 = Activation("relu")(bn20) down5 = MaxPooling2D(pool_size=(4, 4), strides=4)(relu20) conv21 = Conv2D(32, 3, activation="linear", padding="same", strides=1)(down5) bn21 = BatchNormalization()(conv21) relu21 = Activation("relu")(bn21) down6 = MaxPooling2D(pool_size=(4, 4), strides=4)(relu21) conv22 = Conv2D(64, 3, activation="linear", padding="same", strides=1)(down6) bn22 = BatchNormalization()(conv22) relu22 = Activation("relu")(bn22) down7 = MaxPooling2D(pool_size=(4, 4), strides=4)(relu22) flatten1 = Flatten()(down7) concat5 = concatenate([gap1, gap2, gap3, flatten1], axis=-1) # FC layers fc1 = Dense(1024, activation="relu")(concat5) dropout1 = Dropout(0.5)(fc1) fc2 = Dense(1024, activation="relu")(dropout1) dropout2 = Dropout(0.5)(fc2) classification_output = Dense(num_classes, activation="softmax", name="classification_output")(dropout2) # Define the model model = Model(inputs=inputs, outputs=[classification_output, segmentation_output]) return model def segmentation_loss(y_true, y_pred): y_true = tf.cast(y_true, tf.float32) y_pred = tf.cast(y_pred, tf.float32) bce_loss = tf.keras.losses.binary_crossentropy(y_true, y_pred) smooth = 1e-5 intersection = tf.reduce_sum(y_true * y_pred) union = tf.reduce_sum(y_true) + tf.reduce_sum(y_pred) dice_loss = 1.0 - 2.0 * (intersection + smooth) / (union + smooth) segmentation_loss = bce_loss + 1 * dice_loss return segmentation_loss def train_model(model, X_train, y_train_class, y_train_seg, X_val, y_val_class, y_val_seg, batch_size, epochs): checkpoint = ModelCheckpoint( "multitask_best_weights.h5", monitor="val_classification_output_accuracy", save_best_only=True, mode="max", verbose=1,) reduce_lr = ReduceLROnPlateau( monitor="val_classification_output_accuracy", factor=0.3, patience=2, min_delta=0.001, mode="auto", verbose=1,) tensorboard = TensorBoard(log_dir="logs") model.compile( optimizer=Adam(lr=0.001), loss={"classification_output": "categorical_crossentropy", "segmentation_output": segmentation_loss}, metrics={"classification_output": "accuracy", "segmentation_output": "accuracy"}, loss_weights={"classification_output": 1, "segmentation_output": 1},) history = model.fit( X_train, {"classification_output": y_train_class, "segmentation_output": y_train_seg}, validation_data=(X_val, {"classification_output": y_val_class, "segmentation_output": y_val_seg}), epochs=epochs, verbose=1, batch_size=batch_size, callbacks=[checkpoint, reduce_lr, tensorboard],) return history def evaluate_model(model, X_test, y_test_class, y_test_seg): with tf.keras.utils.custom_object_scope({"segmentation_loss": segmentation_loss}): # Load the best model weights best_model = load_model("multitask_best_weights.h5") # Evaluate the model on test data test_loss, test_class_loss, test_seg_loss, test_class_acc, test_seg_acc = best_model.evaluate( X_test, {"classification_output": y_test_class, "segmentation_output": y_test_seg}) print("Test Classification Loss:", test_class_loss) print("Test Segmentation Loss:", test_seg_loss) print("Test Classification Accuracy:", test_class_acc) print("Test Segmentation Accuracy:", test_seg_acc) # Evaluate the model on validation data val_loss, val_class_loss, val_seg_loss, val_class_acc, val_seg_acc = best_model.evaluate( X_val, {'classification_output': y_val_class, 'segmentation_output': y_val_seg}) print("Validation Classification Loss:", val_class_loss) print("Validation Segmentation Loss:", val_seg_loss) print("Validation Classification Accuracy:", val_class_acc) print("Validation Segmentation Accuracy:", val_seg_acc) # Evaluate the model on training data train_loss, train_class_loss, train_seg_loss, train_class_acc, train_seg_acc = best_model.evaluate(X_train, {'classification_output': y_train_class, 'segmentation_output': y_train_seg}) print("Train Classification Loss:", train_class_loss) print("Train Segmentation Loss:", train_seg_loss) print("Train Classification Accuracy:", train_class_acc) print("Train Segmentation Accuracy:", train_seg_acc) # Return test classification accuracy return test_class_acc def plot_performance(history): # Plot classification accuracy classification_train_accuracy = history.history["classification_output_accuracy"] classification_val_accuracy = history.history["val_classification_output_accuracy"] plt.figure(figsize=(7, 3)) plt.plot(classification_train_accuracy, label="Training Accuracy") plt.plot(classification_val_accuracy, label="Validation Accuracy") plt.title("Classification Accuracy") plt.xlabel("Epochs") plt.ylabel("Accuracy") plt.legend() plt.show() # Plot classification loss classification_train_loss = history.history["classification_output_loss"] classification_val_loss = history.history["val_classification_output_loss"] plt.figure(figsize=(7, 3)) plt.plot(classification_train_loss, "b", label="Training Loss") plt.plot(classification_val_loss, "r", label="Validation Loss") plt.title("Classification Loss") plt.xlabel("Epochs") plt.ylabel("Loss") plt.legend() plt.show() # Plot segmentation accuracy segmentation_train_accuracy = history.history["segmentation_output_accuracy"] segmentation_val_accuracy = history.history["val_segmentation_output_accuracy"] plt.figure(figsize=(7, 3)) plt.plot(segmentation_train_accuracy, label="Training Accuracy") plt.plot(segmentation_val_accuracy, label="Validation Accuracy") plt.title("Segmentation Accuracy") plt.xlabel("Epochs") plt.ylabel("Accuracy") plt.legend() plt.show() # Plot segmentation loss segmentation_train_loss = history.history["segmentation_output_loss"] segmentation_val_loss = history.history["val_segmentation_output_loss"] plt.figure(figsize=(7, 3)) plt.plot(segmentation_train_loss, "b", label="Training Loss") plt.plot(segmentation_val_loss, "r", label="Validation Loss") plt.title("Segmentation Loss") plt.xlabel("Epochs") plt.ylabel("Loss") plt.legend() plt.show() # Set image size image_size = 224 # Define labels labels = ["bridge", "excess", "good"] # Set data folders data_folders = [ "/content/gdrive/MyDrive/Deep learning/FYP_2/4 Dataset Ratio 60 20 20/jit012/jit0/f_dip/train", "/content/gdrive/MyDrive/Deep learning/FYP_2/4 Dataset Ratio 60 20 20/jit012/jit0/f_dip/val", "/content/gdrive/MyDrive/Deep learning/FYP_2/4 Dataset Ratio 60 20 20/jit012/jit0/f_dip/test",] # Load data X_data, y_class_labels, y_seg_labels = load_data(data_folders) # Set image size image_size = 224 # Split data train_ratio = 0.1 val_ratio = 0.2 test_ratio = 0.6 X_train, y_train_class, y_train_seg, X_val, y_val_class, y_val_seg, X_test, y_test_class, y_test_seg = split_data( X_data, y_class_labels, y_seg_labels, train_ratio, val_ratio, test_ratio) # Build model input_shape = (image_size, image_size, 3) num_classes = len(labels) model = build_model(input_shape, num_classes) test_class_acc_list = [] for i in range(5): print(f"\nTrain {i+1}:\n") model = build_model(input_shape, num_classes) # Train model batch_size = 16 epochs = 50 history = train_model(model, X_train, y_train_class, y_train_seg, X_val, y_val_class, y_val_seg, batch_size, epochs) # Evaluate model on test data test_class_acc = evaluate_model(model, X_test, y_test_class, y_test_seg) plot_performance(history) test_class_acc_list.append(test_class_acc) # Calculate average test classification accuracy average_test_class_acc = sum(test_class_acc_list) / len(test_class_acc_list) print("Test Classification Accuracy List:", test_class_acc_list) print("Average Test Classification Accuracy:", average_test_class_acc) " The above is the Python code with Keras to do multi-task learning with binary segmentation and classification using one mult-task learning model. I have already loaded and separated the dataset (contain both images and ground truth segmentation masks) into train:val:test ratio of 10:20:60. Add the code to check the number of images of each class in the train,val,test set respectively, e.g.For train: bridge: 12, excess: 27, good:42,... Show full code.
66ab54c1ec890d10f0ab1035e2704903
{ "intermediate": 0.43294963240623474, "beginner": 0.3695805072784424, "expert": 0.1974697858095169 }
42,682
Create me an interesting batch code
ce74f317dba5f5c2838f3f4442a02a8e
{ "intermediate": 0.35672667622566223, "beginner": 0.23984917998313904, "expert": 0.4034241735935211 }
42,683
You are a Python expert who can provide clear, concise, high-quality code. " import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns import cv2 import random from keras.models import load_model import tensorflow as tf from tensorflow.keras.optimizers import Adam, SGD, RMSprop, AdamW, Adadelta, Adagrad, Adamax, Adafactor, Nadam, Ftrl from tensorflow.keras.preprocessing.image import ImageDataGenerator from tqdm import tqdm import os from sklearn.utils import shuffle from sklearn.model_selection import train_test_split from tensorflow.keras.models import Sequential, Model from tensorflow.keras.layers import GlobalAveragePooling2D, Dropout, Dense, Conv2D, MaxPooling2D, Flatten, Dropout, BatchNormalization, Activation, concatenate, Conv2DTranspose, Input, Reshape, UpSampling2D from tensorflow.python.ops.gen_nn_ops import FusedBatchNormGradV2 from tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau, TensorBoard, ModelCheckpoint from sklearn.metrics import classification_report, confusion_matrix import ipywidgets as widgets import io from PIL import Image from IPython.display import display, clear_output from warnings import filterwarnings from google.colab import drive drive.mount('/content/gdrive') # Set image size image_size = 224 # Define labels labels = ['bridge', 'excess', 'good'] # Create data arrays X_train = [] # Train data y_train_class = [] # Train classification label y_train_seg = [] # Train segmentation label X_val = [] # Validation data y_val_class = [] # Validation classification label y_val_seg = [] # Validation segmentation label X_test = [] # Test data y_test_class = [] # Test classification label y_test_seg = [] # Test segmentation label # Load training data for label in labels: folderPath = os.path.join('/content/gdrive/MyDrive/FYP/5 Dataset Ratio 20 20 60 TP 10 to 90/jit012_p0.1-0.9/jit0_p0.5/f_dip/train', label) for filename in tqdm(os.listdir(folderPath)): if filename.endswith('.jpg'): img = cv2.imread(os.path.join(folderPath, filename)) img = cv2.resize(img, (image_size, image_size)) X_train.append(img) y_train_class.append(label) seg_filename = filename.split('.')[0] + '.png' seg_img = cv2.imread(os.path.join(folderPath, seg_filename), 0) seg_img = cv2.resize(seg_img, (image_size, image_size)) seg_img = np.where(seg_img > 0, 1, 0) # Convert segmentation mask to binary y_train_seg.append(seg_img) # Load validation data for label in labels: folderPath = os.path.join('/content/gdrive/MyDrive/FYP/5 Dataset Ratio 20 20 60 TP 10 to 90/jit012_p0.1-0.9/jit0_p0.5/f_dip/val', label) for filename in tqdm(os.listdir(folderPath)): if filename.endswith('.jpg'): img = cv2.imread(os.path.join(folderPath, filename)) img = cv2.resize(img, (image_size, image_size)) X_val.append(img) y_val_class.append(label) seg_filename = filename.split('.')[0] + '.png' seg_img = cv2.imread(os.path.join(folderPath, seg_filename), 0) seg_img = cv2.resize(seg_img, (image_size, image_size)) seg_img = np.where(seg_img > 0, 1, 0) # Convert segmentation mask to binary y_val_seg.append(seg_img) # Load test data for label in labels: folderPath = os.path.join('/content/gdrive/MyDrive/FYP/5 Dataset Ratio 20 20 60 TP 10 to 90/jit012_p0.1-0.9/jit0_p0.5/f_dip/test', label) for filename in tqdm(os.listdir(folderPath)): if filename.endswith('.jpg'): img = cv2.imread(os.path.join(folderPath, filename)) img = cv2.resize(img, (image_size, image_size)) X_test.append(img) y_test_class.append(label) seg_filename = filename.split('.')[0] + '.png' seg_img = cv2.imread(os.path.join(folderPath, seg_filename), 0) seg_img = cv2.resize(seg_img, (image_size, image_size)) seg_img = np.where(seg_img > 0, 1, 0) # Convert segmentation mask to binary y_test_seg.append(seg_img) # Convert to numpy arrays X_train = np.array(X_train) y_train_class = np.array(y_train_class) y_train_seg = np.array(y_train_seg) X_val = np.array(X_val) y_val_class = np.array(y_val_class) y_val_seg = np.array(y_val_seg) X_test = np.array(X_test) y_test_class = np.array(y_test_class) y_test_seg = np.array(y_test_seg) # Shuffle the data X_train, y_train_class, y_train_seg = shuffle(X_train, y_train_class, y_train_seg, random_state=101) # One Hot Encoding for classification labels y_train_class_new = [] for label in y_train_class: y_train_class_new.append(labels.index(label)) y_train_class = y_train_class_new y_train_class = tf.keras.utils.to_categorical(y_train_class) y_val_class_new = [] for label in y_val_class: y_val_class_new.append(labels.index(label)) y_val_class = y_val_class_new y_val_class = tf.keras.utils.to_categorical(y_val_class) y_test_class_new = [] for label in y_test_class: y_test_class_new.append(labels.index(label)) y_test_class = y_test_class_new y_test_class = tf.keras.utils.to_categorical(y_test_class) # Print the counts print("Number of train images:", len(X_train)) print("Number of train binary masks:", len(y_train_seg)) print("Number of validation images:", len(X_val)) print("Number of validation binary masks:", len(y_val_seg)) print("Number of test images:", len(X_test)) print("Number of test binary masks:", len(y_test_seg)) # Define U-Net model input_shape = (image_size, image_size, 3) num_classes = len(labels) inputs = Input(input_shape) num_filter = 32 # 16/32 best, 8: best classification but no segment # Encoder (Done) conv1 = Conv2D(num_filter * 1, 3, activation='linear', padding='same', strides=1)(inputs) bn1 = BatchNormalization()(conv1) relu1 = Activation('relu')(bn1) conv2 = Conv2D(num_filter * 1, 3, activation='linear', padding='same', strides=1)(relu1) bn2 = BatchNormalization()(conv2) relu2 = Activation('relu')(bn2) down1 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu2) conv3 = Conv2D(num_filter * 2, 3, activation='linear', padding='same', strides=1)(down1) bn3 = BatchNormalization()(conv3) relu3 = Activation('relu')(bn3) conv4 = Conv2D(num_filter * 2, 3, activation='linear', padding='same', strides=1)(relu3) bn4 = BatchNormalization()(conv4) relu4 = Activation('relu')(bn4) down2 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu4) conv5 = Conv2D(num_filter * 4, 3, activation='linear', padding='same', strides=1)(down2) bn5 = BatchNormalization()(conv5) relu5 = Activation('relu')(bn5) conv6 = Conv2D(num_filter * 4, 3, activation='linear', padding='same', strides=1)(relu5) bn6 = BatchNormalization()(conv6) relu6 = Activation('relu')(bn6) down3 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu6) conv7 = Conv2D(num_filter * 8, 3, activation='linear', padding='same', strides=1)(down3) bn7 = BatchNormalization()(conv7) relu7 = Activation('relu')(bn7) conv8 = Conv2D(num_filter * 8, 3, activation='linear', padding='same', strides=1)(relu7) bn8 = BatchNormalization()(conv8) relu8 = Activation('relu')(bn8) # Middle down4 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu8) conv9 = Conv2D(num_filter * 16, 3, activation='linear', padding='same', strides=1)(down4) bn9 = BatchNormalization()(conv9) relu9 = Activation('relu')(bn9) conv10 = Conv2D(num_filter * 16, 3, activation='linear', padding='same', strides=1)(relu9) bn10 = BatchNormalization()(conv10) relu10 = Activation('relu')(bn10) up1 = UpSampling2D(size=(2, 2), interpolation='bilinear')(relu10) # Decoder (Done) concat1 = concatenate([up1, relu8], axis=-1) #, axis=3 conv11 = Conv2D(num_filter * 8, 3, activation='linear', padding='same', strides=1)(concat1) bn11 = BatchNormalization()(conv11) relu11 = Activation('relu')(bn11) conv12 = Conv2D(num_filter * 8, 3, activation='linear', padding='same', strides=1)(relu11) bn12 = BatchNormalization()(conv12) relu12 = Activation('relu')(bn12) up2 = UpSampling2D(size=(2, 2), interpolation='bilinear')(relu12) concat2 = concatenate([up2, relu6], axis=-1) #, axis=3 conv13 = Conv2D(num_filter * 4, 3, activation='linear', padding='same', strides=1)(concat2) bn13 = BatchNormalization()(conv13) relu13 = Activation('relu')(bn13) conv14 = Conv2D(num_filter * 4, 3, activation='linear', padding='same', strides=1)(relu13) bn14 = BatchNormalization()(conv14) relu14 = Activation('relu')(bn14) up3 = UpSampling2D(size=(2, 2), interpolation='bilinear')(relu14) concat3 = concatenate([up3, relu4], axis=-1) #, axis=3 conv15 = Conv2D(num_filter * 2, 3, activation='linear', padding='same', strides=1)(concat3) bn15 = BatchNormalization()(conv15) relu15 = Activation('relu')(bn15) conv16 = Conv2D(num_filter * 2, 3, activation='linear', padding='same', strides=1)(relu15) bn16 = BatchNormalization()(conv16) relu16 = Activation('relu')(bn16) up4 = UpSampling2D(size=(2, 2), interpolation='bilinear')(relu16) concat4 = concatenate([up4, relu2], axis=-1) #, axis=3 conv17 = Conv2D(num_filter * 1, 3, activation='linear', padding='same', strides=1)(concat4) bn17 = BatchNormalization()(conv17) relu17 = Activation('relu')(bn17) conv18 = Conv2D(num_filter * 1, 3, activation='linear', padding='same', strides=1)(relu17) bn18 = BatchNormalization()(conv18) relu18 = Activation('relu')(bn18) # Segmentation branch segmentation_output = Conv2D(1, 1, activation='sigmoid', name='segmentation_output')(relu18) #original # Classification branch (Not done) gap1 = GlobalAveragePooling2D()(relu8) gap2 = GlobalAveragePooling2D()(relu10) gap3 = GlobalAveragePooling2D()(relu12) conv20 = Conv2D(16, 3, activation='linear', padding='same', strides=1)(segmentation_output) bn20 = BatchNormalization()(conv20) relu20 = Activation('relu')(bn20) down5 = MaxPooling2D(pool_size=(4, 4), strides=4)(relu20) conv21 = Conv2D(32, 3, activation='linear', padding='same', strides=1)(down5) bn21 = BatchNormalization()(conv21) relu21 = Activation('relu')(bn21) down6 = MaxPooling2D(pool_size=(4, 4), strides=4)(relu21) conv22 = Conv2D(64, 3, activation='linear', padding='same', strides=1)(down6) bn22 = BatchNormalization()(conv22) relu22 = Activation('relu')(bn22) down7 = MaxPooling2D(pool_size=(4, 4), strides=4)(relu22) flatten1 = Flatten()(down7) concat5 = concatenate([gap1, gap2, gap3, flatten1], axis = -1) # axis = -1 # FC layers fc1 = Dense(1024, activation='relu')(concat5) # 512, 256 match with num_filter = 8 dropout1 = Dropout(0.5)(fc1) fc2 = Dense(1024, activation='relu')(dropout1) # 512,256 dropout2 = Dropout(0.5)(fc2) classification_output = Dense(num_classes, activation='softmax', name='classification_output')(dropout2) # Define the model model = Model(inputs=inputs, outputs=[classification_output, segmentation_output]) model.summary() # Compile model def segmentation_loss(y_true, y_pred): y_true = tf.cast(y_true, tf.float32) y_pred = tf.cast(y_pred, tf.float32) # Binary cross-entropy loss bce_loss = tf.keras.losses.binary_crossentropy(y_true, y_pred) # Dice loss smooth = 1e-6 intersection = tf.reduce_sum(y_true * y_pred) union = tf.reduce_sum(y_true) + tf.reduce_sum(y_pred) dice_loss = 1.0 - 2.0 * (intersection + smooth) / (union + smooth) # Combine losses segmentation_loss = bce_loss + 1 * dice_loss return segmentation_loss model.compile(optimizer=Adam(lr=0.001), loss={'classification_output': 'categorical_crossentropy', 'segmentation_output': segmentation_loss}, # binary_crossentropy metrics={'classification_output': 'accuracy', 'segmentation_output': 'accuracy'}, loss_weights={'classification_output': 1, 'segmentation_output': 1}) # Define the callbacks checkpoint = ModelCheckpoint("multitask_best_weights.h5", monitor="val_classification_output_accuracy", save_best_only=True, mode="max", verbose=1) reduce_lr = ReduceLROnPlateau(monitor="val_classification_output_accuracy", factor=0.3, patience=2, min_delta=0.001, mode='auto', verbose=1) tensorboard = TensorBoard(log_dir='logs') history = model.fit(X_train, {'classification_output': y_train_class, 'segmentation_output': y_train_seg}, validation_data=(X_val, {'classification_output': y_val_class, 'segmentation_output': y_val_seg}), epochs=50, verbose=1, batch_size=16, callbacks=[checkpoint,reduce_lr,tensorboard]) # reduce_lr # Evaluate the model with tf.keras.utils.custom_object_scope({'segmentation_loss': segmentation_loss}): # Load the model best_model = load_model('multitask_best_weights.h5') # Evaluate the model on test data test_loss, test_class_loss, test_seg_loss, test_class_acc, test_seg_acc = best_model.evaluate(X_test, {'classification_output': y_test_class, 'segmentation_output': y_test_seg}) print("Test Classification Loss:", test_class_loss) print("Test Segmentation Loss:", test_seg_loss) print("Test Classification Accuracy:", test_class_acc) print("Test Segmentation Accuracy:", test_seg_acc) # Evaluate the model on validation data val_loss, val_class_loss, val_seg_loss, val_class_acc, val_seg_acc = best_model.evaluate(X_val, {'classification_output': y_val_class, 'segmentation_output': y_val_seg}) print("Validation Classification Loss:", val_class_loss) print("Validation Segmentation Loss:", val_seg_loss) print("Validation Classification Accuracy:", val_class_acc) print("Validation Segmentation Accuracy:", val_seg_acc) # Evaluate the model on training data train_loss, train_class_loss, train_seg_loss, train_class_acc, train_seg_acc = best_model.evaluate(X_train, {'classification_output': y_train_class, 'segmentation_output': y_train_seg}) print("Train Classification Loss:", train_class_loss) print("Train Segmentation Loss:", train_seg_loss) print("Train Classification Accuracy:", train_class_acc) print("Train Segmentation Accuracy:", train_seg_acc) # Plot performance classification_train_accuracy = history.history['classification_output_accuracy'] classification_train_loss = history.history['classification_output_loss'] classification_val_accuracy = history.history['val_classification_output_accuracy'] classification_val_loss = history.history['val_classification_output_loss'] segmentation_train_accuracy = history.history['segmentation_output_accuracy'] segmentation_train_loss = history.history['segmentation_output_loss'] segmentation_val_accuracy = history.history['val_segmentation_output_accuracy'] segmentation_val_loss = history.history['val_segmentation_output_loss'] # Plot classification accuracy plt.figure(figsize=(7, 3)) plt.plot(classification_train_accuracy, label='Training Accuracy') plt.plot(classification_val_accuracy, label='Validation Accuracy') plt.title('Classification Accuracy') plt.xlabel('Epochs') plt.ylabel('Accuracy') plt.legend() plt.show() # Plot segmentation accuracy plt.figure(figsize=(7, 3)) plt.plot(segmentation_train_accuracy, label='Training Accuracy') plt.plot(segmentation_val_accuracy, label='Validation Accuracy') plt.title('Segmentation Accuracy') plt.xlabel('Epochs') plt.ylabel('Accuracy') plt.legend() plt.show() # Plot classification loss plt.figure(figsize=(7, 3)) plt.plot(classification_train_loss,'b', label='Training Loss') plt.plot(classification_val_loss,'r', label='Validation Loss') plt.title('Classification Loss') plt.xlabel('Epochs') plt.ylabel('Loss') plt.legend() plt.show() # Plot segmentation loss plt.figure(figsize=(7, 3)) plt.plot(segmentation_train_loss,'b', label='Training Loss') plt.plot(segmentation_val_loss,'r', label='Validation Loss') plt.title('Segmentation Loss') plt.xlabel('Epochs') plt.ylabel('Loss') plt.legend() plt.show() " The above is the Python code with Keras to do multi-task learning with binary segmentation and classification using one mult-task learning model. Modify the code so that it can run 5 independent runs to train the model and take the average test accuracies of the 5 runs.
02b4523b261685b2d62c57176d7872d6
{ "intermediate": 0.29371780157089233, "beginner": 0.34619608521461487, "expert": 0.3600860834121704 }
42,684
You are a Python expert who can provide clear, concise, high-quality code. " import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns import cv2 import random from keras.models import load_model import tensorflow as tf from tensorflow.keras.optimizers import Adam, SGD, RMSprop, AdamW, Adadelta, Adagrad, Adamax, Adafactor, Nadam, Ftrl from tensorflow.keras.preprocessing.image import ImageDataGenerator from tqdm import tqdm import os from sklearn.utils import shuffle from sklearn.model_selection import train_test_split from tensorflow.keras.models import Sequential, Model from tensorflow.keras.layers import GlobalAveragePooling2D, Dropout, Dense, Conv2D, MaxPooling2D, Flatten, Dropout, BatchNormalization, Activation, concatenate, Conv2DTranspose, Input, Reshape, UpSampling2D from tensorflow.python.ops.gen_nn_ops import FusedBatchNormGradV2 from tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau, TensorBoard, ModelCheckpoint from sklearn.metrics import classification_report, confusion_matrix import ipywidgets as widgets import io from PIL import Image from IPython.display import display, clear_output from warnings import filterwarnings from google.colab import drive drive.mount('/content/gdrive') # Set image size image_size = 224 # Define labels labels = ['bridge', 'excess', 'good'] # Create data arrays X_train = [] # Train data y_train_class = [] # Train classification label y_train_seg = [] # Train segmentation label X_val = [] # Validation data y_val_class = [] # Validation classification label y_val_seg = [] # Validation segmentation label X_test = [] # Test data y_test_class = [] # Test classification label y_test_seg = [] # Test segmentation label # Load training data for label in labels: folderPath = os.path.join('/content/gdrive/MyDrive/FYP/5 Dataset Ratio 20 20 60 TP 10 to 90/jit012_p0.1-0.9/jit0_p0.5/f_dip/train', label) for filename in tqdm(os.listdir(folderPath)): if filename.endswith('.jpg'): img = cv2.imread(os.path.join(folderPath, filename)) img = cv2.resize(img, (image_size, image_size)) X_train.append(img) y_train_class.append(label) seg_filename = filename.split('.')[0] + '.png' seg_img = cv2.imread(os.path.join(folderPath, seg_filename), 0) seg_img = cv2.resize(seg_img, (image_size, image_size)) seg_img = np.where(seg_img > 0, 1, 0) # Convert segmentation mask to binary y_train_seg.append(seg_img) # Load validation data for label in labels: folderPath = os.path.join('/content/gdrive/MyDrive/FYP/5 Dataset Ratio 20 20 60 TP 10 to 90/jit012_p0.1-0.9/jit0_p0.5/f_dip/val', label) for filename in tqdm(os.listdir(folderPath)): if filename.endswith('.jpg'): img = cv2.imread(os.path.join(folderPath, filename)) img = cv2.resize(img, (image_size, image_size)) X_val.append(img) y_val_class.append(label) seg_filename = filename.split('.')[0] + '.png' seg_img = cv2.imread(os.path.join(folderPath, seg_filename), 0) seg_img = cv2.resize(seg_img, (image_size, image_size)) seg_img = np.where(seg_img > 0, 1, 0) # Convert segmentation mask to binary y_val_seg.append(seg_img) # Load test data for label in labels: folderPath = os.path.join('/content/gdrive/MyDrive/FYP/5 Dataset Ratio 20 20 60 TP 10 to 90/jit012_p0.1-0.9/jit0_p0.5/f_dip/test', label) for filename in tqdm(os.listdir(folderPath)): if filename.endswith('.jpg'): img = cv2.imread(os.path.join(folderPath, filename)) img = cv2.resize(img, (image_size, image_size)) X_test.append(img) y_test_class.append(label) seg_filename = filename.split('.')[0] + '.png' seg_img = cv2.imread(os.path.join(folderPath, seg_filename), 0) seg_img = cv2.resize(seg_img, (image_size, image_size)) seg_img = np.where(seg_img > 0, 1, 0) # Convert segmentation mask to binary y_test_seg.append(seg_img) # Convert to numpy arrays X_train = np.array(X_train) y_train_class = np.array(y_train_class) y_train_seg = np.array(y_train_seg) X_val = np.array(X_val) y_val_class = np.array(y_val_class) y_val_seg = np.array(y_val_seg) X_test = np.array(X_test) y_test_class = np.array(y_test_class) y_test_seg = np.array(y_test_seg) # Shuffle the data X_train, y_train_class, y_train_seg = shuffle(X_train, y_train_class, y_train_seg, random_state=101) # One Hot Encoding for classification labels y_train_class_new = [] for label in y_train_class: y_train_class_new.append(labels.index(label)) y_train_class = y_train_class_new y_train_class = tf.keras.utils.to_categorical(y_train_class) y_val_class_new = [] for label in y_val_class: y_val_class_new.append(labels.index(label)) y_val_class = y_val_class_new y_val_class = tf.keras.utils.to_categorical(y_val_class) y_test_class_new = [] for label in y_test_class: y_test_class_new.append(labels.index(label)) y_test_class = y_test_class_new y_test_class = tf.keras.utils.to_categorical(y_test_class) # Print the counts print("Number of train images:", len(X_train)) print("Number of train binary masks:", len(y_train_seg)) print("Number of validation images:", len(X_val)) print("Number of validation binary masks:", len(y_val_seg)) print("Number of test images:", len(X_test)) print("Number of test binary masks:", len(y_test_seg)) # Define U-Net model input_shape = (image_size, image_size, 3) num_classes = len(labels) inputs = Input(input_shape) num_filter = 32 # 16/32 best, 8: best classification but no segment # Encoder (Done) conv1 = Conv2D(num_filter * 1, 3, activation='linear', padding='same', strides=1)(inputs) bn1 = BatchNormalization()(conv1) relu1 = Activation('relu')(bn1) conv2 = Conv2D(num_filter * 1, 3, activation='linear', padding='same', strides=1)(relu1) bn2 = BatchNormalization()(conv2) relu2 = Activation('relu')(bn2) down1 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu2) conv3 = Conv2D(num_filter * 2, 3, activation='linear', padding='same', strides=1)(down1) bn3 = BatchNormalization()(conv3) relu3 = Activation('relu')(bn3) conv4 = Conv2D(num_filter * 2, 3, activation='linear', padding='same', strides=1)(relu3) bn4 = BatchNormalization()(conv4) relu4 = Activation('relu')(bn4) down2 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu4) conv5 = Conv2D(num_filter * 4, 3, activation='linear', padding='same', strides=1)(down2) bn5 = BatchNormalization()(conv5) relu5 = Activation('relu')(bn5) conv6 = Conv2D(num_filter * 4, 3, activation='linear', padding='same', strides=1)(relu5) bn6 = BatchNormalization()(conv6) relu6 = Activation('relu')(bn6) down3 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu6) conv7 = Conv2D(num_filter * 8, 3, activation='linear', padding='same', strides=1)(down3) bn7 = BatchNormalization()(conv7) relu7 = Activation('relu')(bn7) conv8 = Conv2D(num_filter * 8, 3, activation='linear', padding='same', strides=1)(relu7) bn8 = BatchNormalization()(conv8) relu8 = Activation('relu')(bn8) # Middle down4 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu8) conv9 = Conv2D(num_filter * 16, 3, activation='linear', padding='same', strides=1)(down4) bn9 = BatchNormalization()(conv9) relu9 = Activation('relu')(bn9) conv10 = Conv2D(num_filter * 16, 3, activation='linear', padding='same', strides=1)(relu9) bn10 = BatchNormalization()(conv10) relu10 = Activation('relu')(bn10) up1 = UpSampling2D(size=(2, 2), interpolation='bilinear')(relu10) # Decoder (Done) concat1 = concatenate([up1, relu8], axis=-1) #, axis=3 conv11 = Conv2D(num_filter * 8, 3, activation='linear', padding='same', strides=1)(concat1) bn11 = BatchNormalization()(conv11) relu11 = Activation('relu')(bn11) conv12 = Conv2D(num_filter * 8, 3, activation='linear', padding='same', strides=1)(relu11) bn12 = BatchNormalization()(conv12) relu12 = Activation('relu')(bn12) up2 = UpSampling2D(size=(2, 2), interpolation='bilinear')(relu12) concat2 = concatenate([up2, relu6], axis=-1) #, axis=3 conv13 = Conv2D(num_filter * 4, 3, activation='linear', padding='same', strides=1)(concat2) bn13 = BatchNormalization()(conv13) relu13 = Activation('relu')(bn13) conv14 = Conv2D(num_filter * 4, 3, activation='linear', padding='same', strides=1)(relu13) bn14 = BatchNormalization()(conv14) relu14 = Activation('relu')(bn14) up3 = UpSampling2D(size=(2, 2), interpolation='bilinear')(relu14) concat3 = concatenate([up3, relu4], axis=-1) #, axis=3 conv15 = Conv2D(num_filter * 2, 3, activation='linear', padding='same', strides=1)(concat3) bn15 = BatchNormalization()(conv15) relu15 = Activation('relu')(bn15) conv16 = Conv2D(num_filter * 2, 3, activation='linear', padding='same', strides=1)(relu15) bn16 = BatchNormalization()(conv16) relu16 = Activation('relu')(bn16) up4 = UpSampling2D(size=(2, 2), interpolation='bilinear')(relu16) concat4 = concatenate([up4, relu2], axis=-1) #, axis=3 conv17 = Conv2D(num_filter * 1, 3, activation='linear', padding='same', strides=1)(concat4) bn17 = BatchNormalization()(conv17) relu17 = Activation('relu')(bn17) conv18 = Conv2D(num_filter * 1, 3, activation='linear', padding='same', strides=1)(relu17) bn18 = BatchNormalization()(conv18) relu18 = Activation('relu')(bn18) # Segmentation branch segmentation_output = Conv2D(1, 1, activation='sigmoid', name='segmentation_output')(relu18) #original # Classification branch (Not done) gap1 = GlobalAveragePooling2D()(relu8) gap2 = GlobalAveragePooling2D()(relu10) gap3 = GlobalAveragePooling2D()(relu12) conv20 = Conv2D(16, 3, activation='linear', padding='same', strides=1)(segmentation_output) bn20 = BatchNormalization()(conv20) relu20 = Activation('relu')(bn20) down5 = MaxPooling2D(pool_size=(4, 4), strides=4)(relu20) conv21 = Conv2D(32, 3, activation='linear', padding='same', strides=1)(down5) bn21 = BatchNormalization()(conv21) relu21 = Activation('relu')(bn21) down6 = MaxPooling2D(pool_size=(4, 4), strides=4)(relu21) conv22 = Conv2D(64, 3, activation='linear', padding='same', strides=1)(down6) bn22 = BatchNormalization()(conv22) relu22 = Activation('relu')(bn22) down7 = MaxPooling2D(pool_size=(4, 4), strides=4)(relu22) flatten1 = Flatten()(down7) concat5 = concatenate([gap1, gap2, gap3, flatten1], axis = -1) # axis = -1 # FC layers fc1 = Dense(1024, activation='relu')(concat5) # 512, 256 match with num_filter = 8 dropout1 = Dropout(0.5)(fc1) fc2 = Dense(1024, activation='relu')(dropout1) # 512,256 dropout2 = Dropout(0.5)(fc2) classification_output = Dense(num_classes, activation='softmax', name='classification_output')(dropout2) # Define the model model = Model(inputs=inputs, outputs=[classification_output, segmentation_output]) model.summary() # Compile model def segmentation_loss(y_true, y_pred): y_true = tf.cast(y_true, tf.float32) y_pred = tf.cast(y_pred, tf.float32) # Binary cross-entropy loss bce_loss = tf.keras.losses.binary_crossentropy(y_true, y_pred) # Dice loss smooth = 1e-6 intersection = tf.reduce_sum(y_true * y_pred) union = tf.reduce_sum(y_true) + tf.reduce_sum(y_pred) dice_loss = 1.0 - 2.0 * (intersection + smooth) / (union + smooth) # Combine losses segmentation_loss = bce_loss + 1 * dice_loss return segmentation_loss model.compile(optimizer=Adam(lr=0.001), loss={'classification_output': 'categorical_crossentropy', 'segmentation_output': segmentation_loss}, # binary_crossentropy metrics={'classification_output': 'accuracy', 'segmentation_output': 'accuracy'}, loss_weights={'classification_output': 1, 'segmentation_output': 1}) # Define the callbacks checkpoint = ModelCheckpoint("multitask_best_weights.h5", monitor="val_classification_output_accuracy", save_best_only=True, mode="max", verbose=1) reduce_lr = ReduceLROnPlateau(monitor="val_classification_output_accuracy", factor=0.3, patience=2, min_delta=0.001, mode='auto', verbose=1) tensorboard = TensorBoard(log_dir='logs') history = model.fit(X_train, {'classification_output': y_train_class, 'segmentation_output': y_train_seg}, validation_data=(X_val, {'classification_output': y_val_class, 'segmentation_output': y_val_seg}), epochs=50, verbose=1, batch_size=16, callbacks=[checkpoint,reduce_lr,tensorboard]) # reduce_lr # Evaluate the model with tf.keras.utils.custom_object_scope({'segmentation_loss': segmentation_loss}): # Load the model best_model = load_model('multitask_best_weights.h5') # Evaluate the model on test data test_loss, test_class_loss, test_seg_loss, test_class_acc, test_seg_acc = best_model.evaluate(X_test, {'classification_output': y_test_class, 'segmentation_output': y_test_seg}) print("Test Classification Loss:", test_class_loss) print("Test Segmentation Loss:", test_seg_loss) print("Test Classification Accuracy:", test_class_acc) print("Test Segmentation Accuracy:", test_seg_acc) # Evaluate the model on validation data val_loss, val_class_loss, val_seg_loss, val_class_acc, val_seg_acc = best_model.evaluate(X_val, {'classification_output': y_val_class, 'segmentation_output': y_val_seg}) print("Validation Classification Loss:", val_class_loss) print("Validation Segmentation Loss:", val_seg_loss) print("Validation Classification Accuracy:", val_class_acc) print("Validation Segmentation Accuracy:", val_seg_acc) # Evaluate the model on training data train_loss, train_class_loss, train_seg_loss, train_class_acc, train_seg_acc = best_model.evaluate(X_train, {'classification_output': y_train_class, 'segmentation_output': y_train_seg}) print("Train Classification Loss:", train_class_loss) print("Train Segmentation Loss:", train_seg_loss) print("Train Classification Accuracy:", train_class_acc) print("Train Segmentation Accuracy:", train_seg_acc) # Plot performance classification_train_accuracy = history.history['classification_output_accuracy'] classification_train_loss = history.history['classification_output_loss'] classification_val_accuracy = history.history['val_classification_output_accuracy'] classification_val_loss = history.history['val_classification_output_loss'] segmentation_train_accuracy = history.history['segmentation_output_accuracy'] segmentation_train_loss = history.history['segmentation_output_loss'] segmentation_val_accuracy = history.history['val_segmentation_output_accuracy'] segmentation_val_loss = history.history['val_segmentation_output_loss'] # Plot classification accuracy plt.figure(figsize=(7, 3)) plt.plot(classification_train_accuracy, label='Training Accuracy') plt.plot(classification_val_accuracy, label='Validation Accuracy') plt.title('Classification Accuracy') plt.xlabel('Epochs') plt.ylabel('Accuracy') plt.legend() plt.show() # Plot segmentation accuracy plt.figure(figsize=(7, 3)) plt.plot(segmentation_train_accuracy, label='Training Accuracy') plt.plot(segmentation_val_accuracy, label='Validation Accuracy') plt.title('Segmentation Accuracy') plt.xlabel('Epochs') plt.ylabel('Accuracy') plt.legend() plt.show() # Plot classification loss plt.figure(figsize=(7, 3)) plt.plot(classification_train_loss,'b', label='Training Loss') plt.plot(classification_val_loss,'r', label='Validation Loss') plt.title('Classification Loss') plt.xlabel('Epochs') plt.ylabel('Loss') plt.legend() plt.show() # Plot segmentation loss plt.figure(figsize=(7, 3)) plt.plot(segmentation_train_loss,'b', label='Training Loss') plt.plot(segmentation_val_loss,'r', label='Validation Loss') plt.title('Segmentation Loss') plt.xlabel('Epochs') plt.ylabel('Loss') plt.legend() plt.show() " The above is the Python code with Keras to do multi-task learning with binary segmentation and classification using one mult-task learning model. Modify the code so that it can run 5 independent runs to train the model and take the average test accuracies of the 5 runs.
eaecaffeb572bff74f4a0d988e26df6f
{ "intermediate": 0.29371780157089233, "beginner": 0.34619608521461487, "expert": 0.3600860834121704 }
42,685
You are a Python expert who can provide clear, concise, high-quality code. " import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns import cv2 import random from keras.models import load_model import tensorflow as tf from tensorflow.keras.optimizers import Adam, SGD, RMSprop, AdamW, Adadelta, Adagrad, Adamax, Adafactor, Nadam, Ftrl from tensorflow.keras.preprocessing.image import ImageDataGenerator from tqdm import tqdm import os from sklearn.utils import shuffle from sklearn.model_selection import train_test_split from tensorflow.keras.models import Sequential, Model from tensorflow.keras.layers import GlobalAveragePooling2D, Dropout, Dense, Conv2D, MaxPooling2D, Flatten, Dropout, BatchNormalization, Activation, concatenate, Conv2DTranspose, Input, Reshape, UpSampling2D from tensorflow.python.ops.gen_nn_ops import FusedBatchNormGradV2 from tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau, TensorBoard, ModelCheckpoint from sklearn.metrics import classification_report, confusion_matrix import ipywidgets as widgets import io from PIL import Image from IPython.display import display, clear_output from warnings import filterwarnings from google.colab import drive drive.mount('/content/gdrive') # Set image size image_size = 224 # Define labels labels = ['bridge', 'excess', 'good'] # Create data arrays X_train = [] # Train data y_train_class = [] # Train classification label y_train_seg = [] # Train segmentation label X_val = [] # Validation data y_val_class = [] # Validation classification label y_val_seg = [] # Validation segmentation label X_test = [] # Test data y_test_class = [] # Test classification label y_test_seg = [] # Test segmentation label # Load training data for label in labels: folderPath = os.path.join('/content/gdrive/MyDrive/FYP/5 Dataset Ratio 20 20 60 TP 10 to 90/jit012_p0.1-0.9/jit0_p0.5/f_dip/train', label) for filename in tqdm(os.listdir(folderPath)): if filename.endswith('.jpg'): img = cv2.imread(os.path.join(folderPath, filename)) img = cv2.resize(img, (image_size, image_size)) X_train.append(img) y_train_class.append(label) seg_filename = filename.split('.')[0] + '.png' seg_img = cv2.imread(os.path.join(folderPath, seg_filename), 0) seg_img = cv2.resize(seg_img, (image_size, image_size)) seg_img = np.where(seg_img > 0, 1, 0) # Convert segmentation mask to binary y_train_seg.append(seg_img) # Load validation data for label in labels: folderPath = os.path.join('/content/gdrive/MyDrive/FYP/5 Dataset Ratio 20 20 60 TP 10 to 90/jit012_p0.1-0.9/jit0_p0.5/f_dip/val', label) for filename in tqdm(os.listdir(folderPath)): if filename.endswith('.jpg'): img = cv2.imread(os.path.join(folderPath, filename)) img = cv2.resize(img, (image_size, image_size)) X_val.append(img) y_val_class.append(label) seg_filename = filename.split('.')[0] + '.png' seg_img = cv2.imread(os.path.join(folderPath, seg_filename), 0) seg_img = cv2.resize(seg_img, (image_size, image_size)) seg_img = np.where(seg_img > 0, 1, 0) # Convert segmentation mask to binary y_val_seg.append(seg_img) # Load test data for label in labels: folderPath = os.path.join('/content/gdrive/MyDrive/FYP/5 Dataset Ratio 20 20 60 TP 10 to 90/jit012_p0.1-0.9/jit0_p0.5/f_dip/test', label) for filename in tqdm(os.listdir(folderPath)): if filename.endswith('.jpg'): img = cv2.imread(os.path.join(folderPath, filename)) img = cv2.resize(img, (image_size, image_size)) X_test.append(img) y_test_class.append(label) seg_filename = filename.split('.')[0] + '.png' seg_img = cv2.imread(os.path.join(folderPath, seg_filename), 0) seg_img = cv2.resize(seg_img, (image_size, image_size)) seg_img = np.where(seg_img > 0, 1, 0) # Convert segmentation mask to binary y_test_seg.append(seg_img) # Convert to numpy arrays X_train = np.array(X_train) y_train_class = np.array(y_train_class) y_train_seg = np.array(y_train_seg) X_val = np.array(X_val) y_val_class = np.array(y_val_class) y_val_seg = np.array(y_val_seg) X_test = np.array(X_test) y_test_class = np.array(y_test_class) y_test_seg = np.array(y_test_seg) # Shuffle the data X_train, y_train_class, y_train_seg = shuffle(X_train, y_train_class, y_train_seg, random_state=101) # One Hot Encoding for classification labels y_train_class_new = [] for label in y_train_class: y_train_class_new.append(labels.index(label)) y_train_class = y_train_class_new y_train_class = tf.keras.utils.to_categorical(y_train_class) y_val_class_new = [] for label in y_val_class: y_val_class_new.append(labels.index(label)) y_val_class = y_val_class_new y_val_class = tf.keras.utils.to_categorical(y_val_class) y_test_class_new = [] for label in y_test_class: y_test_class_new.append(labels.index(label)) y_test_class = y_test_class_new y_test_class = tf.keras.utils.to_categorical(y_test_class) # Print the counts print("Number of train images:", len(X_train)) print("Number of train binary masks:", len(y_train_seg)) print("Number of validation images:", len(X_val)) print("Number of validation binary masks:", len(y_val_seg)) print("Number of test images:", len(X_test)) print("Number of test binary masks:", len(y_test_seg)) # Define U-Net model input_shape = (image_size, image_size, 3) num_classes = len(labels) inputs = Input(input_shape) num_filter = 32 # 16/32 best, 8: best classification but no segment # Encoder (Done) conv1 = Conv2D(num_filter * 1, 3, activation='linear', padding='same', strides=1)(inputs) bn1 = BatchNormalization()(conv1) relu1 = Activation('relu')(bn1) conv2 = Conv2D(num_filter * 1, 3, activation='linear', padding='same', strides=1)(relu1) bn2 = BatchNormalization()(conv2) relu2 = Activation('relu')(bn2) down1 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu2) conv3 = Conv2D(num_filter * 2, 3, activation='linear', padding='same', strides=1)(down1) bn3 = BatchNormalization()(conv3) relu3 = Activation('relu')(bn3) conv4 = Conv2D(num_filter * 2, 3, activation='linear', padding='same', strides=1)(relu3) bn4 = BatchNormalization()(conv4) relu4 = Activation('relu')(bn4) down2 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu4) conv5 = Conv2D(num_filter * 4, 3, activation='linear', padding='same', strides=1)(down2) bn5 = BatchNormalization()(conv5) relu5 = Activation('relu')(bn5) conv6 = Conv2D(num_filter * 4, 3, activation='linear', padding='same', strides=1)(relu5) bn6 = BatchNormalization()(conv6) relu6 = Activation('relu')(bn6) down3 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu6) conv7 = Conv2D(num_filter * 8, 3, activation='linear', padding='same', strides=1)(down3) bn7 = BatchNormalization()(conv7) relu7 = Activation('relu')(bn7) conv8 = Conv2D(num_filter * 8, 3, activation='linear', padding='same', strides=1)(relu7) bn8 = BatchNormalization()(conv8) relu8 = Activation('relu')(bn8) # Middle down4 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu8) conv9 = Conv2D(num_filter * 16, 3, activation='linear', padding='same', strides=1)(down4) bn9 = BatchNormalization()(conv9) relu9 = Activation('relu')(bn9) conv10 = Conv2D(num_filter * 16, 3, activation='linear', padding='same', strides=1)(relu9) bn10 = BatchNormalization()(conv10) relu10 = Activation('relu')(bn10) up1 = UpSampling2D(size=(2, 2), interpolation='bilinear')(relu10) # Decoder (Done) concat1 = concatenate([up1, relu8], axis=-1) #, axis=3 conv11 = Conv2D(num_filter * 8, 3, activation='linear', padding='same', strides=1)(concat1) bn11 = BatchNormalization()(conv11) relu11 = Activation('relu')(bn11) conv12 = Conv2D(num_filter * 8, 3, activation='linear', padding='same', strides=1)(relu11) bn12 = BatchNormalization()(conv12) relu12 = Activation('relu')(bn12) up2 = UpSampling2D(size=(2, 2), interpolation='bilinear')(relu12) concat2 = concatenate([up2, relu6], axis=-1) #, axis=3 conv13 = Conv2D(num_filter * 4, 3, activation='linear', padding='same', strides=1)(concat2) bn13 = BatchNormalization()(conv13) relu13 = Activation('relu')(bn13) conv14 = Conv2D(num_filter * 4, 3, activation='linear', padding='same', strides=1)(relu13) bn14 = BatchNormalization()(conv14) relu14 = Activation('relu')(bn14) up3 = UpSampling2D(size=(2, 2), interpolation='bilinear')(relu14) concat3 = concatenate([up3, relu4], axis=-1) #, axis=3 conv15 = Conv2D(num_filter * 2, 3, activation='linear', padding='same', strides=1)(concat3) bn15 = BatchNormalization()(conv15) relu15 = Activation('relu')(bn15) conv16 = Conv2D(num_filter * 2, 3, activation='linear', padding='same', strides=1)(relu15) bn16 = BatchNormalization()(conv16) relu16 = Activation('relu')(bn16) up4 = UpSampling2D(size=(2, 2), interpolation='bilinear')(relu16) concat4 = concatenate([up4, relu2], axis=-1) #, axis=3 conv17 = Conv2D(num_filter * 1, 3, activation='linear', padding='same', strides=1)(concat4) bn17 = BatchNormalization()(conv17) relu17 = Activation('relu')(bn17) conv18 = Conv2D(num_filter * 1, 3, activation='linear', padding='same', strides=1)(relu17) bn18 = BatchNormalization()(conv18) relu18 = Activation('relu')(bn18) # Segmentation branch segmentation_output = Conv2D(1, 1, activation='sigmoid', name='segmentation_output')(relu18) #original # Classification branch (Not done) gap1 = GlobalAveragePooling2D()(relu8) gap2 = GlobalAveragePooling2D()(relu10) gap3 = GlobalAveragePooling2D()(relu12) conv20 = Conv2D(16, 3, activation='linear', padding='same', strides=1)(segmentation_output) bn20 = BatchNormalization()(conv20) relu20 = Activation('relu')(bn20) down5 = MaxPooling2D(pool_size=(4, 4), strides=4)(relu20) conv21 = Conv2D(32, 3, activation='linear', padding='same', strides=1)(down5) bn21 = BatchNormalization()(conv21) relu21 = Activation('relu')(bn21) down6 = MaxPooling2D(pool_size=(4, 4), strides=4)(relu21) conv22 = Conv2D(64, 3, activation='linear', padding='same', strides=1)(down6) bn22 = BatchNormalization()(conv22) relu22 = Activation('relu')(bn22) down7 = MaxPooling2D(pool_size=(4, 4), strides=4)(relu22) flatten1 = Flatten()(down7) concat5 = concatenate([gap1, gap2, gap3, flatten1], axis = -1) # axis = -1 # FC layers fc1 = Dense(1024, activation='relu')(concat5) # 512, 256 match with num_filter = 8 dropout1 = Dropout(0.5)(fc1) fc2 = Dense(1024, activation='relu')(dropout1) # 512,256 dropout2 = Dropout(0.5)(fc2) classification_output = Dense(num_classes, activation='softmax', name='classification_output')(dropout2) # Define the model model = Model(inputs=inputs, outputs=[classification_output, segmentation_output]) model.summary() # Compile model def segmentation_loss(y_true, y_pred): y_true = tf.cast(y_true, tf.float32) y_pred = tf.cast(y_pred, tf.float32) # Binary cross-entropy loss bce_loss = tf.keras.losses.binary_crossentropy(y_true, y_pred) # Dice loss smooth = 1e-6 intersection = tf.reduce_sum(y_true * y_pred) union = tf.reduce_sum(y_true) + tf.reduce_sum(y_pred) dice_loss = 1.0 - 2.0 * (intersection + smooth) / (union + smooth) # Combine losses segmentation_loss = bce_loss + 1 * dice_loss return segmentation_loss model.compile(optimizer=Adam(lr=0.001), loss={'classification_output': 'categorical_crossentropy', 'segmentation_output': segmentation_loss}, # binary_crossentropy metrics={'classification_output': 'accuracy', 'segmentation_output': 'accuracy'}, loss_weights={'classification_output': 1, 'segmentation_output': 1}) # Define the callbacks checkpoint = ModelCheckpoint("multitask_best_weights.h5", monitor="val_classification_output_accuracy", save_best_only=True, mode="max", verbose=1) reduce_lr = ReduceLROnPlateau(monitor="val_classification_output_accuracy", factor=0.3, patience=2, min_delta=0.001, mode='auto', verbose=1) tensorboard = TensorBoard(log_dir='logs') history = model.fit(X_train, {'classification_output': y_train_class, 'segmentation_output': y_train_seg}, validation_data=(X_val, {'classification_output': y_val_class, 'segmentation_output': y_val_seg}), epochs=50, verbose=1, batch_size=16, callbacks=[checkpoint,reduce_lr,tensorboard]) # reduce_lr # Evaluate the model with tf.keras.utils.custom_object_scope({'segmentation_loss': segmentation_loss}): # Load the model best_model = load_model('multitask_best_weights.h5') # Evaluate the model on test data test_loss, test_class_loss, test_seg_loss, test_class_acc, test_seg_acc = best_model.evaluate(X_test, {'classification_output': y_test_class, 'segmentation_output': y_test_seg}) print("Test Classification Loss:", test_class_loss) print("Test Segmentation Loss:", test_seg_loss) print("Test Classification Accuracy:", test_class_acc) print("Test Segmentation Accuracy:", test_seg_acc) # Evaluate the model on validation data val_loss, val_class_loss, val_seg_loss, val_class_acc, val_seg_acc = best_model.evaluate(X_val, {'classification_output': y_val_class, 'segmentation_output': y_val_seg}) print("Validation Classification Loss:", val_class_loss) print("Validation Segmentation Loss:", val_seg_loss) print("Validation Classification Accuracy:", val_class_acc) print("Validation Segmentation Accuracy:", val_seg_acc) # Evaluate the model on training data train_loss, train_class_loss, train_seg_loss, train_class_acc, train_seg_acc = best_model.evaluate(X_train, {'classification_output': y_train_class, 'segmentation_output': y_train_seg}) print("Train Classification Loss:", train_class_loss) print("Train Segmentation Loss:", train_seg_loss) print("Train Classification Accuracy:", train_class_acc) print("Train Segmentation Accuracy:", train_seg_acc) # Plot performance classification_train_accuracy = history.history['classification_output_accuracy'] classification_train_loss = history.history['classification_output_loss'] classification_val_accuracy = history.history['val_classification_output_accuracy'] classification_val_loss = history.history['val_classification_output_loss'] segmentation_train_accuracy = history.history['segmentation_output_accuracy'] segmentation_train_loss = history.history['segmentation_output_loss'] segmentation_val_accuracy = history.history['val_segmentation_output_accuracy'] segmentation_val_loss = history.history['val_segmentation_output_loss'] # Plot classification accuracy plt.figure(figsize=(7, 3)) plt.plot(classification_train_accuracy, label='Training Accuracy') plt.plot(classification_val_accuracy, label='Validation Accuracy') plt.title('Classification Accuracy') plt.xlabel('Epochs') plt.ylabel('Accuracy') plt.legend() plt.show() # Plot segmentation accuracy plt.figure(figsize=(7, 3)) plt.plot(segmentation_train_accuracy, label='Training Accuracy') plt.plot(segmentation_val_accuracy, label='Validation Accuracy') plt.title('Segmentation Accuracy') plt.xlabel('Epochs') plt.ylabel('Accuracy') plt.legend() plt.show() # Plot classification loss plt.figure(figsize=(7, 3)) plt.plot(classification_train_loss,'b', label='Training Loss') plt.plot(classification_val_loss,'r', label='Validation Loss') plt.title('Classification Loss') plt.xlabel('Epochs') plt.ylabel('Loss') plt.legend() plt.show() # Plot segmentation loss plt.figure(figsize=(7, 3)) plt.plot(segmentation_train_loss,'b', label='Training Loss') plt.plot(segmentation_val_loss,'r', label='Validation Loss') plt.title('Segmentation Loss') plt.xlabel('Epochs') plt.ylabel('Loss') plt.legend() plt.show() " The above is the Python code with Keras to do multi-task learning with binary segmentation and classification using one mult-task learning model. Modify the code so that it can run 5 independent runs to train the model and take the average test accuracies of the 5 runs. Also, remove the save best model function.
6f9d22f13cffc598fc9b00430cee0cde
{ "intermediate": 0.29371780157089233, "beginner": 0.34619608521461487, "expert": 0.3600860834121704 }
42,686
You are a Python expert who can provide clear, concise, high-quality code. " import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns import cv2 import random from keras.models import load_model import tensorflow as tf from tensorflow.keras.optimizers import Adam, SGD, RMSprop, AdamW, Adadelta, Adagrad, Adamax, Adafactor, Nadam, Ftrl from tensorflow.keras.preprocessing.image import ImageDataGenerator from tqdm import tqdm import os from sklearn.utils import shuffle from sklearn.model_selection import train_test_split from tensorflow.keras.models import Sequential, Model from tensorflow.keras.layers import GlobalAveragePooling2D, Dropout, Dense, Conv2D, MaxPooling2D, Flatten, Dropout, BatchNormalization, Activation, concatenate, Conv2DTranspose, Input, Reshape, UpSampling2D from tensorflow.python.ops.gen_nn_ops import FusedBatchNormGradV2 from tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau, TensorBoard, ModelCheckpoint from sklearn.metrics import classification_report, confusion_matrix import ipywidgets as widgets import io from PIL import Image from IPython.display import display, clear_output from warnings import filterwarnings from google.colab import drive drive.mount('/content/gdrive') # Set image size image_size = 224 # Define labels labels = ['bridge', 'excess', 'good'] # Create data arrays X_train = [] # Train data y_train_class = [] # Train classification label y_train_seg = [] # Train segmentation label X_val = [] # Validation data y_val_class = [] # Validation classification label y_val_seg = [] # Validation segmentation label X_test = [] # Test data y_test_class = [] # Test classification label y_test_seg = [] # Test segmentation label # Load training data for label in labels: folderPath = os.path.join('/content/gdrive/MyDrive/FYP/5 Dataset Ratio 20 20 60 TP 10 to 90/jit012_p0.1-0.9/jit0_p0.5/f_dip/train', label) for filename in tqdm(os.listdir(folderPath)): if filename.endswith('.jpg'): img = cv2.imread(os.path.join(folderPath, filename)) img = cv2.resize(img, (image_size, image_size)) X_train.append(img) y_train_class.append(label) seg_filename = filename.split('.')[0] + '.png' seg_img = cv2.imread(os.path.join(folderPath, seg_filename), 0) seg_img = cv2.resize(seg_img, (image_size, image_size)) seg_img = np.where(seg_img > 0, 1, 0) # Convert segmentation mask to binary y_train_seg.append(seg_img) # Load validation data for label in labels: folderPath = os.path.join('/content/gdrive/MyDrive/FYP/5 Dataset Ratio 20 20 60 TP 10 to 90/jit012_p0.1-0.9/jit0_p0.5/f_dip/val', label) for filename in tqdm(os.listdir(folderPath)): if filename.endswith('.jpg'): img = cv2.imread(os.path.join(folderPath, filename)) img = cv2.resize(img, (image_size, image_size)) X_val.append(img) y_val_class.append(label) seg_filename = filename.split('.')[0] + '.png' seg_img = cv2.imread(os.path.join(folderPath, seg_filename), 0) seg_img = cv2.resize(seg_img, (image_size, image_size)) seg_img = np.where(seg_img > 0, 1, 0) # Convert segmentation mask to binary y_val_seg.append(seg_img) # Load test data for label in labels: folderPath = os.path.join('/content/gdrive/MyDrive/FYP/5 Dataset Ratio 20 20 60 TP 10 to 90/jit012_p0.1-0.9/jit0_p0.5/f_dip/test', label) for filename in tqdm(os.listdir(folderPath)): if filename.endswith('.jpg'): img = cv2.imread(os.path.join(folderPath, filename)) img = cv2.resize(img, (image_size, image_size)) X_test.append(img) y_test_class.append(label) seg_filename = filename.split('.')[0] + '.png' seg_img = cv2.imread(os.path.join(folderPath, seg_filename), 0) seg_img = cv2.resize(seg_img, (image_size, image_size)) seg_img = np.where(seg_img > 0, 1, 0) # Convert segmentation mask to binary y_test_seg.append(seg_img) # Convert to numpy arrays X_train = np.array(X_train) y_train_class = np.array(y_train_class) y_train_seg = np.array(y_train_seg) X_val = np.array(X_val) y_val_class = np.array(y_val_class) y_val_seg = np.array(y_val_seg) X_test = np.array(X_test) y_test_class = np.array(y_test_class) y_test_seg = np.array(y_test_seg) # Shuffle the data X_train, y_train_class, y_train_seg = shuffle(X_train, y_train_class, y_train_seg, random_state=101) # One Hot Encoding for classification labels y_train_class_new = [] for label in y_train_class: y_train_class_new.append(labels.index(label)) y_train_class = y_train_class_new y_train_class = tf.keras.utils.to_categorical(y_train_class) y_val_class_new = [] for label in y_val_class: y_val_class_new.append(labels.index(label)) y_val_class = y_val_class_new y_val_class = tf.keras.utils.to_categorical(y_val_class) y_test_class_new = [] for label in y_test_class: y_test_class_new.append(labels.index(label)) y_test_class = y_test_class_new y_test_class = tf.keras.utils.to_categorical(y_test_class) # Print the counts print("Number of train images:", len(X_train)) print("Number of train binary masks:", len(y_train_seg)) print("Number of validation images:", len(X_val)) print("Number of validation binary masks:", len(y_val_seg)) print("Number of test images:", len(X_test)) print("Number of test binary masks:", len(y_test_seg)) # Define U-Net model input_shape = (image_size, image_size, 3) num_classes = len(labels) inputs = Input(input_shape) num_filter = 32 # 16/32 best, 8: best classification but no segment # Encoder (Done) conv1 = Conv2D(num_filter * 1, 3, activation='linear', padding='same', strides=1)(inputs) bn1 = BatchNormalization()(conv1) relu1 = Activation('relu')(bn1) conv2 = Conv2D(num_filter * 1, 3, activation='linear', padding='same', strides=1)(relu1) bn2 = BatchNormalization()(conv2) relu2 = Activation('relu')(bn2) down1 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu2) conv3 = Conv2D(num_filter * 2, 3, activation='linear', padding='same', strides=1)(down1) bn3 = BatchNormalization()(conv3) relu3 = Activation('relu')(bn3) conv4 = Conv2D(num_filter * 2, 3, activation='linear', padding='same', strides=1)(relu3) bn4 = BatchNormalization()(conv4) relu4 = Activation('relu')(bn4) down2 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu4) conv5 = Conv2D(num_filter * 4, 3, activation='linear', padding='same', strides=1)(down2) bn5 = BatchNormalization()(conv5) relu5 = Activation('relu')(bn5) conv6 = Conv2D(num_filter * 4, 3, activation='linear', padding='same', strides=1)(relu5) bn6 = BatchNormalization()(conv6) relu6 = Activation('relu')(bn6) down3 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu6) conv7 = Conv2D(num_filter * 8, 3, activation='linear', padding='same', strides=1)(down3) bn7 = BatchNormalization()(conv7) relu7 = Activation('relu')(bn7) conv8 = Conv2D(num_filter * 8, 3, activation='linear', padding='same', strides=1)(relu7) bn8 = BatchNormalization()(conv8) relu8 = Activation('relu')(bn8) # Middle down4 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu8) conv9 = Conv2D(num_filter * 16, 3, activation='linear', padding='same', strides=1)(down4) bn9 = BatchNormalization()(conv9) relu9 = Activation('relu')(bn9) conv10 = Conv2D(num_filter * 16, 3, activation='linear', padding='same', strides=1)(relu9) bn10 = BatchNormalization()(conv10) relu10 = Activation('relu')(bn10) up1 = UpSampling2D(size=(2, 2), interpolation='bilinear')(relu10) # Decoder (Done) concat1 = concatenate([up1, relu8], axis=-1) #, axis=3 conv11 = Conv2D(num_filter * 8, 3, activation='linear', padding='same', strides=1)(concat1) bn11 = BatchNormalization()(conv11) relu11 = Activation('relu')(bn11) conv12 = Conv2D(num_filter * 8, 3, activation='linear', padding='same', strides=1)(relu11) bn12 = BatchNormalization()(conv12) relu12 = Activation('relu')(bn12) up2 = UpSampling2D(size=(2, 2), interpolation='bilinear')(relu12) concat2 = concatenate([up2, relu6], axis=-1) #, axis=3 conv13 = Conv2D(num_filter * 4, 3, activation='linear', padding='same', strides=1)(concat2) bn13 = BatchNormalization()(conv13) relu13 = Activation('relu')(bn13) conv14 = Conv2D(num_filter * 4, 3, activation='linear', padding='same', strides=1)(relu13) bn14 = BatchNormalization()(conv14) relu14 = Activation('relu')(bn14) up3 = UpSampling2D(size=(2, 2), interpolation='bilinear')(relu14) concat3 = concatenate([up3, relu4], axis=-1) #, axis=3 conv15 = Conv2D(num_filter * 2, 3, activation='linear', padding='same', strides=1)(concat3) bn15 = BatchNormalization()(conv15) relu15 = Activation('relu')(bn15) conv16 = Conv2D(num_filter * 2, 3, activation='linear', padding='same', strides=1)(relu15) bn16 = BatchNormalization()(conv16) relu16 = Activation('relu')(bn16) up4 = UpSampling2D(size=(2, 2), interpolation='bilinear')(relu16) concat4 = concatenate([up4, relu2], axis=-1) #, axis=3 conv17 = Conv2D(num_filter * 1, 3, activation='linear', padding='same', strides=1)(concat4) bn17 = BatchNormalization()(conv17) relu17 = Activation('relu')(bn17) conv18 = Conv2D(num_filter * 1, 3, activation='linear', padding='same', strides=1)(relu17) bn18 = BatchNormalization()(conv18) relu18 = Activation('relu')(bn18) # Segmentation branch segmentation_output = Conv2D(1, 1, activation='sigmoid', name='segmentation_output')(relu18) #original # Classification branch (Not done) gap1 = GlobalAveragePooling2D()(relu8) gap2 = GlobalAveragePooling2D()(relu10) gap3 = GlobalAveragePooling2D()(relu12) conv20 = Conv2D(16, 3, activation='linear', padding='same', strides=1)(segmentation_output) bn20 = BatchNormalization()(conv20) relu20 = Activation('relu')(bn20) down5 = MaxPooling2D(pool_size=(4, 4), strides=4)(relu20) conv21 = Conv2D(32, 3, activation='linear', padding='same', strides=1)(down5) bn21 = BatchNormalization()(conv21) relu21 = Activation('relu')(bn21) down6 = MaxPooling2D(pool_size=(4, 4), strides=4)(relu21) conv22 = Conv2D(64, 3, activation='linear', padding='same', strides=1)(down6) bn22 = BatchNormalization()(conv22) relu22 = Activation('relu')(bn22) down7 = MaxPooling2D(pool_size=(4, 4), strides=4)(relu22) flatten1 = Flatten()(down7) concat5 = concatenate([gap1, gap2, gap3, flatten1], axis = -1) # axis = -1 # FC layers fc1 = Dense(1024, activation='relu')(concat5) # 512, 256 match with num_filter = 8 dropout1 = Dropout(0.5)(fc1) fc2 = Dense(1024, activation='relu')(dropout1) # 512,256 dropout2 = Dropout(0.5)(fc2) classification_output = Dense(num_classes, activation='softmax', name='classification_output')(dropout2) # Define the model model = Model(inputs=inputs, outputs=[classification_output, segmentation_output]) model.summary() # Compile model def segmentation_loss(y_true, y_pred): y_true = tf.cast(y_true, tf.float32) y_pred = tf.cast(y_pred, tf.float32) # Binary cross-entropy loss bce_loss = tf.keras.losses.binary_crossentropy(y_true, y_pred) # Dice loss smooth = 1e-6 intersection = tf.reduce_sum(y_true * y_pred) union = tf.reduce_sum(y_true) + tf.reduce_sum(y_pred) dice_loss = 1.0 - 2.0 * (intersection + smooth) / (union + smooth) # Combine losses segmentation_loss = bce_loss + 1 * dice_loss return segmentation_loss model.compile(optimizer=Adam(lr=0.001), loss={'classification_output': 'categorical_crossentropy', 'segmentation_output': segmentation_loss}, # binary_crossentropy metrics={'classification_output': 'accuracy', 'segmentation_output': 'accuracy'}, loss_weights={'classification_output': 1, 'segmentation_output': 1}) # Define the callbacks checkpoint = ModelCheckpoint("multitask_best_weights.h5", monitor="val_classification_output_accuracy", save_best_only=True, mode="max", verbose=1) reduce_lr = ReduceLROnPlateau(monitor="val_classification_output_accuracy", factor=0.3, patience=2, min_delta=0.001, mode='auto', verbose=1) tensorboard = TensorBoard(log_dir='logs') history = model.fit(X_train, {'classification_output': y_train_class, 'segmentation_output': y_train_seg}, validation_data=(X_val, {'classification_output': y_val_class, 'segmentation_output': y_val_seg}), epochs=50, verbose=1, batch_size=16, callbacks=[checkpoint,reduce_lr,tensorboard]) # reduce_lr # Evaluate the model with tf.keras.utils.custom_object_scope({'segmentation_loss': segmentation_loss}): # Load the model best_model = load_model('multitask_best_weights.h5') # Evaluate the model on test data test_loss, test_class_loss, test_seg_loss, test_class_acc, test_seg_acc = best_model.evaluate(X_test, {'classification_output': y_test_class, 'segmentation_output': y_test_seg}) print("Test Classification Loss:", test_class_loss) print("Test Segmentation Loss:", test_seg_loss) print("Test Classification Accuracy:", test_class_acc) print("Test Segmentation Accuracy:", test_seg_acc) # Evaluate the model on validation data val_loss, val_class_loss, val_seg_loss, val_class_acc, val_seg_acc = best_model.evaluate(X_val, {'classification_output': y_val_class, 'segmentation_output': y_val_seg}) print("Validation Classification Loss:", val_class_loss) print("Validation Segmentation Loss:", val_seg_loss) print("Validation Classification Accuracy:", val_class_acc) print("Validation Segmentation Accuracy:", val_seg_acc) # Evaluate the model on training data train_loss, train_class_loss, train_seg_loss, train_class_acc, train_seg_acc = best_model.evaluate(X_train, {'classification_output': y_train_class, 'segmentation_output': y_train_seg}) print("Train Classification Loss:", train_class_loss) print("Train Segmentation Loss:", train_seg_loss) print("Train Classification Accuracy:", train_class_acc) print("Train Segmentation Accuracy:", train_seg_acc) # Plot performance classification_train_accuracy = history.history['classification_output_accuracy'] classification_train_loss = history.history['classification_output_loss'] classification_val_accuracy = history.history['val_classification_output_accuracy'] classification_val_loss = history.history['val_classification_output_loss'] segmentation_train_accuracy = history.history['segmentation_output_accuracy'] segmentation_train_loss = history.history['segmentation_output_loss'] segmentation_val_accuracy = history.history['val_segmentation_output_accuracy'] segmentation_val_loss = history.history['val_segmentation_output_loss'] # Plot classification accuracy plt.figure(figsize=(7, 3)) plt.plot(classification_train_accuracy, label='Training Accuracy') plt.plot(classification_val_accuracy, label='Validation Accuracy') plt.title('Classification Accuracy') plt.xlabel('Epochs') plt.ylabel('Accuracy') plt.legend() plt.show() # Plot segmentation accuracy plt.figure(figsize=(7, 3)) plt.plot(segmentation_train_accuracy, label='Training Accuracy') plt.plot(segmentation_val_accuracy, label='Validation Accuracy') plt.title('Segmentation Accuracy') plt.xlabel('Epochs') plt.ylabel('Accuracy') plt.legend() plt.show() # Plot classification loss plt.figure(figsize=(7, 3)) plt.plot(classification_train_loss,'b', label='Training Loss') plt.plot(classification_val_loss,'r', label='Validation Loss') plt.title('Classification Loss') plt.xlabel('Epochs') plt.ylabel('Loss') plt.legend() plt.show() # Plot segmentation loss plt.figure(figsize=(7, 3)) plt.plot(segmentation_train_loss,'b', label='Training Loss') plt.plot(segmentation_val_loss,'r', label='Validation Loss') plt.title('Segmentation Loss') plt.xlabel('Epochs') plt.ylabel('Loss') plt.legend() plt.show() " The above is the Python code with Keras to do multi-task learning with binary segmentation and classification using one mult-task learning model. Modify the code so that it can run 5 independent runs to train the model and take the average test accuracies of the 5 runs. Also, remove the save best model function.
9ec96e98c6a386b93444a93fde108843
{ "intermediate": 0.29371780157089233, "beginner": 0.34619608521461487, "expert": 0.3600860834121704 }
42,687
You are a Python expert who can provide clear, concise, high-quality code. " import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns import cv2 import random from keras.models import load_model import tensorflow as tf from tensorflow.keras.optimizers import Adam, SGD, RMSprop, AdamW, Adadelta, Adagrad, Adamax, Adafactor, Nadam, Ftrl from tensorflow.keras.preprocessing.image import ImageDataGenerator from tqdm import tqdm import os from sklearn.utils import shuffle from sklearn.model_selection import train_test_split from tensorflow.keras.models import Sequential, Model from tensorflow.keras.layers import GlobalAveragePooling2D, Dropout, Dense, Conv2D, MaxPooling2D, Flatten, Dropout, BatchNormalization, Activation, concatenate, Conv2DTranspose, Input, Reshape, UpSampling2D from tensorflow.python.ops.gen_nn_ops import FusedBatchNormGradV2 from tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau, TensorBoard, ModelCheckpoint from sklearn.metrics import classification_report, confusion_matrix import ipywidgets as widgets import io from PIL import Image from IPython.display import display, clear_output from warnings import filterwarnings from google.colab import drive drive.mount('/content/gdrive') # Set image size image_size = 224 # Define labels labels = ['bridge', 'excess', 'good'] # Create data arrays X_train = [] # Train data y_train_class = [] # Train classification label y_train_seg = [] # Train segmentation label X_val = [] # Validation data y_val_class = [] # Validation classification label y_val_seg = [] # Validation segmentation label X_test = [] # Test data y_test_class = [] # Test classification label y_test_seg = [] # Test segmentation label # Load training data for label in labels: folderPath = os.path.join('/content/gdrive/MyDrive/FYP/5 Dataset Ratio 20 20 60 TP 10 to 90/jit012_p0.1-0.9/jit0_p0.5/f_dip/train', label) for filename in tqdm(os.listdir(folderPath)): if filename.endswith('.jpg'): img = cv2.imread(os.path.join(folderPath, filename)) img = cv2.resize(img, (image_size, image_size)) X_train.append(img) y_train_class.append(label) seg_filename = filename.split('.')[0] + '.png' seg_img = cv2.imread(os.path.join(folderPath, seg_filename), 0) seg_img = cv2.resize(seg_img, (image_size, image_size)) seg_img = np.where(seg_img > 0, 1, 0) # Convert segmentation mask to binary y_train_seg.append(seg_img) # Load validation data for label in labels: folderPath = os.path.join('/content/gdrive/MyDrive/FYP/5 Dataset Ratio 20 20 60 TP 10 to 90/jit012_p0.1-0.9/jit0_p0.5/f_dip/val', label) for filename in tqdm(os.listdir(folderPath)): if filename.endswith('.jpg'): img = cv2.imread(os.path.join(folderPath, filename)) img = cv2.resize(img, (image_size, image_size)) X_val.append(img) y_val_class.append(label) seg_filename = filename.split('.')[0] + '.png' seg_img = cv2.imread(os.path.join(folderPath, seg_filename), 0) seg_img = cv2.resize(seg_img, (image_size, image_size)) seg_img = np.where(seg_img > 0, 1, 0) # Convert segmentation mask to binary y_val_seg.append(seg_img) # Load test data for label in labels: folderPath = os.path.join('/content/gdrive/MyDrive/FYP/5 Dataset Ratio 20 20 60 TP 10 to 90/jit012_p0.1-0.9/jit0_p0.5/f_dip/test', label) for filename in tqdm(os.listdir(folderPath)): if filename.endswith('.jpg'): img = cv2.imread(os.path.join(folderPath, filename)) img = cv2.resize(img, (image_size, image_size)) X_test.append(img) y_test_class.append(label) seg_filename = filename.split('.')[0] + '.png' seg_img = cv2.imread(os.path.join(folderPath, seg_filename), 0) seg_img = cv2.resize(seg_img, (image_size, image_size)) seg_img = np.where(seg_img > 0, 1, 0) # Convert segmentation mask to binary y_test_seg.append(seg_img) # Convert to numpy arrays X_train = np.array(X_train) y_train_class = np.array(y_train_class) y_train_seg = np.array(y_train_seg) X_val = np.array(X_val) y_val_class = np.array(y_val_class) y_val_seg = np.array(y_val_seg) X_test = np.array(X_test) y_test_class = np.array(y_test_class) y_test_seg = np.array(y_test_seg) # Shuffle the data X_train, y_train_class, y_train_seg = shuffle(X_train, y_train_class, y_train_seg, random_state=101) # One Hot Encoding for classification labels y_train_class_new = [] for label in y_train_class: y_train_class_new.append(labels.index(label)) y_train_class = y_train_class_new y_train_class = tf.keras.utils.to_categorical(y_train_class) y_val_class_new = [] for label in y_val_class: y_val_class_new.append(labels.index(label)) y_val_class = y_val_class_new y_val_class = tf.keras.utils.to_categorical(y_val_class) y_test_class_new = [] for label in y_test_class: y_test_class_new.append(labels.index(label)) y_test_class = y_test_class_new y_test_class = tf.keras.utils.to_categorical(y_test_class) # Print the counts print("Number of train images:", len(X_train)) print("Number of train binary masks:", len(y_train_seg)) print("Number of validation images:", len(X_val)) print("Number of validation binary masks:", len(y_val_seg)) print("Number of test images:", len(X_test)) print("Number of test binary masks:", len(y_test_seg)) # Define U-Net model input_shape = (image_size, image_size, 3) num_classes = len(labels) inputs = Input(input_shape) num_filter = 32 # 16/32 best, 8: best classification but no segment # Encoder (Done) conv1 = Conv2D(num_filter * 1, 3, activation='linear', padding='same', strides=1)(inputs) bn1 = BatchNormalization()(conv1) relu1 = Activation('relu')(bn1) conv2 = Conv2D(num_filter * 1, 3, activation='linear', padding='same', strides=1)(relu1) bn2 = BatchNormalization()(conv2) relu2 = Activation('relu')(bn2) down1 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu2) conv3 = Conv2D(num_filter * 2, 3, activation='linear', padding='same', strides=1)(down1) bn3 = BatchNormalization()(conv3) relu3 = Activation('relu')(bn3) conv4 = Conv2D(num_filter * 2, 3, activation='linear', padding='same', strides=1)(relu3) bn4 = BatchNormalization()(conv4) relu4 = Activation('relu')(bn4) down2 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu4) conv5 = Conv2D(num_filter * 4, 3, activation='linear', padding='same', strides=1)(down2) bn5 = BatchNormalization()(conv5) relu5 = Activation('relu')(bn5) conv6 = Conv2D(num_filter * 4, 3, activation='linear', padding='same', strides=1)(relu5) bn6 = BatchNormalization()(conv6) relu6 = Activation('relu')(bn6) down3 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu6) conv7 = Conv2D(num_filter * 8, 3, activation='linear', padding='same', strides=1)(down3) bn7 = BatchNormalization()(conv7) relu7 = Activation('relu')(bn7) conv8 = Conv2D(num_filter * 8, 3, activation='linear', padding='same', strides=1)(relu7) bn8 = BatchNormalization()(conv8) relu8 = Activation('relu')(bn8) # Middle down4 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu8) conv9 = Conv2D(num_filter * 16, 3, activation='linear', padding='same', strides=1)(down4) bn9 = BatchNormalization()(conv9) relu9 = Activation('relu')(bn9) conv10 = Conv2D(num_filter * 16, 3, activation='linear', padding='same', strides=1)(relu9) bn10 = BatchNormalization()(conv10) relu10 = Activation('relu')(bn10) up1 = UpSampling2D(size=(2, 2), interpolation='bilinear')(relu10) # Decoder (Done) concat1 = concatenate([up1, relu8], axis=-1) #, axis=3 conv11 = Conv2D(num_filter * 8, 3, activation='linear', padding='same', strides=1)(concat1) bn11 = BatchNormalization()(conv11) relu11 = Activation('relu')(bn11) conv12 = Conv2D(num_filter * 8, 3, activation='linear', padding='same', strides=1)(relu11) bn12 = BatchNormalization()(conv12) relu12 = Activation('relu')(bn12) up2 = UpSampling2D(size=(2, 2), interpolation='bilinear')(relu12) concat2 = concatenate([up2, relu6], axis=-1) #, axis=3 conv13 = Conv2D(num_filter * 4, 3, activation='linear', padding='same', strides=1)(concat2) bn13 = BatchNormalization()(conv13) relu13 = Activation('relu')(bn13) conv14 = Conv2D(num_filter * 4, 3, activation='linear', padding='same', strides=1)(relu13) bn14 = BatchNormalization()(conv14) relu14 = Activation('relu')(bn14) up3 = UpSampling2D(size=(2, 2), interpolation='bilinear')(relu14) concat3 = concatenate([up3, relu4], axis=-1) #, axis=3 conv15 = Conv2D(num_filter * 2, 3, activation='linear', padding='same', strides=1)(concat3) bn15 = BatchNormalization()(conv15) relu15 = Activation('relu')(bn15) conv16 = Conv2D(num_filter * 2, 3, activation='linear', padding='same', strides=1)(relu15) bn16 = BatchNormalization()(conv16) relu16 = Activation('relu')(bn16) up4 = UpSampling2D(size=(2, 2), interpolation='bilinear')(relu16) concat4 = concatenate([up4, relu2], axis=-1) #, axis=3 conv17 = Conv2D(num_filter * 1, 3, activation='linear', padding='same', strides=1)(concat4) bn17 = BatchNormalization()(conv17) relu17 = Activation('relu')(bn17) conv18 = Conv2D(num_filter * 1, 3, activation='linear', padding='same', strides=1)(relu17) bn18 = BatchNormalization()(conv18) relu18 = Activation('relu')(bn18) # Segmentation branch segmentation_output = Conv2D(1, 1, activation='sigmoid', name='segmentation_output')(relu18) #original # Classification branch (Not done) gap1 = GlobalAveragePooling2D()(relu8) gap2 = GlobalAveragePooling2D()(relu10) gap3 = GlobalAveragePooling2D()(relu12) conv20 = Conv2D(16, 3, activation='linear', padding='same', strides=1)(segmentation_output) bn20 = BatchNormalization()(conv20) relu20 = Activation('relu')(bn20) down5 = MaxPooling2D(pool_size=(4, 4), strides=4)(relu20) conv21 = Conv2D(32, 3, activation='linear', padding='same', strides=1)(down5) bn21 = BatchNormalization()(conv21) relu21 = Activation('relu')(bn21) down6 = MaxPooling2D(pool_size=(4, 4), strides=4)(relu21) conv22 = Conv2D(64, 3, activation='linear', padding='same', strides=1)(down6) bn22 = BatchNormalization()(conv22) relu22 = Activation('relu')(bn22) down7 = MaxPooling2D(pool_size=(4, 4), strides=4)(relu22) flatten1 = Flatten()(down7) concat5 = concatenate([gap1, gap2, gap3, flatten1], axis = -1) # axis = -1 # FC layers fc1 = Dense(1024, activation='relu')(concat5) # 512, 256 match with num_filter = 8 dropout1 = Dropout(0.5)(fc1) fc2 = Dense(1024, activation='relu')(dropout1) # 512,256 dropout2 = Dropout(0.5)(fc2) classification_output = Dense(num_classes, activation='softmax', name='classification_output')(dropout2) # Define the model model = Model(inputs=inputs, outputs=[classification_output, segmentation_output]) model.summary() # Compile model def segmentation_loss(y_true, y_pred): y_true = tf.cast(y_true, tf.float32) y_pred = tf.cast(y_pred, tf.float32) # Binary cross-entropy loss bce_loss = tf.keras.losses.binary_crossentropy(y_true, y_pred) # Dice loss smooth = 1e-6 intersection = tf.reduce_sum(y_true * y_pred) union = tf.reduce_sum(y_true) + tf.reduce_sum(y_pred) dice_loss = 1.0 - 2.0 * (intersection + smooth) / (union + smooth) # Combine losses segmentation_loss = bce_loss + 1 * dice_loss return segmentation_loss model.compile(optimizer=Adam(lr=0.001), loss={'classification_output': 'categorical_crossentropy', 'segmentation_output': segmentation_loss}, # binary_crossentropy metrics={'classification_output': 'accuracy', 'segmentation_output': 'accuracy'}, loss_weights={'classification_output': 1, 'segmentation_output': 1}) # Define the callbacks checkpoint = ModelCheckpoint("multitask_best_weights.h5", monitor="val_classification_output_accuracy", save_best_only=True, mode="max", verbose=1) reduce_lr = ReduceLROnPlateau(monitor="val_classification_output_accuracy", factor=0.3, patience=2, min_delta=0.001, mode='auto', verbose=1) tensorboard = TensorBoard(log_dir='logs') history = model.fit(X_train, {'classification_output': y_train_class, 'segmentation_output': y_train_seg}, validation_data=(X_val, {'classification_output': y_val_class, 'segmentation_output': y_val_seg}), epochs=50, verbose=1, batch_size=16, callbacks=[checkpoint,reduce_lr,tensorboard]) # reduce_lr # Evaluate the model with tf.keras.utils.custom_object_scope({'segmentation_loss': segmentation_loss}): # Load the model best_model = load_model('multitask_best_weights.h5') # Evaluate the model on test data test_loss, test_class_loss, test_seg_loss, test_class_acc, test_seg_acc = best_model.evaluate(X_test, {'classification_output': y_test_class, 'segmentation_output': y_test_seg}) print("Test Classification Loss:", test_class_loss) print("Test Segmentation Loss:", test_seg_loss) print("Test Classification Accuracy:", test_class_acc) print("Test Segmentation Accuracy:", test_seg_acc) # Evaluate the model on validation data val_loss, val_class_loss, val_seg_loss, val_class_acc, val_seg_acc = best_model.evaluate(X_val, {'classification_output': y_val_class, 'segmentation_output': y_val_seg}) print("Validation Classification Loss:", val_class_loss) print("Validation Segmentation Loss:", val_seg_loss) print("Validation Classification Accuracy:", val_class_acc) print("Validation Segmentation Accuracy:", val_seg_acc) # Evaluate the model on training data train_loss, train_class_loss, train_seg_loss, train_class_acc, train_seg_acc = best_model.evaluate(X_train, {'classification_output': y_train_class, 'segmentation_output': y_train_seg}) print("Train Classification Loss:", train_class_loss) print("Train Segmentation Loss:", train_seg_loss) print("Train Classification Accuracy:", train_class_acc) print("Train Segmentation Accuracy:", train_seg_acc) # Plot performance classification_train_accuracy = history.history['classification_output_accuracy'] classification_train_loss = history.history['classification_output_loss'] classification_val_accuracy = history.history['val_classification_output_accuracy'] classification_val_loss = history.history['val_classification_output_loss'] segmentation_train_accuracy = history.history['segmentation_output_accuracy'] segmentation_train_loss = history.history['segmentation_output_loss'] segmentation_val_accuracy = history.history['val_segmentation_output_accuracy'] segmentation_val_loss = history.history['val_segmentation_output_loss'] # Plot classification accuracy plt.figure(figsize=(7, 3)) plt.plot(classification_train_accuracy, label='Training Accuracy') plt.plot(classification_val_accuracy, label='Validation Accuracy') plt.title('Classification Accuracy') plt.xlabel('Epochs') plt.ylabel('Accuracy') plt.legend() plt.show() # Plot segmentation accuracy plt.figure(figsize=(7, 3)) plt.plot(segmentation_train_accuracy, label='Training Accuracy') plt.plot(segmentation_val_accuracy, label='Validation Accuracy') plt.title('Segmentation Accuracy') plt.xlabel('Epochs') plt.ylabel('Accuracy') plt.legend() plt.show() # Plot classification loss plt.figure(figsize=(7, 3)) plt.plot(classification_train_loss,'b', label='Training Loss') plt.plot(classification_val_loss,'r', label='Validation Loss') plt.title('Classification Loss') plt.xlabel('Epochs') plt.ylabel('Loss') plt.legend() plt.show() # Plot segmentation loss plt.figure(figsize=(7, 3)) plt.plot(segmentation_train_loss,'b', label='Training Loss') plt.plot(segmentation_val_loss,'r', label='Validation Loss') plt.title('Segmentation Loss') plt.xlabel('Epochs') plt.ylabel('Loss') plt.legend() plt.show() " The above is the Python code with Keras to do multi-task learning with binary segmentation and classification using one mult-task learning model. Modify the code so that it can run 5 independent runs to train the model and take the average test accuracies of the 5 runs. Also, remove the save best model function.
0d3dc617ac87dd480458c77328e94570
{ "intermediate": 0.29371780157089233, "beginner": 0.34619608521461487, "expert": 0.3600860834121704 }
42,688
You are a Python expert who can provide clear, concise, high-quality code. " import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns import cv2 import random from keras.models import load_model import tensorflow as tf from tensorflow.keras.optimizers import Adam, SGD, RMSprop, AdamW, Adadelta, Adagrad, Adamax, Adafactor, Nadam, Ftrl from tensorflow.keras.preprocessing.image import ImageDataGenerator from tqdm import tqdm import os from sklearn.utils import shuffle from sklearn.model_selection import train_test_split from tensorflow.keras.models import Sequential, Model from tensorflow.keras.layers import GlobalAveragePooling2D, Dropout, Dense, Conv2D, MaxPooling2D, Flatten, Dropout, BatchNormalization, Activation, concatenate, Conv2DTranspose, Input, Reshape, UpSampling2D from tensorflow.python.ops.gen_nn_ops import FusedBatchNormGradV2 from tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau, TensorBoard, ModelCheckpoint from sklearn.metrics import classification_report, confusion_matrix import ipywidgets as widgets import io from PIL import Image from IPython.display import display, clear_output from warnings import filterwarnings from google.colab import drive drive.mount('/content/gdrive') # Set image size image_size = 224 # Define labels labels = ['bridge', 'excess', 'good'] # Create data arrays X_train = [] # Train data y_train_class = [] # Train classification label y_train_seg = [] # Train segmentation label X_val = [] # Validation data y_val_class = [] # Validation classification label y_val_seg = [] # Validation segmentation label X_test = [] # Test data y_test_class = [] # Test classification label y_test_seg = [] # Test segmentation label # Load training data for label in labels: folderPath = os.path.join('/content/gdrive/MyDrive/FYP/5 Dataset Ratio 20 20 60 TP 10 to 90/jit012_p0.1-0.9/jit0_p0.5/f_dip/train', label) for filename in tqdm(os.listdir(folderPath)): if filename.endswith('.jpg'): img = cv2.imread(os.path.join(folderPath, filename)) img = cv2.resize(img, (image_size, image_size)) X_train.append(img) y_train_class.append(label) seg_filename = filename.split('.')[0] + '.png' seg_img = cv2.imread(os.path.join(folderPath, seg_filename), 0) seg_img = cv2.resize(seg_img, (image_size, image_size)) seg_img = np.where(seg_img > 0, 1, 0) # Convert segmentation mask to binary y_train_seg.append(seg_img) # Load validation data for label in labels: folderPath = os.path.join('/content/gdrive/MyDrive/FYP/5 Dataset Ratio 20 20 60 TP 10 to 90/jit012_p0.1-0.9/jit0_p0.5/f_dip/val', label) for filename in tqdm(os.listdir(folderPath)): if filename.endswith('.jpg'): img = cv2.imread(os.path.join(folderPath, filename)) img = cv2.resize(img, (image_size, image_size)) X_val.append(img) y_val_class.append(label) seg_filename = filename.split('.')[0] + '.png' seg_img = cv2.imread(os.path.join(folderPath, seg_filename), 0) seg_img = cv2.resize(seg_img, (image_size, image_size)) seg_img = np.where(seg_img > 0, 1, 0) # Convert segmentation mask to binary y_val_seg.append(seg_img) # Load test data for label in labels: folderPath = os.path.join('/content/gdrive/MyDrive/FYP/5 Dataset Ratio 20 20 60 TP 10 to 90/jit012_p0.1-0.9/jit0_p0.5/f_dip/test', label) for filename in tqdm(os.listdir(folderPath)): if filename.endswith('.jpg'): img = cv2.imread(os.path.join(folderPath, filename)) img = cv2.resize(img, (image_size, image_size)) X_test.append(img) y_test_class.append(label) seg_filename = filename.split('.')[0] + '.png' seg_img = cv2.imread(os.path.join(folderPath, seg_filename), 0) seg_img = cv2.resize(seg_img, (image_size, image_size)) seg_img = np.where(seg_img > 0, 1, 0) # Convert segmentation mask to binary y_test_seg.append(seg_img) # Convert to numpy arrays X_train = np.array(X_train) y_train_class = np.array(y_train_class) y_train_seg = np.array(y_train_seg) X_val = np.array(X_val) y_val_class = np.array(y_val_class) y_val_seg = np.array(y_val_seg) X_test = np.array(X_test) y_test_class = np.array(y_test_class) y_test_seg = np.array(y_test_seg) # Shuffle the data X_train, y_train_class, y_train_seg = shuffle(X_train, y_train_class, y_train_seg, random_state=101) # One Hot Encoding for classification labels y_train_class_new = [] for label in y_train_class: y_train_class_new.append(labels.index(label)) y_train_class = y_train_class_new y_train_class = tf.keras.utils.to_categorical(y_train_class) y_val_class_new = [] for label in y_val_class: y_val_class_new.append(labels.index(label)) y_val_class = y_val_class_new y_val_class = tf.keras.utils.to_categorical(y_val_class) y_test_class_new = [] for label in y_test_class: y_test_class_new.append(labels.index(label)) y_test_class = y_test_class_new y_test_class = tf.keras.utils.to_categorical(y_test_class) # Print the counts print("Number of train images:", len(X_train)) print("Number of train binary masks:", len(y_train_seg)) print("Number of validation images:", len(X_val)) print("Number of validation binary masks:", len(y_val_seg)) print("Number of test images:", len(X_test)) print("Number of test binary masks:", len(y_test_seg)) # Define U-Net model input_shape = (image_size, image_size, 3) num_classes = len(labels) inputs = Input(input_shape) num_filter = 32 # 16/32 best, 8: best classification but no segment # Encoder (Done) conv1 = Conv2D(num_filter * 1, 3, activation='linear', padding='same', strides=1)(inputs) bn1 = BatchNormalization()(conv1) relu1 = Activation('relu')(bn1) conv2 = Conv2D(num_filter * 1, 3, activation='linear', padding='same', strides=1)(relu1) bn2 = BatchNormalization()(conv2) relu2 = Activation('relu')(bn2) down1 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu2) conv3 = Conv2D(num_filter * 2, 3, activation='linear', padding='same', strides=1)(down1) bn3 = BatchNormalization()(conv3) relu3 = Activation('relu')(bn3) conv4 = Conv2D(num_filter * 2, 3, activation='linear', padding='same', strides=1)(relu3) bn4 = BatchNormalization()(conv4) relu4 = Activation('relu')(bn4) down2 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu4) conv5 = Conv2D(num_filter * 4, 3, activation='linear', padding='same', strides=1)(down2) bn5 = BatchNormalization()(conv5) relu5 = Activation('relu')(bn5) conv6 = Conv2D(num_filter * 4, 3, activation='linear', padding='same', strides=1)(relu5) bn6 = BatchNormalization()(conv6) relu6 = Activation('relu')(bn6) down3 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu6) conv7 = Conv2D(num_filter * 8, 3, activation='linear', padding='same', strides=1)(down3) bn7 = BatchNormalization()(conv7) relu7 = Activation('relu')(bn7) conv8 = Conv2D(num_filter * 8, 3, activation='linear', padding='same', strides=1)(relu7) bn8 = BatchNormalization()(conv8) relu8 = Activation('relu')(bn8) # Middle down4 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu8) conv9 = Conv2D(num_filter * 16, 3, activation='linear', padding='same', strides=1)(down4) bn9 = BatchNormalization()(conv9) relu9 = Activation('relu')(bn9) conv10 = Conv2D(num_filter * 16, 3, activation='linear', padding='same', strides=1)(relu9) bn10 = BatchNormalization()(conv10) relu10 = Activation('relu')(bn10) up1 = UpSampling2D(size=(2, 2), interpolation='bilinear')(relu10) # Decoder (Done) concat1 = concatenate([up1, relu8], axis=-1) #, axis=3 conv11 = Conv2D(num_filter * 8, 3, activation='linear', padding='same', strides=1)(concat1) bn11 = BatchNormalization()(conv11) relu11 = Activation('relu')(bn11) conv12 = Conv2D(num_filter * 8, 3, activation='linear', padding='same', strides=1)(relu11) bn12 = BatchNormalization()(conv12) relu12 = Activation('relu')(bn12) up2 = UpSampling2D(size=(2, 2), interpolation='bilinear')(relu12) concat2 = concatenate([up2, relu6], axis=-1) #, axis=3 conv13 = Conv2D(num_filter * 4, 3, activation='linear', padding='same', strides=1)(concat2) bn13 = BatchNormalization()(conv13) relu13 = Activation('relu')(bn13) conv14 = Conv2D(num_filter * 4, 3, activation='linear', padding='same', strides=1)(relu13) bn14 = BatchNormalization()(conv14) relu14 = Activation('relu')(bn14) up3 = UpSampling2D(size=(2, 2), interpolation='bilinear')(relu14) concat3 = concatenate([up3, relu4], axis=-1) #, axis=3 conv15 = Conv2D(num_filter * 2, 3, activation='linear', padding='same', strides=1)(concat3) bn15 = BatchNormalization()(conv15) relu15 = Activation('relu')(bn15) conv16 = Conv2D(num_filter * 2, 3, activation='linear', padding='same', strides=1)(relu15) bn16 = BatchNormalization()(conv16) relu16 = Activation('relu')(bn16) up4 = UpSampling2D(size=(2, 2), interpolation='bilinear')(relu16) concat4 = concatenate([up4, relu2], axis=-1) #, axis=3 conv17 = Conv2D(num_filter * 1, 3, activation='linear', padding='same', strides=1)(concat4) bn17 = BatchNormalization()(conv17) relu17 = Activation('relu')(bn17) conv18 = Conv2D(num_filter * 1, 3, activation='linear', padding='same', strides=1)(relu17) bn18 = BatchNormalization()(conv18) relu18 = Activation('relu')(bn18) # Segmentation branch segmentation_output = Conv2D(1, 1, activation='sigmoid', name='segmentation_output')(relu18) #original # Classification branch (Not done) gap1 = GlobalAveragePooling2D()(relu8) gap2 = GlobalAveragePooling2D()(relu10) gap3 = GlobalAveragePooling2D()(relu12) conv20 = Conv2D(16, 3, activation='linear', padding='same', strides=1)(segmentation_output) bn20 = BatchNormalization()(conv20) relu20 = Activation('relu')(bn20) down5 = MaxPooling2D(pool_size=(4, 4), strides=4)(relu20) conv21 = Conv2D(32, 3, activation='linear', padding='same', strides=1)(down5) bn21 = BatchNormalization()(conv21) relu21 = Activation('relu')(bn21) down6 = MaxPooling2D(pool_size=(4, 4), strides=4)(relu21) conv22 = Conv2D(64, 3, activation='linear', padding='same', strides=1)(down6) bn22 = BatchNormalization()(conv22) relu22 = Activation('relu')(bn22) down7 = MaxPooling2D(pool_size=(4, 4), strides=4)(relu22) flatten1 = Flatten()(down7) concat5 = concatenate([gap1, gap2, gap3, flatten1], axis = -1) # axis = -1 # FC layers fc1 = Dense(1024, activation='relu')(concat5) # 512, 256 match with num_filter = 8 dropout1 = Dropout(0.5)(fc1) fc2 = Dense(1024, activation='relu')(dropout1) # 512,256 dropout2 = Dropout(0.5)(fc2) classification_output = Dense(num_classes, activation='softmax', name='classification_output')(dropout2) # Define the model model = Model(inputs=inputs, outputs=[classification_output, segmentation_output]) model.summary() # Compile model def segmentation_loss(y_true, y_pred): y_true = tf.cast(y_true, tf.float32) y_pred = tf.cast(y_pred, tf.float32) # Binary cross-entropy loss bce_loss = tf.keras.losses.binary_crossentropy(y_true, y_pred) # Dice loss smooth = 1e-6 intersection = tf.reduce_sum(y_true * y_pred) union = tf.reduce_sum(y_true) + tf.reduce_sum(y_pred) dice_loss = 1.0 - 2.0 * (intersection + smooth) / (union + smooth) # Combine losses segmentation_loss = bce_loss + 1 * dice_loss return segmentation_loss model.compile(optimizer=Adam(lr=0.001), loss={'classification_output': 'categorical_crossentropy', 'segmentation_output': segmentation_loss}, # binary_crossentropy metrics={'classification_output': 'accuracy', 'segmentation_output': 'accuracy'}, loss_weights={'classification_output': 1, 'segmentation_output': 1}) # Define the callbacks checkpoint = ModelCheckpoint("multitask_best_weights.h5", monitor="val_classification_output_accuracy", save_best_only=True, mode="max", verbose=1) reduce_lr = ReduceLROnPlateau(monitor="val_classification_output_accuracy", factor=0.3, patience=2, min_delta=0.001, mode='auto', verbose=1) tensorboard = TensorBoard(log_dir='logs') history = model.fit(X_train, {'classification_output': y_train_class, 'segmentation_output': y_train_seg}, validation_data=(X_val, {'classification_output': y_val_class, 'segmentation_output': y_val_seg}), epochs=50, verbose=1, batch_size=16, callbacks=[checkpoint,reduce_lr,tensorboard]) # reduce_lr # Evaluate the model with tf.keras.utils.custom_object_scope({'segmentation_loss': segmentation_loss}): # Load the model best_model = load_model('multitask_best_weights.h5') # Evaluate the model on test data test_loss, test_class_loss, test_seg_loss, test_class_acc, test_seg_acc = best_model.evaluate(X_test, {'classification_output': y_test_class, 'segmentation_output': y_test_seg}) print("Test Classification Loss:", test_class_loss) print("Test Segmentation Loss:", test_seg_loss) print("Test Classification Accuracy:", test_class_acc) print("Test Segmentation Accuracy:", test_seg_acc) # Evaluate the model on validation data val_loss, val_class_loss, val_seg_loss, val_class_acc, val_seg_acc = best_model.evaluate(X_val, {'classification_output': y_val_class, 'segmentation_output': y_val_seg}) print("Validation Classification Loss:", val_class_loss) print("Validation Segmentation Loss:", val_seg_loss) print("Validation Classification Accuracy:", val_class_acc) print("Validation Segmentation Accuracy:", val_seg_acc) # Evaluate the model on training data train_loss, train_class_loss, train_seg_loss, train_class_acc, train_seg_acc = best_model.evaluate(X_train, {'classification_output': y_train_class, 'segmentation_output': y_train_seg}) print("Train Classification Loss:", train_class_loss) print("Train Segmentation Loss:", train_seg_loss) print("Train Classification Accuracy:", train_class_acc) print("Train Segmentation Accuracy:", train_seg_acc) # Plot performance classification_train_accuracy = history.history['classification_output_accuracy'] classification_train_loss = history.history['classification_output_loss'] classification_val_accuracy = history.history['val_classification_output_accuracy'] classification_val_loss = history.history['val_classification_output_loss'] segmentation_train_accuracy = history.history['segmentation_output_accuracy'] segmentation_train_loss = history.history['segmentation_output_loss'] segmentation_val_accuracy = history.history['val_segmentation_output_accuracy'] segmentation_val_loss = history.history['val_segmentation_output_loss'] # Plot classification accuracy plt.figure(figsize=(7, 3)) plt.plot(classification_train_accuracy, label='Training Accuracy') plt.plot(classification_val_accuracy, label='Validation Accuracy') plt.title('Classification Accuracy') plt.xlabel('Epochs') plt.ylabel('Accuracy') plt.legend() plt.show() # Plot segmentation accuracy plt.figure(figsize=(7, 3)) plt.plot(segmentation_train_accuracy, label='Training Accuracy') plt.plot(segmentation_val_accuracy, label='Validation Accuracy') plt.title('Segmentation Accuracy') plt.xlabel('Epochs') plt.ylabel('Accuracy') plt.legend() plt.show() # Plot classification loss plt.figure(figsize=(7, 3)) plt.plot(classification_train_loss,'b', label='Training Loss') plt.plot(classification_val_loss,'r', label='Validation Loss') plt.title('Classification Loss') plt.xlabel('Epochs') plt.ylabel('Loss') plt.legend() plt.show() # Plot segmentation loss plt.figure(figsize=(7, 3)) plt.plot(segmentation_train_loss,'b', label='Training Loss') plt.plot(segmentation_val_loss,'r', label='Validation Loss') plt.title('Segmentation Loss') plt.xlabel('Epochs') plt.ylabel('Loss') plt.legend() plt.show() " The above is the Python code with Keras to do multi-task learning with binary segmentation and classification using one mult-task learning model. Modify the code so that it can run 5 independent runs to train the model and take the average test accuracies of the 5 runs. Also, remove the save best model function.
1cbfbd60b0a25a77dc190814e5335d94
{ "intermediate": 0.29371780157089233, "beginner": 0.34619608521461487, "expert": 0.3600860834121704 }
42,689
You are a Python expert who can provide clear, concise, high-quality code. " import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns import cv2 import random from keras.models import load_model import tensorflow as tf from tensorflow.keras.optimizers import Adam, SGD, RMSprop, AdamW, Adadelta, Adagrad, Adamax, Adafactor, Nadam, Ftrl from tensorflow.keras.preprocessing.image import ImageDataGenerator from tqdm import tqdm import os from sklearn.utils import shuffle from sklearn.model_selection import train_test_split from tensorflow.keras.models import Sequential, Model from tensorflow.keras.layers import GlobalAveragePooling2D, Dropout, Dense, Conv2D, MaxPooling2D, Flatten, Dropout, BatchNormalization, Activation, concatenate, Conv2DTranspose, Input, Reshape, UpSampling2D from tensorflow.python.ops.gen_nn_ops import FusedBatchNormGradV2 from tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau, TensorBoard, ModelCheckpoint from sklearn.metrics import classification_report, confusion_matrix import ipywidgets as widgets import io from PIL import Image from IPython.display import display, clear_output from warnings import filterwarnings from google.colab import drive drive.mount('/content/gdrive') # Set image size image_size = 224 # Define labels labels = ['bridge', 'excess', 'good'] # Create data arrays X_train = [] # Train data y_train_class = [] # Train classification label y_train_seg = [] # Train segmentation label X_val = [] # Validation data y_val_class = [] # Validation classification label y_val_seg = [] # Validation segmentation label X_test = [] # Test data y_test_class = [] # Test classification label y_test_seg = [] # Test segmentation label # Load training data for label in labels: folderPath = os.path.join('/content/gdrive/MyDrive/FYP/5 Dataset Ratio 20 20 60 TP 10 to 90/jit012_p0.1-0.9/jit0_p0.5/f_dip/train', label) for filename in tqdm(os.listdir(folderPath)): if filename.endswith('.jpg'): img = cv2.imread(os.path.join(folderPath, filename)) img = cv2.resize(img, (image_size, image_size)) X_train.append(img) y_train_class.append(label) seg_filename = filename.split('.')[0] + '.png' seg_img = cv2.imread(os.path.join(folderPath, seg_filename), 0) seg_img = cv2.resize(seg_img, (image_size, image_size)) seg_img = np.where(seg_img > 0, 1, 0) # Convert segmentation mask to binary y_train_seg.append(seg_img) # Load validation data for label in labels: folderPath = os.path.join('/content/gdrive/MyDrive/FYP/5 Dataset Ratio 20 20 60 TP 10 to 90/jit012_p0.1-0.9/jit0_p0.5/f_dip/val', label) for filename in tqdm(os.listdir(folderPath)): if filename.endswith('.jpg'): img = cv2.imread(os.path.join(folderPath, filename)) img = cv2.resize(img, (image_size, image_size)) X_val.append(img) y_val_class.append(label) seg_filename = filename.split('.')[0] + '.png' seg_img = cv2.imread(os.path.join(folderPath, seg_filename), 0) seg_img = cv2.resize(seg_img, (image_size, image_size)) seg_img = np.where(seg_img > 0, 1, 0) # Convert segmentation mask to binary y_val_seg.append(seg_img) # Load test data for label in labels: folderPath = os.path.join('/content/gdrive/MyDrive/FYP/5 Dataset Ratio 20 20 60 TP 10 to 90/jit012_p0.1-0.9/jit0_p0.5/f_dip/test', label) for filename in tqdm(os.listdir(folderPath)): if filename.endswith('.jpg'): img = cv2.imread(os.path.join(folderPath, filename)) img = cv2.resize(img, (image_size, image_size)) X_test.append(img) y_test_class.append(label) seg_filename = filename.split('.')[0] + '.png' seg_img = cv2.imread(os.path.join(folderPath, seg_filename), 0) seg_img = cv2.resize(seg_img, (image_size, image_size)) seg_img = np.where(seg_img > 0, 1, 0) # Convert segmentation mask to binary y_test_seg.append(seg_img) # Convert to numpy arrays X_train = np.array(X_train) y_train_class = np.array(y_train_class) y_train_seg = np.array(y_train_seg) X_val = np.array(X_val) y_val_class = np.array(y_val_class) y_val_seg = np.array(y_val_seg) X_test = np.array(X_test) y_test_class = np.array(y_test_class) y_test_seg = np.array(y_test_seg) # Shuffle the data X_train, y_train_class, y_train_seg = shuffle(X_train, y_train_class, y_train_seg, random_state=101) # One Hot Encoding for classification labels y_train_class_new = [] for label in y_train_class: y_train_class_new.append(labels.index(label)) y_train_class = y_train_class_new y_train_class = tf.keras.utils.to_categorical(y_train_class) y_val_class_new = [] for label in y_val_class: y_val_class_new.append(labels.index(label)) y_val_class = y_val_class_new y_val_class = tf.keras.utils.to_categorical(y_val_class) y_test_class_new = [] for label in y_test_class: y_test_class_new.append(labels.index(label)) y_test_class = y_test_class_new y_test_class = tf.keras.utils.to_categorical(y_test_class) # Print the counts print("Number of train images:", len(X_train)) print("Number of train binary masks:", len(y_train_seg)) print("Number of validation images:", len(X_val)) print("Number of validation binary masks:", len(y_val_seg)) print("Number of test images:", len(X_test)) print("Number of test binary masks:", len(y_test_seg)) # Define U-Net model input_shape = (image_size, image_size, 3) num_classes = len(labels) inputs = Input(input_shape) num_filter = 32 # 16/32 best, 8: best classification but no segment # Encoder (Done) conv1 = Conv2D(num_filter * 1, 3, activation='linear', padding='same', strides=1)(inputs) bn1 = BatchNormalization()(conv1) relu1 = Activation('relu')(bn1) conv2 = Conv2D(num_filter * 1, 3, activation='linear', padding='same', strides=1)(relu1) bn2 = BatchNormalization()(conv2) relu2 = Activation('relu')(bn2) down1 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu2) conv3 = Conv2D(num_filter * 2, 3, activation='linear', padding='same', strides=1)(down1) bn3 = BatchNormalization()(conv3) relu3 = Activation('relu')(bn3) conv4 = Conv2D(num_filter * 2, 3, activation='linear', padding='same', strides=1)(relu3) bn4 = BatchNormalization()(conv4) relu4 = Activation('relu')(bn4) down2 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu4) conv5 = Conv2D(num_filter * 4, 3, activation='linear', padding='same', strides=1)(down2) bn5 = BatchNormalization()(conv5) relu5 = Activation('relu')(bn5) conv6 = Conv2D(num_filter * 4, 3, activation='linear', padding='same', strides=1)(relu5) bn6 = BatchNormalization()(conv6) relu6 = Activation('relu')(bn6) down3 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu6) conv7 = Conv2D(num_filter * 8, 3, activation='linear', padding='same', strides=1)(down3) bn7 = BatchNormalization()(conv7) relu7 = Activation('relu')(bn7) conv8 = Conv2D(num_filter * 8, 3, activation='linear', padding='same', strides=1)(relu7) bn8 = BatchNormalization()(conv8) relu8 = Activation('relu')(bn8) # Middle down4 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu8) conv9 = Conv2D(num_filter * 16, 3, activation='linear', padding='same', strides=1)(down4) bn9 = BatchNormalization()(conv9) relu9 = Activation('relu')(bn9) conv10 = Conv2D(num_filter * 16, 3, activation='linear', padding='same', strides=1)(relu9) bn10 = BatchNormalization()(conv10) relu10 = Activation('relu')(bn10) up1 = UpSampling2D(size=(2, 2), interpolation='bilinear')(relu10) # Decoder (Done) concat1 = concatenate([up1, relu8], axis=-1) #, axis=3 conv11 = Conv2D(num_filter * 8, 3, activation='linear', padding='same', strides=1)(concat1) bn11 = BatchNormalization()(conv11) relu11 = Activation('relu')(bn11) conv12 = Conv2D(num_filter * 8, 3, activation='linear', padding='same', strides=1)(relu11) bn12 = BatchNormalization()(conv12) relu12 = Activation('relu')(bn12) up2 = UpSampling2D(size=(2, 2), interpolation='bilinear')(relu12) concat2 = concatenate([up2, relu6], axis=-1) #, axis=3 conv13 = Conv2D(num_filter * 4, 3, activation='linear', padding='same', strides=1)(concat2) bn13 = BatchNormalization()(conv13) relu13 = Activation('relu')(bn13) conv14 = Conv2D(num_filter * 4, 3, activation='linear', padding='same', strides=1)(relu13) bn14 = BatchNormalization()(conv14) relu14 = Activation('relu')(bn14) up3 = UpSampling2D(size=(2, 2), interpolation='bilinear')(relu14) concat3 = concatenate([up3, relu4], axis=-1) #, axis=3 conv15 = Conv2D(num_filter * 2, 3, activation='linear', padding='same', strides=1)(concat3) bn15 = BatchNormalization()(conv15) relu15 = Activation('relu')(bn15) conv16 = Conv2D(num_filter * 2, 3, activation='linear', padding='same', strides=1)(relu15) bn16 = BatchNormalization()(conv16) relu16 = Activation('relu')(bn16) up4 = UpSampling2D(size=(2, 2), interpolation='bilinear')(relu16) concat4 = concatenate([up4, relu2], axis=-1) #, axis=3 conv17 = Conv2D(num_filter * 1, 3, activation='linear', padding='same', strides=1)(concat4) bn17 = BatchNormalization()(conv17) relu17 = Activation('relu')(bn17) conv18 = Conv2D(num_filter * 1, 3, activation='linear', padding='same', strides=1)(relu17) bn18 = BatchNormalization()(conv18) relu18 = Activation('relu')(bn18) # Segmentation branch segmentation_output = Conv2D(1, 1, activation='sigmoid', name='segmentation_output')(relu18) #original # Classification branch (Not done) gap1 = GlobalAveragePooling2D()(relu8) gap2 = GlobalAveragePooling2D()(relu10) gap3 = GlobalAveragePooling2D()(relu12) conv20 = Conv2D(16, 3, activation='linear', padding='same', strides=1)(segmentation_output) bn20 = BatchNormalization()(conv20) relu20 = Activation('relu')(bn20) down5 = MaxPooling2D(pool_size=(4, 4), strides=4)(relu20) conv21 = Conv2D(32, 3, activation='linear', padding='same', strides=1)(down5) bn21 = BatchNormalization()(conv21) relu21 = Activation('relu')(bn21) down6 = MaxPooling2D(pool_size=(4, 4), strides=4)(relu21) conv22 = Conv2D(64, 3, activation='linear', padding='same', strides=1)(down6) bn22 = BatchNormalization()(conv22) relu22 = Activation('relu')(bn22) down7 = MaxPooling2D(pool_size=(4, 4), strides=4)(relu22) flatten1 = Flatten()(down7) concat5 = concatenate([gap1, gap2, gap3, flatten1], axis = -1) # axis = -1 # FC layers fc1 = Dense(1024, activation='relu')(concat5) # 512, 256 match with num_filter = 8 dropout1 = Dropout(0.5)(fc1) fc2 = Dense(1024, activation='relu')(dropout1) # 512,256 dropout2 = Dropout(0.5)(fc2) classification_output = Dense(num_classes, activation='softmax', name='classification_output')(dropout2) # Define the model model = Model(inputs=inputs, outputs=[classification_output, segmentation_output]) model.summary() # Compile model def segmentation_loss(y_true, y_pred): y_true = tf.cast(y_true, tf.float32) y_pred = tf.cast(y_pred, tf.float32) # Binary cross-entropy loss bce_loss = tf.keras.losses.binary_crossentropy(y_true, y_pred) # Dice loss smooth = 1e-6 intersection = tf.reduce_sum(y_true * y_pred) union = tf.reduce_sum(y_true) + tf.reduce_sum(y_pred) dice_loss = 1.0 - 2.0 * (intersection + smooth) / (union + smooth) # Combine losses segmentation_loss = bce_loss + 1 * dice_loss return segmentation_loss model.compile(optimizer=Adam(lr=0.001), loss={'classification_output': 'categorical_crossentropy', 'segmentation_output': segmentation_loss}, # binary_crossentropy metrics={'classification_output': 'accuracy', 'segmentation_output': 'accuracy'}, loss_weights={'classification_output': 1, 'segmentation_output': 1}) # Define the callbacks checkpoint = ModelCheckpoint("multitask_best_weights.h5", monitor="val_classification_output_accuracy", save_best_only=True, mode="max", verbose=1) reduce_lr = ReduceLROnPlateau(monitor="val_classification_output_accuracy", factor=0.3, patience=2, min_delta=0.001, mode='auto', verbose=1) tensorboard = TensorBoard(log_dir='logs') history = model.fit(X_train, {'classification_output': y_train_class, 'segmentation_output': y_train_seg}, validation_data=(X_val, {'classification_output': y_val_class, 'segmentation_output': y_val_seg}), epochs=50, verbose=1, batch_size=16, callbacks=[checkpoint,reduce_lr,tensorboard]) # reduce_lr # Evaluate the model with tf.keras.utils.custom_object_scope({'segmentation_loss': segmentation_loss}): # Load the model best_model = load_model('multitask_best_weights.h5') # Evaluate the model on test data test_loss, test_class_loss, test_seg_loss, test_class_acc, test_seg_acc = best_model.evaluate(X_test, {'classification_output': y_test_class, 'segmentation_output': y_test_seg}) print("Test Classification Loss:", test_class_loss) print("Test Segmentation Loss:", test_seg_loss) print("Test Classification Accuracy:", test_class_acc) print("Test Segmentation Accuracy:", test_seg_acc) # Evaluate the model on validation data val_loss, val_class_loss, val_seg_loss, val_class_acc, val_seg_acc = best_model.evaluate(X_val, {'classification_output': y_val_class, 'segmentation_output': y_val_seg}) print("Validation Classification Loss:", val_class_loss) print("Validation Segmentation Loss:", val_seg_loss) print("Validation Classification Accuracy:", val_class_acc) print("Validation Segmentation Accuracy:", val_seg_acc) # Evaluate the model on training data train_loss, train_class_loss, train_seg_loss, train_class_acc, train_seg_acc = best_model.evaluate(X_train, {'classification_output': y_train_class, 'segmentation_output': y_train_seg}) print("Train Classification Loss:", train_class_loss) print("Train Segmentation Loss:", train_seg_loss) print("Train Classification Accuracy:", train_class_acc) print("Train Segmentation Accuracy:", train_seg_acc) # Plot performance classification_train_accuracy = history.history['classification_output_accuracy'] classification_train_loss = history.history['classification_output_loss'] classification_val_accuracy = history.history['val_classification_output_accuracy'] classification_val_loss = history.history['val_classification_output_loss'] segmentation_train_accuracy = history.history['segmentation_output_accuracy'] segmentation_train_loss = history.history['segmentation_output_loss'] segmentation_val_accuracy = history.history['val_segmentation_output_accuracy'] segmentation_val_loss = history.history['val_segmentation_output_loss'] # Plot classification accuracy plt.figure(figsize=(7, 3)) plt.plot(classification_train_accuracy, label='Training Accuracy') plt.plot(classification_val_accuracy, label='Validation Accuracy') plt.title('Classification Accuracy') plt.xlabel('Epochs') plt.ylabel('Accuracy') plt.legend() plt.show() # Plot segmentation accuracy plt.figure(figsize=(7, 3)) plt.plot(segmentation_train_accuracy, label='Training Accuracy') plt.plot(segmentation_val_accuracy, label='Validation Accuracy') plt.title('Segmentation Accuracy') plt.xlabel('Epochs') plt.ylabel('Accuracy') plt.legend() plt.show() # Plot classification loss plt.figure(figsize=(7, 3)) plt.plot(classification_train_loss,'b', label='Training Loss') plt.plot(classification_val_loss,'r', label='Validation Loss') plt.title('Classification Loss') plt.xlabel('Epochs') plt.ylabel('Loss') plt.legend() plt.show() # Plot segmentation loss plt.figure(figsize=(7, 3)) plt.plot(segmentation_train_loss,'b', label='Training Loss') plt.plot(segmentation_val_loss,'r', label='Validation Loss') plt.title('Segmentation Loss') plt.xlabel('Epochs') plt.ylabel('Loss') plt.legend() plt.show() " The above is the Python code with Keras to do multi-task learning with binary segmentation and classification using one mult-task learning model. Modify the code so that it can run 5 independent runs to train the model and take the average test accuracies of the 5 runs. Also, remove the save best model function.
6072a493ac2c09459cb339572aa5e7e5
{ "intermediate": 0.29371780157089233, "beginner": 0.34619608521461487, "expert": 0.3600860834121704 }
42,690
def preprocess_for_question_generation(examples): if examples["answer"] is None or examples["context"] is None: return None if not isinstance(examples["answer"], list) or not isinstance(examples["context"], list): return None if len(examples["answer"]) != len(examples["context"]): return None prepared_inputs = [] prepared_targets = [] for context, answer, answer_start in zip(examples["context"], examples["answer"], examples["answer_start"]): context = context answer = answer input_format = f"{answer} <SEP> {context}" target_format = f"{context} <EOS>" prepared_inputs.append(input_format) prepared_targets.append(target_format) tokenized_inputs = tokenizer( prepared_inputs, max_length=128, padding="max_length", truncation=True, return_tensors="pt" ) tokenized_targets = tokenizer( prepared_targets, max_length=64, padding="max_length", truncation=True, return_tensors="pt" ) tokenized_inputs["labels"] = tokenized_targets["input_ids"].clone() # Convert tensors to NumPy arrays tokenized_inputs_numpy = {} for key, value in tokenized_inputs.items(): tokenized_inputs_numpy[key] = value.numpy() return tokenized_inputs_numpy #return tokenized_inputs # Now apply the preprocessing function to your datasets tokenized_train_dataset = train_dataset.map(preprocess_for_question_generation, batched=True) tokenized_val_dataset = val_dataset.map(preprocess_for_question_generation, batched=True) tokenized_test_dataset = test_dataset.map(preprocess_for_question_generation, batched=True) my task is question generation data have question answer context and start answer can rewrite this function to be suitable for may task that well generate question based on answer ,return questin given an answer also my mdel ia arat5
948bba18fb10252ad4ce238626ccf08c
{ "intermediate": 0.549924373626709, "beginner": 0.1770898699760437, "expert": 0.2729857265949249 }
42,691
You are a Python expert who can provide clear, concise, high-quality code. " import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns import cv2 import random from keras.models import load_model import tensorflow as tf from tensorflow.keras.optimizers import Adam, SGD, RMSprop, AdamW, Adadelta, Adagrad, Adamax, Adafactor, Nadam, Ftrl from tensorflow.keras.preprocessing.image import ImageDataGenerator from tqdm import tqdm import os from sklearn.utils import shuffle from sklearn.model_selection import train_test_split from tensorflow.keras.models import Sequential, Model from tensorflow.keras.layers import GlobalAveragePooling2D, Dropout, Dense, Conv2D, MaxPooling2D, Flatten, Dropout, BatchNormalization, Activation, concatenate, Conv2DTranspose, Input, Reshape, UpSampling2D from tensorflow.python.ops.gen_nn_ops import FusedBatchNormGradV2 from tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau, TensorBoard, ModelCheckpoint from sklearn.metrics import classification_report, confusion_matrix import ipywidgets as widgets import io from PIL import Image from IPython.display import display, clear_output from warnings import filterwarnings from google.colab import drive drive.mount('/content/gdrive') # Set image size image_size = 224 # Define labels labels = ['bridge', 'excess', 'good'] # Create data arrays X_train = [] # Train data y_train_class = [] # Train classification label y_train_seg = [] # Train segmentation label X_val = [] # Validation data y_val_class = [] # Validation classification label y_val_seg = [] # Validation segmentation label X_test = [] # Test data y_test_class = [] # Test classification label y_test_seg = [] # Test segmentation label # Load training data for label in labels: folderPath = os.path.join('/content/gdrive/MyDrive/FYP/5 Dataset Ratio 20 20 60 TP 10 to 90/jit012_p0.1-0.9/jit0_p0.5/f_dip/train', label) for filename in tqdm(os.listdir(folderPath)): if filename.endswith('.jpg'): img = cv2.imread(os.path.join(folderPath, filename)) img = cv2.resize(img, (image_size, image_size)) X_train.append(img) y_train_class.append(label) seg_filename = filename.split('.')[0] + '.png' seg_img = cv2.imread(os.path.join(folderPath, seg_filename), 0) seg_img = cv2.resize(seg_img, (image_size, image_size)) seg_img = np.where(seg_img > 0, 1, 0) # Convert segmentation mask to binary y_train_seg.append(seg_img) # Load validation data for label in labels: folderPath = os.path.join('/content/gdrive/MyDrive/FYP/5 Dataset Ratio 20 20 60 TP 10 to 90/jit012_p0.1-0.9/jit0_p0.5/f_dip/val', label) for filename in tqdm(os.listdir(folderPath)): if filename.endswith('.jpg'): img = cv2.imread(os.path.join(folderPath, filename)) img = cv2.resize(img, (image_size, image_size)) X_val.append(img) y_val_class.append(label) seg_filename = filename.split('.')[0] + '.png' seg_img = cv2.imread(os.path.join(folderPath, seg_filename), 0) seg_img = cv2.resize(seg_img, (image_size, image_size)) seg_img = np.where(seg_img > 0, 1, 0) # Convert segmentation mask to binary y_val_seg.append(seg_img) # Load test data for label in labels: folderPath = os.path.join('/content/gdrive/MyDrive/FYP/5 Dataset Ratio 20 20 60 TP 10 to 90/jit012_p0.1-0.9/jit0_p0.5/f_dip/test', label) for filename in tqdm(os.listdir(folderPath)): if filename.endswith('.jpg'): img = cv2.imread(os.path.join(folderPath, filename)) img = cv2.resize(img, (image_size, image_size)) X_test.append(img) y_test_class.append(label) seg_filename = filename.split('.')[0] + '.png' seg_img = cv2.imread(os.path.join(folderPath, seg_filename), 0) seg_img = cv2.resize(seg_img, (image_size, image_size)) seg_img = np.where(seg_img > 0, 1, 0) # Convert segmentation mask to binary y_test_seg.append(seg_img) # Convert to numpy arrays X_train = np.array(X_train) y_train_class = np.array(y_train_class) y_train_seg = np.array(y_train_seg) X_val = np.array(X_val) y_val_class = np.array(y_val_class) y_val_seg = np.array(y_val_seg) X_test = np.array(X_test) y_test_class = np.array(y_test_class) y_test_seg = np.array(y_test_seg) # Shuffle the data X_train, y_train_class, y_train_seg = shuffle(X_train, y_train_class, y_train_seg, random_state=101) # One Hot Encoding for classification labels y_train_class_new = [] for label in y_train_class: y_train_class_new.append(labels.index(label)) y_train_class = y_train_class_new y_train_class = tf.keras.utils.to_categorical(y_train_class) y_val_class_new = [] for label in y_val_class: y_val_class_new.append(labels.index(label)) y_val_class = y_val_class_new y_val_class = tf.keras.utils.to_categorical(y_val_class) y_test_class_new = [] for label in y_test_class: y_test_class_new.append(labels.index(label)) y_test_class = y_test_class_new y_test_class = tf.keras.utils.to_categorical(y_test_class) # Print the counts print("Number of train images:", len(X_train)) print("Number of train binary masks:", len(y_train_seg)) print("Number of validation images:", len(X_val)) print("Number of validation binary masks:", len(y_val_seg)) print("Number of test images:", len(X_test)) print("Number of test binary masks:", len(y_test_seg)) # Define U-Net model input_shape = (image_size, image_size, 3) num_classes = len(labels) inputs = Input(input_shape) num_filter = 32 # 16/32 best, 8: best classification but no segment # Encoder (Done) conv1 = Conv2D(num_filter * 1, 3, activation='linear', padding='same', strides=1)(inputs) bn1 = BatchNormalization()(conv1) relu1 = Activation('relu')(bn1) conv2 = Conv2D(num_filter * 1, 3, activation='linear', padding='same', strides=1)(relu1) bn2 = BatchNormalization()(conv2) relu2 = Activation('relu')(bn2) down1 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu2) conv3 = Conv2D(num_filter * 2, 3, activation='linear', padding='same', strides=1)(down1) bn3 = BatchNormalization()(conv3) relu3 = Activation('relu')(bn3) conv4 = Conv2D(num_filter * 2, 3, activation='linear', padding='same', strides=1)(relu3) bn4 = BatchNormalization()(conv4) relu4 = Activation('relu')(bn4) down2 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu4) conv5 = Conv2D(num_filter * 4, 3, activation='linear', padding='same', strides=1)(down2) bn5 = BatchNormalization()(conv5) relu5 = Activation('relu')(bn5) conv6 = Conv2D(num_filter * 4, 3, activation='linear', padding='same', strides=1)(relu5) bn6 = BatchNormalization()(conv6) relu6 = Activation('relu')(bn6) down3 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu6) conv7 = Conv2D(num_filter * 8, 3, activation='linear', padding='same', strides=1)(down3) bn7 = BatchNormalization()(conv7) relu7 = Activation('relu')(bn7) conv8 = Conv2D(num_filter * 8, 3, activation='linear', padding='same', strides=1)(relu7) bn8 = BatchNormalization()(conv8) relu8 = Activation('relu')(bn8) # Middle down4 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu8) conv9 = Conv2D(num_filter * 16, 3, activation='linear', padding='same', strides=1)(down4) bn9 = BatchNormalization()(conv9) relu9 = Activation('relu')(bn9) conv10 = Conv2D(num_filter * 16, 3, activation='linear', padding='same', strides=1)(relu9) bn10 = BatchNormalization()(conv10) relu10 = Activation('relu')(bn10) up1 = UpSampling2D(size=(2, 2), interpolation='bilinear')(relu10) # Decoder (Done) concat1 = concatenate([up1, relu8], axis=-1) #, axis=3 conv11 = Conv2D(num_filter * 8, 3, activation='linear', padding='same', strides=1)(concat1) bn11 = BatchNormalization()(conv11) relu11 = Activation('relu')(bn11) conv12 = Conv2D(num_filter * 8, 3, activation='linear', padding='same', strides=1)(relu11) bn12 = BatchNormalization()(conv12) relu12 = Activation('relu')(bn12) up2 = UpSampling2D(size=(2, 2), interpolation='bilinear')(relu12) concat2 = concatenate([up2, relu6], axis=-1) #, axis=3 conv13 = Conv2D(num_filter * 4, 3, activation='linear', padding='same', strides=1)(concat2) bn13 = BatchNormalization()(conv13) relu13 = Activation('relu')(bn13) conv14 = Conv2D(num_filter * 4, 3, activation='linear', padding='same', strides=1)(relu13) bn14 = BatchNormalization()(conv14) relu14 = Activation('relu')(bn14) up3 = UpSampling2D(size=(2, 2), interpolation='bilinear')(relu14) concat3 = concatenate([up3, relu4], axis=-1) #, axis=3 conv15 = Conv2D(num_filter * 2, 3, activation='linear', padding='same', strides=1)(concat3) bn15 = BatchNormalization()(conv15) relu15 = Activation('relu')(bn15) conv16 = Conv2D(num_filter * 2, 3, activation='linear', padding='same', strides=1)(relu15) bn16 = BatchNormalization()(conv16) relu16 = Activation('relu')(bn16) up4 = UpSampling2D(size=(2, 2), interpolation='bilinear')(relu16) concat4 = concatenate([up4, relu2], axis=-1) #, axis=3 conv17 = Conv2D(num_filter * 1, 3, activation='linear', padding='same', strides=1)(concat4) bn17 = BatchNormalization()(conv17) relu17 = Activation('relu')(bn17) conv18 = Conv2D(num_filter * 1, 3, activation='linear', padding='same', strides=1)(relu17) bn18 = BatchNormalization()(conv18) relu18 = Activation('relu')(bn18) # Segmentation branch segmentation_output = Conv2D(1, 1, activation='sigmoid', name='segmentation_output')(relu18) #original # Classification branch (Not done) gap1 = GlobalAveragePooling2D()(relu8) gap2 = GlobalAveragePooling2D()(relu10) gap3 = GlobalAveragePooling2D()(relu12) conv20 = Conv2D(16, 3, activation='linear', padding='same', strides=1)(segmentation_output) bn20 = BatchNormalization()(conv20) relu20 = Activation('relu')(bn20) down5 = MaxPooling2D(pool_size=(4, 4), strides=4)(relu20) conv21 = Conv2D(32, 3, activation='linear', padding='same', strides=1)(down5) bn21 = BatchNormalization()(conv21) relu21 = Activation('relu')(bn21) down6 = MaxPooling2D(pool_size=(4, 4), strides=4)(relu21) conv22 = Conv2D(64, 3, activation='linear', padding='same', strides=1)(down6) bn22 = BatchNormalization()(conv22) relu22 = Activation('relu')(bn22) down7 = MaxPooling2D(pool_size=(4, 4), strides=4)(relu22) flatten1 = Flatten()(down7) concat5 = concatenate([gap1, gap2, gap3, flatten1], axis = -1) # axis = -1 # FC layers fc1 = Dense(1024, activation='relu')(concat5) # 512, 256 match with num_filter = 8 dropout1 = Dropout(0.5)(fc1) fc2 = Dense(1024, activation='relu')(dropout1) # 512,256 dropout2 = Dropout(0.5)(fc2) classification_output = Dense(num_classes, activation='softmax', name='classification_output')(dropout2) # Define the model model = Model(inputs=inputs, outputs=[classification_output, segmentation_output]) model.summary() # Compile model def segmentation_loss(y_true, y_pred): y_true = tf.cast(y_true, tf.float32) y_pred = tf.cast(y_pred, tf.float32) # Binary cross-entropy loss bce_loss = tf.keras.losses.binary_crossentropy(y_true, y_pred) # Dice loss smooth = 1e-6 intersection = tf.reduce_sum(y_true * y_pred) union = tf.reduce_sum(y_true) + tf.reduce_sum(y_pred) dice_loss = 1.0 - 2.0 * (intersection + smooth) / (union + smooth) # Combine losses segmentation_loss = bce_loss + 1 * dice_loss return segmentation_loss model.compile(optimizer=Adam(lr=0.001), loss={'classification_output': 'categorical_crossentropy', 'segmentation_output': segmentation_loss}, # binary_crossentropy metrics={'classification_output': 'accuracy', 'segmentation_output': 'accuracy'}, loss_weights={'classification_output': 1, 'segmentation_output': 1}) # Define the callbacks checkpoint = ModelCheckpoint("multitask_best_weights.h5", monitor="val_classification_output_accuracy", save_best_only=True, mode="max", verbose=1) reduce_lr = ReduceLROnPlateau(monitor="val_classification_output_accuracy", factor=0.3, patience=2, min_delta=0.001, mode='auto', verbose=1) tensorboard = TensorBoard(log_dir='logs') history = model.fit(X_train, {'classification_output': y_train_class, 'segmentation_output': y_train_seg}, validation_data=(X_val, {'classification_output': y_val_class, 'segmentation_output': y_val_seg}), epochs=50, verbose=1, batch_size=16, callbacks=[checkpoint,reduce_lr,tensorboard]) # reduce_lr # Evaluate the model with tf.keras.utils.custom_object_scope({'segmentation_loss': segmentation_loss}): # Load the model best_model = load_model('multitask_best_weights.h5') # Evaluate the model on test data test_loss, test_class_loss, test_seg_loss, test_class_acc, test_seg_acc = best_model.evaluate(X_test, {'classification_output': y_test_class, 'segmentation_output': y_test_seg}) print("Test Classification Loss:", test_class_loss) print("Test Segmentation Loss:", test_seg_loss) print("Test Classification Accuracy:", test_class_acc) print("Test Segmentation Accuracy:", test_seg_acc) # Evaluate the model on validation data val_loss, val_class_loss, val_seg_loss, val_class_acc, val_seg_acc = best_model.evaluate(X_val, {'classification_output': y_val_class, 'segmentation_output': y_val_seg}) print("Validation Classification Loss:", val_class_loss) print("Validation Segmentation Loss:", val_seg_loss) print("Validation Classification Accuracy:", val_class_acc) print("Validation Segmentation Accuracy:", val_seg_acc) # Evaluate the model on training data train_loss, train_class_loss, train_seg_loss, train_class_acc, train_seg_acc = best_model.evaluate(X_train, {'classification_output': y_train_class, 'segmentation_output': y_train_seg}) print("Train Classification Loss:", train_class_loss) print("Train Segmentation Loss:", train_seg_loss) print("Train Classification Accuracy:", train_class_acc) print("Train Segmentation Accuracy:", train_seg_acc) # Plot performance classification_train_accuracy = history.history['classification_output_accuracy'] classification_train_loss = history.history['classification_output_loss'] classification_val_accuracy = history.history['val_classification_output_accuracy'] classification_val_loss = history.history['val_classification_output_loss'] segmentation_train_accuracy = history.history['segmentation_output_accuracy'] segmentation_train_loss = history.history['segmentation_output_loss'] segmentation_val_accuracy = history.history['val_segmentation_output_accuracy'] segmentation_val_loss = history.history['val_segmentation_output_loss'] # Plot classification accuracy plt.figure(figsize=(7, 3)) plt.plot(classification_train_accuracy, label='Training Accuracy') plt.plot(classification_val_accuracy, label='Validation Accuracy') plt.title('Classification Accuracy') plt.xlabel('Epochs') plt.ylabel('Accuracy') plt.legend() plt.show() # Plot segmentation accuracy plt.figure(figsize=(7, 3)) plt.plot(segmentation_train_accuracy, label='Training Accuracy') plt.plot(segmentation_val_accuracy, label='Validation Accuracy') plt.title('Segmentation Accuracy') plt.xlabel('Epochs') plt.ylabel('Accuracy') plt.legend() plt.show() # Plot classification loss plt.figure(figsize=(7, 3)) plt.plot(classification_train_loss,'b', label='Training Loss') plt.plot(classification_val_loss,'r', label='Validation Loss') plt.title('Classification Loss') plt.xlabel('Epochs') plt.ylabel('Loss') plt.legend() plt.show() # Plot segmentation loss plt.figure(figsize=(7, 3)) plt.plot(segmentation_train_loss,'b', label='Training Loss') plt.plot(segmentation_val_loss,'r', label='Validation Loss') plt.title('Segmentation Loss') plt.xlabel('Epochs') plt.ylabel('Loss') plt.legend() plt.show() " The above is the Python code with Keras to do multi-task learning with binary segmentation and classification using one mult-task learning model. Modify the code so that it can run 5 independent runs to train the model and take the average test accuracies of the 5 runs. Also, remove the save best model function.
35daa0973ed88ba9deabb0a5ce6ea5d9
{ "intermediate": 0.29371780157089233, "beginner": 0.34619608521461487, "expert": 0.3600860834121704 }
42,692
Sometimes my Linux installation does the following: When I turn the screen on, it's just black with no signal REISUB doesn't work Need to close it from the PSU How do I debug this after rebooting? What log files should I check? NixOS if it matters.
5f43cbc5dcd9c6ce3010f241b02cbd54
{ "intermediate": 0.6381611227989197, "beginner": 0.21759231388568878, "expert": 0.14424654841423035 }
42,693
Use this code to transcribe, diarize and merge the output - # Prediction interface for Cog ⚙️ from typing import Any, List import base64 import datetime import subprocess import os import requests import time import torch import re from cog import BasePredictor, BaseModel, Input, File, Path from faster_whisper import WhisperModel from pyannote.audio import Pipeline class Output(BaseModel): segments: list language: str = None num_speakers: int = None class Predictor(BasePredictor): def setup(self): """Load the model into memory to make running multiple predictions efficient""" model_name = "large-v3" self.model = WhisperModel( model_name, device="cuda" if torch.cuda.is_available() else "cpu", compute_type="float16", ) self.diarization_model = Pipeline.from_pretrained( "pyannote/speaker-diarization-3.1", use_auth_token="YOUR HF TOKEN HERE", ).to(torch.device("cuda")) def predict( self, file_string: str = Input( description="Either provide: Base64 encoded audio file,", default=None ), file_url: str = Input( description="Or provide: A direct audio file URL", default=None ), file: Path = Input(description="Or an audio file", default=None), group_segments: bool = Input( description="Group segments of same speaker shorter apart than 2 seconds", default=True, ), transcript_output_format: str = Input( description="Specify the format of the transcript output: individual words with timestamps, full text of segments, or a combination of both.", default="both", choices=["words_only", "segments_only", "both"], ), num_speakers: int = Input( description="Number of speakers, leave empty to autodetect.", ge=1, le=50, default=None, ), language: str = Input( description="Language of the spoken words as a language code like 'en'. Leave empty to auto detect language.", default=None, ), prompt: str = Input( description="Vocabulary: provide names, acronyms and loanwords in a list. Use punctuation for best accuracy.", default=None, ), # word_timestamps: bool = Input(description="Return word timestamps", default=True), needs to be implemented offset_seconds: int = Input( description="Offset in seconds, used for chunked inputs", default=0, ge=0 ), ) -> Output: """Run a single prediction on the model""" # Check if either filestring, filepath or file is provided, but only 1 of them """ if sum([file_string is not None, file_url is not None, file is not None]) != 1: raise RuntimeError("Provide either file_string, file or file_url") """ try: # Generate a temporary filename temp_wav_filename = f"temp-{time.time_ns()}.wav" if file is not None: subprocess.run( [ "ffmpeg", "-i", file, "-ar", "16000", "-ac", "1", "-c:a", "pcm_s16le", temp_wav_filename, ] ) elif file_url is not None: response = requests.get(file_url) temp_audio_filename = f"temp-{time.time_ns()}.audio" with open(temp_audio_filename, "wb") as file: file.write(response.content) subprocess.run( [ "ffmpeg", "-i", temp_audio_filename, "-ar", "16000", "-ac", "1", "-c:a", "pcm_s16le", temp_wav_filename, ] ) if os.path.exists(temp_audio_filename): os.remove(temp_audio_filename) elif file_string is not None: audio_data = base64.b64decode( file_string.split(",")[1] if "," in file_string else file_string ) temp_audio_filename = f"temp-{time.time_ns()}.audio" with open(temp_audio_filename, "wb") as f: f.write(audio_data) subprocess.run( [ "ffmpeg", "-i", temp_audio_filename, "-ar", "16000", "-ac", "1", "-c:a", "pcm_s16le", temp_wav_filename, ] ) if os.path.exists(temp_audio_filename): os.remove(temp_audio_filename) segments, detected_num_speakers, detected_language = self.speech_to_text( temp_wav_filename, num_speakers, prompt, offset_seconds, group_segments, language, word_timestamps=True, transcript_output_format=transcript_output_format, ) print(f"done with inference") # Return the results as a JSON object return Output( segments=segments, language=detected_language, num_speakers=detected_num_speakers, ) except Exception as e: raise RuntimeError("Error Running inference with local model", e) finally: # Clean up if os.path.exists(temp_wav_filename): os.remove(temp_wav_filename) def convert_time(self, secs, offset_seconds=0): return datetime.timedelta(seconds=(round(secs) + offset_seconds)) def speech_to_text( self, audio_file_wav, num_speakers=None, prompt="", offset_seconds=0, group_segments=True, language=None, word_timestamps=True, transcript_output_format="both", ): time_start = time.time() # Transcribe audio print("Starting transcribing") options = dict( vad_filter=True, vad_parameters=dict(min_silence_duration_ms=1000), initial_prompt=prompt, word_timestamps=word_timestamps, language=language, ) segments, transcript_info = self.model.transcribe(audio_file_wav, **options) segments = list(segments) segments = [ { "avg_logprob": s.avg_logprob, "start": float(s.start + offset_seconds), "end": float(s.end + offset_seconds), "text": s.text, "words": [ { "start": float(w.start + offset_seconds), "end": float(w.end + offset_seconds), "word": w.word, "probability": w.probability, } for w in s.words ], } for s in segments ] time_transcribing_end = time.time() print( f"Finished with transcribing, took {time_transcribing_end - time_start:.5} seconds" ) print("Starting diarization") diarization = self.diarization_model(audio_file_wav, num_speakers=num_speakers) time_diraization_end = time.time() print( f"Finished with diarization, took {time_diraization_end - time_transcribing_end:.5} seconds" ) print("Starting merging") # Initialize variables to keep track of the current position in both lists margin = 0.1 # 0.1 seconds margin # Initialize an empty list to hold the final segments with speaker info final_segments = [] diarization_list = list(diarization.itertracks(yield_label=True)) unique_speakers = { speaker for _, _, speaker in diarization.itertracks(yield_label=True) } detected_num_speakers = len(unique_speakers) speaker_idx = 0 n_speakers = len(diarization_list) # Iterate over each segment for segment in segments: segment_start = segment["start"] + offset_seconds segment_end = segment["end"] + offset_seconds segment_text = [] segment_words = [] # Iterate over each word in the segment for word in segment["words"]: word_start = word["start"] + offset_seconds - margin word_end = word["end"] + offset_seconds + margin while speaker_idx < n_speakers: turn, _, speaker = diarization_list[speaker_idx] if turn.start <= word_end and turn.end >= word_start: # Add word without modifications segment_text.append(word["word"]) # Strip here for individual word storage word["word"] = word["word"].strip() segment_words.append(word) if turn.end <= word_end: speaker_idx += 1 break elif turn.end < word_start: speaker_idx += 1 else: break if segment_text: combined_text = "".join(segment_text) cleaned_text = re.sub(" ", " ", combined_text).strip() new_segment = { "avg_logprob": segment["avg_logprob"], "start": segment_start - offset_seconds, "end": segment_end - offset_seconds, "speaker": speaker, "text": cleaned_text, "words": segment_words, } final_segments.append(new_segment) time_merging_end = time.time() print( f"Finished with merging, took {time_merging_end - time_diraization_end:.5} seconds" ) print("Starting cleaning") segments = final_segments # Make output output = [] # Initialize an empty list for the output # Initialize the first group with the first segment current_group = { "start": str(segments[0]["start"]), "end": str(segments[0]["end"]), "speaker": segments[0]["speaker"], "avg_logprob": segments[0]["avg_logprob"], } if transcript_output_format in ("segments_only", "both"): current_group["text"] = segments[0]["text"] if transcript_output_format in ("words_only", "both"): current_group["words"] = segments[0]["words"] for i in range(1, len(segments)): # Calculate time gap between consecutive segments time_gap = segments[i]["start"] - segments[i - 1]["end"] # If the current segment's speaker is the same as the previous segment's speaker, # and the time gap is less than or equal to 2 seconds, group them if segments[i]["speaker"] == segments[i - 1]["speaker"] and time_gap <= 2 and group_segments: current_group["end"] = str(segments[i]["end"]) if transcript_output_format in ("segments_only", "both"): current_group["text"] += " " + segments[i]["text"] if transcript_output_format in ("words_only", "both"): current_group.setdefault("words", []).extend(segments[i]["words"]) else: # Add the current_group to the output list output.append(current_group) # Start a new group with the current segment current_group = { "start": str(segments[i]["start"]), "end": str(segments[i]["end"]), "speaker": segments[i]["speaker"], "avg_logprob": segments[i]["avg_logprob"], } if transcript_output_format in ("segments_only", "both"): current_group["text"] = segments[i]["text"] if transcript_output_format in ("words_only", "both"): current_group["words"] = segments[i]["words"] # Add the last group to the output list output.append(current_group) time_cleaning_end = time.time() print( f"Finished with cleaning, took {time_cleaning_end - time_merging_end:.5} seconds" ) time_end = time.time() time_diff = time_end - time_start system_info = f"""Processing time: {time_diff:.5} seconds""" print(system_info) return output, detected_num_speakers, transcript_info.language
f2ad6ce5b41e2c3c788877f5674a3057
{ "intermediate": 0.4280904531478882, "beginner": 0.35736560821533203, "expert": 0.21454398334026337 }
42,694
You are a Python expert who can provide clear, concise, high-quality code. " import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns import cv2 import random import tensorflow as tf import tkinter as tk from tkinter import filedialog from PIL import ImageTk, Image from ipywidgets import interact, interactive, fixed, interact_manual import ipywidgets as widgets from IPython.display import display, clear_output from tensorflow.keras.preprocessing import image from tensorflow.keras.optimizers import Adam, SGD, RMSprop, AdamW, Adadelta, Adagrad, Adamax, Adafactor, Nadam, Ftrl from tensorflow.keras.preprocessing.image import ImageDataGenerator from tqdm import tqdm import os from sklearn.utils import shuffle from sklearn.preprocessing import LabelEncoder from sklearn.model_selection import train_test_split from tensorflow.keras.models import Sequential, Model, load_model from tensorflow.keras.layers import ( GlobalAveragePooling2D, Dropout, Dense, Conv2D, MaxPooling2D, Flatten, Dropout, BatchNormalization, Activation, concatenate, Conv2DTranspose, Input, Reshape, UpSampling2D, ) from tensorflow.keras.applications import ( EfficientNetV2B0, EfficientNetV2B1, EfficientNetV2B2, EfficientNetV2B3, EfficientNetV2L, EfficientNetV2M, EfficientNetV2S, ) from tensorflow.keras.applications import Xception from tensorflow.keras.applications import VGG16, VGG19 from tensorflow.keras.applications import ResNet50, ResNet101, ResNet152, ResNetRS50, ResNetRS101 from tensorflow.keras.applications import InceptionResNetV2, ConvNeXtXLarge, ConvNeXtBase, DenseNet121, MobileNetV2, NASNetLarge, NASNetMobile from tensorflow.keras.utils import to_categorical from tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau, TensorBoard, ModelCheckpoint from sklearn.metrics import classification_report, confusion_matrix import ipywidgets as widgets import io from PIL import Image from IPython.display import display, clear_output from warnings import filterwarnings from google.colab import drive drive.mount("/content/gdrive") def load_data(data_folders): X_data = [] # Combined data y_class_labels = [] # Combined classification labels y_seg_labels = [] # Combined segmentation labels for folderPath in data_folders: for label in labels: label_folder_path = os.path.join(folderPath, label) for filename in tqdm(os.listdir(label_folder_path)): if filename.endswith(".jpg"): img = cv2.imread(os.path.join(label_folder_path, filename)) img = cv2.resize(img, (image_size, image_size)) X_data.append(img) y_class_labels.append(label) seg_filename = filename.split(".")[0] + ".png" seg_img = cv2.imread(os.path.join(label_folder_path, seg_filename), 0) seg_img = cv2.resize(seg_img, (image_size, image_size)) seg_img = np.where(seg_img > 0, 1, 0) # Convert segmentation mask to binary y_seg_labels.append(seg_img) X_data = np.array(X_data) y_class_labels = np.array(y_class_labels) y_seg_labels = np.array(y_seg_labels) X_data, y_class_labels, y_seg_labels = shuffle(X_data, y_class_labels, y_seg_labels, random_state=101) return X_data, y_class_labels, y_seg_labels def split_data(X_data, y_class_labels, y_seg_labels, class_data_counts): X_train = [] y_train_class = [] y_train_seg = [] X_val = [] y_val_class = [] y_val_seg = [] X_test = [] y_test_class = [] y_test_seg = [] for label, count in class_data_counts.items(): label_indices = np.where(y_class_labels == label)[0] class_X_data = X_data[label_indices] class_y_class_labels = y_class_labels[label_indices] class_y_seg_labels = y_seg_labels[label_indices] train_count = count[0] val_count = count[1] test_count = count[2] class_X_train = class_X_data[:train_count] class_y_train_class = class_y_class_labels[:train_count] class_y_train_seg = class_y_seg_labels[:train_count] class_X_val = class_X_data[train_count: train_count + val_count] class_y_val_class = class_y_class_labels[train_count: train_count + val_count] class_y_val_seg = class_y_seg_labels[train_count: train_count + val_count] class_X_test = class_X_data[train_count + val_count: train_count + val_count + test_count] class_y_test_class = class_y_class_labels[train_count + val_count: train_count + val_count + test_count] class_y_test_seg = class_y_seg_labels[train_count + val_count: train_count + val_count + test_count] X_train.extend(class_X_train) y_train_class.extend(class_y_train_class) y_train_seg.extend(class_y_train_seg) X_val.extend(class_X_val) y_val_class.extend(class_y_val_class) y_val_seg.extend(class_y_val_seg) X_test.extend(class_X_test) y_test_class.extend(class_y_test_class) y_test_seg.extend(class_y_test_seg) # Convert class labels to categorical label_encoder = LabelEncoder() y_train_class_encoded = label_encoder.fit_transform(y_train_class) y_train_class_categorical = to_categorical(y_train_class_encoded) y_val_class_encoded = label_encoder.transform(y_val_class) y_val_class_categorical = to_categorical(y_val_class_encoded) y_test_class_encoded = label_encoder.transform(y_test_class) y_test_class_categorical = to_categorical(y_test_class_encoded) return ( np.array(X_train), np.array(y_train_class_categorical), np.array(y_train_seg), np.array(X_val), np.array(y_val_class_categorical), np.array(y_val_seg), np.array(X_test), np.array(y_test_class_categorical), np.array(y_test_seg), ) def count_labels(y_class_categorical, label_encoder): # Convert one-hot encoded labels back to label encoded y_class_labels = np.argmax(y_class_categorical, axis=1) # Convert label encoded labels back to original class names y_class_names = label_encoder.inverse_transform(y_class_labels) unique, counts = np.unique(y_class_names, return_counts=True) return dict(zip(unique, counts)) def build_model(input_shape, num_classes): num_filter = 32 # 16/32 best, 8: best classification but no segment # Encoder (Done) inputs = Input(input_shape) conv1 = Conv2D(num_filter * 1, 3, activation="linear", padding="same", strides=1)(inputs) bn1 = BatchNormalization()(conv1) relu1 = Activation("relu")(bn1) conv2 = Conv2D(num_filter * 1, 3, activation="linear", padding="same", strides=1)(relu1) bn2 = BatchNormalization()(conv2) relu2 = Activation("relu")(bn2) down1 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu2) conv3 = Conv2D(num_filter * 2, 3, activation="linear", padding="same", strides=1)(down1) bn3 = BatchNormalization()(conv3) relu3 = Activation("relu")(bn3) conv4 = Conv2D(num_filter * 2, 3, activation="linear", padding="same", strides=1)(relu3) bn4 = BatchNormalization()(conv4) relu4 = Activation("relu")(bn4) down2 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu4) conv5 = Conv2D(num_filter * 4, 3, activation="linear", padding="same", strides=1)(down2) bn5 = BatchNormalization()(conv5) relu5 = Activation("relu")(bn5) conv6 = Conv2D(num_filter * 4, 3, activation="linear", padding="same", strides=1)(relu5) bn6 = BatchNormalization()(conv6) relu6 = Activation("relu")(bn6) down3 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu6) conv7 = Conv2D(num_filter * 8, 3, activation="linear", padding="same", strides=1)(down3) bn7 = BatchNormalization()(conv7) relu7 = Activation("relu")(bn7) conv8 = Conv2D(num_filter * 8, 3, activation="linear", padding="same", strides=1)(relu7) bn8 = BatchNormalization()(conv8) relu8 = Activation("relu")(bn8) # Middle down4 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu8) conv9 = Conv2D(num_filter * 16, 3, activation="linear", padding="same", strides=1)(down4) bn9 = BatchNormalization()(conv9) relu9 = Activation("relu")(bn9) conv10 = Conv2D(num_filter * 16, 3, activation="linear", padding="same", strides=1)(relu9) bn10 = BatchNormalization()(conv10) relu10 = Activation("relu")(bn10) up1 = UpSampling2D(size=(2, 2), interpolation="bilinear")(relu10) # Decoder (Done) concat1 = concatenate([up1, relu8], axis=-1) # , axis=3 conv11 = Conv2D(num_filter * 8, 3, activation="linear", padding="same", strides=1)(concat1) bn11 = BatchNormalization()(conv11) relu11 = Activation("relu")(bn11) conv12 = Conv2D(num_filter * 8, 3, activation="linear", padding="same", strides=1)(relu11) bn12 = BatchNormalization()(conv12) relu12 = Activation("relu")(bn12) up2 = UpSampling2D(size=(2, 2), interpolation="bilinear")(relu12) concat2 = concatenate([up2, relu6], axis=-1) # , axis=3 conv13 = Conv2D(num_filter * 4, 3, activation="linear", padding="same", strides=1)(concat2) bn13 = BatchNormalization()(conv13) relu13 = Activation("relu")(bn13) conv14 = Conv2D(num_filter * 4, 3, activation="linear", padding="same", strides=1)(relu13) bn14 = BatchNormalization()(conv14) relu14 = Activation("relu")(bn14) up3 = UpSampling2D(size=(2, 2), interpolation="bilinear")(relu14) concat3 = concatenate([up3, relu4], axis=-1) # , axis=3 conv15 = Conv2D(num_filter * 2, 3, activation="linear", padding="same", strides=1)(concat3) bn15 = BatchNormalization()(conv15) relu15 = Activation("relu")(bn15) conv16 = Conv2D(num_filter * 2, 3, activation="linear", padding="same", strides=1)(relu15) bn16 = BatchNormalization()(conv16) relu16 = Activation("relu")(bn16) up4 = UpSampling2D(size=(2, 2), interpolation="bilinear")(relu16) concat4 = concatenate([up4, relu2], axis=-1) # , axis=3 conv17 = Conv2D(num_filter * 1, 3, activation="linear", padding="same", strides=1)(concat4) bn17 = BatchNormalization()(conv17) relu17 = Activation("relu")(bn17) conv18 = Conv2D(num_filter * 1, 3, activation="linear", padding="same", strides=1)(relu17) bn18 = BatchNormalization()(conv18) relu18 = Activation("relu")(bn18) # Segmentation branch segmentation_output = Conv2D(1, 1, activation="sigmoid", name="segmentation_output")(relu18) # original # Classification branch (Not done) gap1 = GlobalAveragePooling2D()(relu8) gap2 = GlobalAveragePooling2D()(relu10) gap3 = GlobalAveragePooling2D()(relu12) conv20 = Conv2D(16, 3, activation="linear", padding="same", strides=1)(segmentation_output) bn20 = BatchNormalization()(conv20) relu20 = Activation("relu")(bn20) down5 = MaxPooling2D(pool_size=(4, 4), strides=4)(relu20) conv21 = Conv2D(32, 3, activation="linear", padding="same", strides=1)(down5) bn21 = BatchNormalization()(conv21) relu21 = Activation("relu")(bn21) down6 = MaxPooling2D(pool_size=(4, 4), strides=4)(relu21) conv22 = Conv2D(64, 3, activation="linear", padding="same", strides=1)(down6) bn22 = BatchNormalization()(conv22) relu22 = Activation("relu")(bn22) down7 = MaxPooling2D(pool_size=(4, 4), strides=4)(relu22) flatten1 = Flatten()(down7) concat5 = concatenate([gap1, gap2, gap3, flatten1], axis=-1) # FC layers fc1 = Dense(1024, activation="relu")(concat5) dropout1 = Dropout(0.5)(fc1) fc2 = Dense(1024, activation="relu")(dropout1) dropout2 = Dropout(0.5)(fc2) classification_output = Dense(num_classes, activation="softmax", name="classification_output")(dropout2) # Define the model model = Model(inputs=inputs, outputs=[classification_output, segmentation_output]) return model def segmentation_loss(y_true, y_pred): y_true = tf.cast(y_true, tf.float32) y_pred = tf.cast(y_pred, tf.float32) bce_loss = tf.keras.losses.binary_crossentropy(y_true, y_pred) smooth = 1e-5 intersection = tf.reduce_sum(y_true * y_pred) union = tf.reduce_sum(y_true) + tf.reduce_sum(y_pred) dice_loss = 1.0 - 2.0 * (intersection + smooth) / (union + smooth) segmentation_loss = bce_loss + 1 * dice_loss return segmentation_loss def train_model(model, X_train, y_train_class, y_train_seg, X_val, y_val_class, y_val_seg, batch_size, epochs): checkpoint = ModelCheckpoint( "multitask_best_weights.h5", monitor="val_classification_output_accuracy", save_best_only=True, mode="max", verbose=1,) reduce_lr = ReduceLROnPlateau( monitor="val_classification_output_accuracy", factor=0.3, patience=2, min_delta=0.001, mode="auto", verbose=1,) tensorboard = TensorBoard(log_dir="logs") model.compile( optimizer=Adam(lr=0.001), loss={"classification_output": "categorical_crossentropy", "segmentation_output": segmentation_loss}, metrics={"classification_output": "accuracy", "segmentation_output": "accuracy"}, loss_weights={"classification_output": 1, "segmentation_output": 1},) history = model.fit( X_train, {"classification_output": y_train_class, "segmentation_output": y_train_seg}, validation_data=(X_val, {"classification_output": y_val_class, "segmentation_output": y_val_seg}), epochs=epochs, verbose=1, batch_size=batch_size, callbacks=[checkpoint, reduce_lr, tensorboard],) return history def evaluate_model(model, X_test, y_test_class, y_test_seg): with tf.keras.utils.custom_object_scope({"segmentation_loss": segmentation_loss}): # Load the best model weights best_model = load_model("multitask_best_weights.h5") # Evaluate the model on test data test_loss, test_class_loss, test_seg_loss, test_class_acc, test_seg_acc = best_model.evaluate( X_test, {"classification_output": y_test_class, "segmentation_output": y_test_seg}) print("Test Classification Loss:", test_class_loss) print("Test Segmentation Loss:", test_seg_loss) print("Test Classification Accuracy:", test_class_acc) print("Test Segmentation Accuracy:", test_seg_acc) # Evaluate the model on validation data val_loss, val_class_loss, val_seg_loss, val_class_acc, val_seg_acc = best_model.evaluate( X_val, {'classification_output': y_val_class, 'segmentation_output': y_val_seg}) print("Validation Classification Loss:", val_class_loss) print("Validation Segmentation Loss:", val_seg_loss) print("Validation Classification Accuracy:", val_class_acc) print("Validation Segmentation Accuracy:", val_seg_acc) # Evaluate the model on training data train_loss, train_class_loss, train_seg_loss, train_class_acc, train_seg_acc = best_model.evaluate(X_train, {'classification_output': y_train_class, 'segmentation_output': y_train_seg}) print("Train Classification Loss:", train_class_loss) print("Train Segmentation Loss:", train_seg_loss) print("Train Classification Accuracy:", train_class_acc) print("Train Segmentation Accuracy:", train_seg_acc) # Return test classification accuracy return test_class_acc def plot_performance(history): # Plot classification accuracy classification_train_accuracy = history.history["classification_output_accuracy"] classification_val_accuracy = history.history["val_classification_output_accuracy"] plt.figure(figsize=(7, 3)) plt.plot(classification_train_accuracy, label="Training Accuracy") plt.plot(classification_val_accuracy, label="Validation Accuracy") plt.title("Classification Accuracy") plt.xlabel("Epochs") plt.ylabel("Accuracy") plt.legend() plt.show() # Plot classification loss classification_train_loss = history.history["classification_output_loss"] classification_val_loss = history.history["val_classification_output_loss"] plt.figure(figsize=(7, 3)) plt.plot(classification_train_loss, "b", label="Training Loss") plt.plot(classification_val_loss, "r", label="Validation Loss") plt.title("Classification Loss") plt.xlabel("Epochs") plt.ylabel("Loss") plt.legend() plt.show() # Plot segmentation accuracy segmentation_train_accuracy = history.history["segmentation_output_accuracy"] segmentation_val_accuracy = history.history["val_segmentation_output_accuracy"] plt.figure(figsize=(7, 3)) plt.plot(segmentation_train_accuracy, label="Training Accuracy") plt.plot(segmentation_val_accuracy, label="Validation Accuracy") plt.title("Segmentation Accuracy") plt.xlabel("Epochs") plt.ylabel("Accuracy") plt.legend() plt.show() # Plot segmentation loss segmentation_train_loss = history.history["segmentation_output_loss"] segmentation_val_loss = history.history["val_segmentation_output_loss"] plt.figure(figsize=(7, 3)) plt.plot(segmentation_train_loss, "b", label="Training Loss") plt.plot(segmentation_val_loss, "r", label="Validation Loss") plt.title("Segmentation Loss") plt.xlabel("Epochs") plt.ylabel("Loss") plt.legend() plt.show() # Set image size image_size = 224 # Define labels labels = ["bridge", "excess", "good", "insuff", "no"] # Set data folders data_folders = [ "/content/gdrive/MyDrive/Deep learning/FYP_2/4 Dataset Ratio 60 20 20/jit012/jit0/b_dip/train", "/content/gdrive/MyDrive/Deep learning/FYP_2/4 Dataset Ratio 60 20 20/jit012/jit0/b_dip/val", "/content/gdrive/MyDrive/Deep learning/FYP_2/4 Dataset Ratio 60 20 20/jit012/jit0/b_dip/test",] # Load data X_data, y_class_labels, y_seg_labels = load_data(data_folders) # Define train:val:test ratio for each class (ratio x4 = exact) class_data_counts = { "bridge": [40, 80, 80], "excess": [40, 80, 80], "good": [40, 80, 80], "insuff": [40, 80, 80], "no": [40, 80, 80]} # Split data X_train, y_train_class, y_train_seg, X_val, y_val_class, y_val_seg, X_test, y_test_class, y_test_seg = split_data( X_data, y_class_labels, y_seg_labels, class_data_counts) ''' print("Number of train images:", len(X_train)) print("Number of train binary masks:", len(y_train_seg)) print("Number of validation images:", len(X_val)) print("Number of validation binary masks:", len(y_val_seg)) print("Number of test images:", len(X_test)) print("Number of test binary masks:", len(y_test_seg)) ''' # Initialize the label encoder label_encoder = LabelEncoder() label_encoder.fit(y_class_labels) # Count the number of images of each class in the train, validation, and test sets train_counts = count_labels(y_train_class, label_encoder) val_counts = count_labels(y_val_class, label_encoder) test_counts = count_labels(y_test_class, label_encoder) print("Train counts: ", train_counts," Total in train set:", sum(train_counts.values())) print("Validation counts:", val_counts, " Total in validation set:", sum(val_counts.values())) print("Test counts: ", test_counts," Total in test set:", sum(test_counts.values())) # Build model input_shape = (image_size, image_size, 3) num_classes = len(labels) model = build_model(input_shape, num_classes) model.summary() # Train model n times test_class_acc_list = [] for i in range(5): print(f"\nTrain {i+1}:\n") model = build_model(input_shape, num_classes) batch_size = 16 epochs = 50 history = train_model(model, X_train, y_train_class, y_train_seg, X_val, y_val_class, y_val_seg, batch_size, epochs) # Evaluate model on test data test_class_acc = evaluate_model(model, X_test, y_test_class, y_test_seg) plot_performance(history) test_class_acc_list.append(test_class_acc) # Calculate average test classification accuracy average_test_class_acc = sum(test_class_acc_list) / len(test_class_acc_list) print("Test Classification Accuracy List:", test_class_acc_list) print("Average Test Classification Accuracy:", average_test_class_acc) " The above is the Python code with Keras to do multi-task learning with binary segmentation and classification using one mult-task learning model. Modify the code to change the model to resnet50 (from keras library), son no need to perform segmentation, only perform classification.
fa5f160f9bf696b70e7279a844430350
{ "intermediate": 0.3006076216697693, "beginner": 0.3237382769584656, "expert": 0.3756541907787323 }
42,695
You are a Python expert who can provide clear, concise, high-quality code. " import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns import cv2 import random import tensorflow as tf import tkinter as tk from tkinter import filedialog from PIL import ImageTk, Image from ipywidgets import interact, interactive, fixed, interact_manual import ipywidgets as widgets from IPython.display import display, clear_output from tensorflow.keras.preprocessing import image from tensorflow.keras.optimizers import Adam, SGD, RMSprop, AdamW, Adadelta, Adagrad, Adamax, Adafactor, Nadam, Ftrl from tensorflow.keras.preprocessing.image import ImageDataGenerator from tqdm import tqdm import os from sklearn.utils import shuffle from sklearn.preprocessing import LabelEncoder from sklearn.model_selection import train_test_split from tensorflow.keras.models import Sequential, Model, load_model from tensorflow.keras.layers import ( GlobalAveragePooling2D, Dropout, Dense, Conv2D, MaxPooling2D, Flatten, Dropout, BatchNormalization, Activation, concatenate, Conv2DTranspose, Input, Reshape, UpSampling2D, ) from tensorflow.keras.applications import ( EfficientNetV2B0, EfficientNetV2B1, EfficientNetV2B2, EfficientNetV2B3, EfficientNetV2L, EfficientNetV2M, EfficientNetV2S, ) from tensorflow.keras.applications import Xception from tensorflow.keras.applications import VGG16, VGG19 from tensorflow.keras.applications import ResNet50, ResNet101, ResNet152, ResNetRS50, ResNetRS101 from tensorflow.keras.applications import InceptionResNetV2, ConvNeXtXLarge, ConvNeXtBase, DenseNet121, MobileNetV2, NASNetLarge, NASNetMobile from tensorflow.keras.utils import to_categorical from tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau, TensorBoard, ModelCheckpoint from sklearn.metrics import classification_report, confusion_matrix import ipywidgets as widgets import io from PIL import Image from IPython.display import display, clear_output from warnings import filterwarnings from google.colab import drive drive.mount("/content/gdrive") def load_data(data_folders): X_data = [] # Combined data y_class_labels = [] # Combined classification labels y_seg_labels = [] # Combined segmentation labels for folderPath in data_folders: for label in labels: label_folder_path = os.path.join(folderPath, label) for filename in tqdm(os.listdir(label_folder_path)): if filename.endswith(".jpg"): img = cv2.imread(os.path.join(label_folder_path, filename)) img = cv2.resize(img, (image_size, image_size)) X_data.append(img) y_class_labels.append(label) seg_filename = filename.split(".")[0] + ".png" seg_img = cv2.imread(os.path.join(label_folder_path, seg_filename), 0) seg_img = cv2.resize(seg_img, (image_size, image_size)) seg_img = np.where(seg_img > 0, 1, 0) # Convert segmentation mask to binary y_seg_labels.append(seg_img) X_data = np.array(X_data) y_class_labels = np.array(y_class_labels) y_seg_labels = np.array(y_seg_labels) X_data, y_class_labels, y_seg_labels = shuffle(X_data, y_class_labels, y_seg_labels, random_state=101) return X_data, y_class_labels, y_seg_labels def split_data(X_data, y_class_labels, y_seg_labels, class_data_counts): X_train = [] y_train_class = [] y_train_seg = [] X_val = [] y_val_class = [] y_val_seg = [] X_test = [] y_test_class = [] y_test_seg = [] for label, count in class_data_counts.items(): label_indices = np.where(y_class_labels == label)[0] class_X_data = X_data[label_indices] class_y_class_labels = y_class_labels[label_indices] class_y_seg_labels = y_seg_labels[label_indices] train_count = count[0] val_count = count[1] test_count = count[2] class_X_train = class_X_data[:train_count] class_y_train_class = class_y_class_labels[:train_count] class_y_train_seg = class_y_seg_labels[:train_count] class_X_val = class_X_data[train_count: train_count + val_count] class_y_val_class = class_y_class_labels[train_count: train_count + val_count] class_y_val_seg = class_y_seg_labels[train_count: train_count + val_count] class_X_test = class_X_data[train_count + val_count: train_count + val_count + test_count] class_y_test_class = class_y_class_labels[train_count + val_count: train_count + val_count + test_count] class_y_test_seg = class_y_seg_labels[train_count + val_count: train_count + val_count + test_count] X_train.extend(class_X_train) y_train_class.extend(class_y_train_class) y_train_seg.extend(class_y_train_seg) X_val.extend(class_X_val) y_val_class.extend(class_y_val_class) y_val_seg.extend(class_y_val_seg) X_test.extend(class_X_test) y_test_class.extend(class_y_test_class) y_test_seg.extend(class_y_test_seg) # Convert class labels to categorical label_encoder = LabelEncoder() y_train_class_encoded = label_encoder.fit_transform(y_train_class) y_train_class_categorical = to_categorical(y_train_class_encoded) y_val_class_encoded = label_encoder.transform(y_val_class) y_val_class_categorical = to_categorical(y_val_class_encoded) y_test_class_encoded = label_encoder.transform(y_test_class) y_test_class_categorical = to_categorical(y_test_class_encoded) return ( np.array(X_train), np.array(y_train_class_categorical), np.array(y_train_seg), np.array(X_val), np.array(y_val_class_categorical), np.array(y_val_seg), np.array(X_test), np.array(y_test_class_categorical), np.array(y_test_seg), ) def count_labels(y_class_categorical, label_encoder): # Convert one-hot encoded labels back to label encoded y_class_labels = np.argmax(y_class_categorical, axis=1) # Convert label encoded labels back to original class names y_class_names = label_encoder.inverse_transform(y_class_labels) unique, counts = np.unique(y_class_names, return_counts=True) return dict(zip(unique, counts)) def build_model(input_shape, num_classes): num_filter = 32 # 16/32 best, 8: best classification but no segment # Encoder (Done) inputs = Input(input_shape) conv1 = Conv2D(num_filter * 1, 3, activation="linear", padding="same", strides=1)(inputs) bn1 = BatchNormalization()(conv1) relu1 = Activation("relu")(bn1) conv2 = Conv2D(num_filter * 1, 3, activation="linear", padding="same", strides=1)(relu1) bn2 = BatchNormalization()(conv2) relu2 = Activation("relu")(bn2) down1 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu2) conv3 = Conv2D(num_filter * 2, 3, activation="linear", padding="same", strides=1)(down1) bn3 = BatchNormalization()(conv3) relu3 = Activation("relu")(bn3) conv4 = Conv2D(num_filter * 2, 3, activation="linear", padding="same", strides=1)(relu3) bn4 = BatchNormalization()(conv4) relu4 = Activation("relu")(bn4) down2 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu4) conv5 = Conv2D(num_filter * 4, 3, activation="linear", padding="same", strides=1)(down2) bn5 = BatchNormalization()(conv5) relu5 = Activation("relu")(bn5) conv6 = Conv2D(num_filter * 4, 3, activation="linear", padding="same", strides=1)(relu5) bn6 = BatchNormalization()(conv6) relu6 = Activation("relu")(bn6) down3 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu6) conv7 = Conv2D(num_filter * 8, 3, activation="linear", padding="same", strides=1)(down3) bn7 = BatchNormalization()(conv7) relu7 = Activation("relu")(bn7) conv8 = Conv2D(num_filter * 8, 3, activation="linear", padding="same", strides=1)(relu7) bn8 = BatchNormalization()(conv8) relu8 = Activation("relu")(bn8) # Middle down4 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu8) conv9 = Conv2D(num_filter * 16, 3, activation="linear", padding="same", strides=1)(down4) bn9 = BatchNormalization()(conv9) relu9 = Activation("relu")(bn9) conv10 = Conv2D(num_filter * 16, 3, activation="linear", padding="same", strides=1)(relu9) bn10 = BatchNormalization()(conv10) relu10 = Activation("relu")(bn10) up1 = UpSampling2D(size=(2, 2), interpolation="bilinear")(relu10) # Decoder (Done) concat1 = concatenate([up1, relu8], axis=-1) # , axis=3 conv11 = Conv2D(num_filter * 8, 3, activation="linear", padding="same", strides=1)(concat1) bn11 = BatchNormalization()(conv11) relu11 = Activation("relu")(bn11) conv12 = Conv2D(num_filter * 8, 3, activation="linear", padding="same", strides=1)(relu11) bn12 = BatchNormalization()(conv12) relu12 = Activation("relu")(bn12) up2 = UpSampling2D(size=(2, 2), interpolation="bilinear")(relu12) concat2 = concatenate([up2, relu6], axis=-1) # , axis=3 conv13 = Conv2D(num_filter * 4, 3, activation="linear", padding="same", strides=1)(concat2) bn13 = BatchNormalization()(conv13) relu13 = Activation("relu")(bn13) conv14 = Conv2D(num_filter * 4, 3, activation="linear", padding="same", strides=1)(relu13) bn14 = BatchNormalization()(conv14) relu14 = Activation("relu")(bn14) up3 = UpSampling2D(size=(2, 2), interpolation="bilinear")(relu14) concat3 = concatenate([up3, relu4], axis=-1) # , axis=3 conv15 = Conv2D(num_filter * 2, 3, activation="linear", padding="same", strides=1)(concat3) bn15 = BatchNormalization()(conv15) relu15 = Activation("relu")(bn15) conv16 = Conv2D(num_filter * 2, 3, activation="linear", padding="same", strides=1)(relu15) bn16 = BatchNormalization()(conv16) relu16 = Activation("relu")(bn16) up4 = UpSampling2D(size=(2, 2), interpolation="bilinear")(relu16) concat4 = concatenate([up4, relu2], axis=-1) # , axis=3 conv17 = Conv2D(num_filter * 1, 3, activation="linear", padding="same", strides=1)(concat4) bn17 = BatchNormalization()(conv17) relu17 = Activation("relu")(bn17) conv18 = Conv2D(num_filter * 1, 3, activation="linear", padding="same", strides=1)(relu17) bn18 = BatchNormalization()(conv18) relu18 = Activation("relu")(bn18) # Segmentation branch segmentation_output = Conv2D(1, 1, activation="sigmoid", name="segmentation_output")(relu18) # original # Classification branch (Not done) gap1 = GlobalAveragePooling2D()(relu8) gap2 = GlobalAveragePooling2D()(relu10) gap3 = GlobalAveragePooling2D()(relu12) conv20 = Conv2D(16, 3, activation="linear", padding="same", strides=1)(segmentation_output) bn20 = BatchNormalization()(conv20) relu20 = Activation("relu")(bn20) down5 = MaxPooling2D(pool_size=(4, 4), strides=4)(relu20) conv21 = Conv2D(32, 3, activation="linear", padding="same", strides=1)(down5) bn21 = BatchNormalization()(conv21) relu21 = Activation("relu")(bn21) down6 = MaxPooling2D(pool_size=(4, 4), strides=4)(relu21) conv22 = Conv2D(64, 3, activation="linear", padding="same", strides=1)(down6) bn22 = BatchNormalization()(conv22) relu22 = Activation("relu")(bn22) down7 = MaxPooling2D(pool_size=(4, 4), strides=4)(relu22) flatten1 = Flatten()(down7) concat5 = concatenate([gap1, gap2, gap3, flatten1], axis=-1) # FC layers fc1 = Dense(1024, activation="relu")(concat5) dropout1 = Dropout(0.5)(fc1) fc2 = Dense(1024, activation="relu")(dropout1) dropout2 = Dropout(0.5)(fc2) classification_output = Dense(num_classes, activation="softmax", name="classification_output")(dropout2) # Define the model model = Model(inputs=inputs, outputs=[classification_output, segmentation_output]) return model def segmentation_loss(y_true, y_pred): y_true = tf.cast(y_true, tf.float32) y_pred = tf.cast(y_pred, tf.float32) bce_loss = tf.keras.losses.binary_crossentropy(y_true, y_pred) smooth = 1e-5 intersection = tf.reduce_sum(y_true * y_pred) union = tf.reduce_sum(y_true) + tf.reduce_sum(y_pred) dice_loss = 1.0 - 2.0 * (intersection + smooth) / (union + smooth) segmentation_loss = bce_loss + 1 * dice_loss return segmentation_loss def train_model(model, X_train, y_train_class, y_train_seg, X_val, y_val_class, y_val_seg, batch_size, epochs): checkpoint = ModelCheckpoint( "multitask_best_weights.h5", monitor="val_classification_output_accuracy", save_best_only=True, mode="max", verbose=1,) reduce_lr = ReduceLROnPlateau( monitor="val_classification_output_accuracy", factor=0.3, patience=2, min_delta=0.001, mode="auto", verbose=1,) tensorboard = TensorBoard(log_dir="logs") model.compile( optimizer=Adam(lr=0.001), loss={"classification_output": "categorical_crossentropy", "segmentation_output": segmentation_loss}, metrics={"classification_output": "accuracy", "segmentation_output": "accuracy"}, loss_weights={"classification_output": 1, "segmentation_output": 1},) history = model.fit( X_train, {"classification_output": y_train_class, "segmentation_output": y_train_seg}, validation_data=(X_val, {"classification_output": y_val_class, "segmentation_output": y_val_seg}), epochs=epochs, verbose=1, batch_size=batch_size, callbacks=[checkpoint, reduce_lr, tensorboard],) return history def evaluate_model(model, X_test, y_test_class, y_test_seg): with tf.keras.utils.custom_object_scope({"segmentation_loss": segmentation_loss}): # Load the best model weights best_model = load_model("multitask_best_weights.h5") # Evaluate the model on test data test_loss, test_class_loss, test_seg_loss, test_class_acc, test_seg_acc = best_model.evaluate( X_test, {"classification_output": y_test_class, "segmentation_output": y_test_seg}) print("Test Classification Loss:", test_class_loss) print("Test Segmentation Loss:", test_seg_loss) print("Test Classification Accuracy:", test_class_acc) print("Test Segmentation Accuracy:", test_seg_acc) # Evaluate the model on validation data val_loss, val_class_loss, val_seg_loss, val_class_acc, val_seg_acc = best_model.evaluate( X_val, {'classification_output': y_val_class, 'segmentation_output': y_val_seg}) print("Validation Classification Loss:", val_class_loss) print("Validation Segmentation Loss:", val_seg_loss) print("Validation Classification Accuracy:", val_class_acc) print("Validation Segmentation Accuracy:", val_seg_acc) # Evaluate the model on training data train_loss, train_class_loss, train_seg_loss, train_class_acc, train_seg_acc = best_model.evaluate(X_train, {'classification_output': y_train_class, 'segmentation_output': y_train_seg}) print("Train Classification Loss:", train_class_loss) print("Train Segmentation Loss:", train_seg_loss) print("Train Classification Accuracy:", train_class_acc) print("Train Segmentation Accuracy:", train_seg_acc) # Return test classification accuracy return test_class_acc def plot_performance(history): # Plot classification accuracy classification_train_accuracy = history.history["classification_output_accuracy"] classification_val_accuracy = history.history["val_classification_output_accuracy"] plt.figure(figsize=(7, 3)) plt.plot(classification_train_accuracy, label="Training Accuracy") plt.plot(classification_val_accuracy, label="Validation Accuracy") plt.title("Classification Accuracy") plt.xlabel("Epochs") plt.ylabel("Accuracy") plt.legend() plt.show() # Plot classification loss classification_train_loss = history.history["classification_output_loss"] classification_val_loss = history.history["val_classification_output_loss"] plt.figure(figsize=(7, 3)) plt.plot(classification_train_loss, "b", label="Training Loss") plt.plot(classification_val_loss, "r", label="Validation Loss") plt.title("Classification Loss") plt.xlabel("Epochs") plt.ylabel("Loss") plt.legend() plt.show() # Plot segmentation accuracy segmentation_train_accuracy = history.history["segmentation_output_accuracy"] segmentation_val_accuracy = history.history["val_segmentation_output_accuracy"] plt.figure(figsize=(7, 3)) plt.plot(segmentation_train_accuracy, label="Training Accuracy") plt.plot(segmentation_val_accuracy, label="Validation Accuracy") plt.title("Segmentation Accuracy") plt.xlabel("Epochs") plt.ylabel("Accuracy") plt.legend() plt.show() # Plot segmentation loss segmentation_train_loss = history.history["segmentation_output_loss"] segmentation_val_loss = history.history["val_segmentation_output_loss"] plt.figure(figsize=(7, 3)) plt.plot(segmentation_train_loss, "b", label="Training Loss") plt.plot(segmentation_val_loss, "r", label="Validation Loss") plt.title("Segmentation Loss") plt.xlabel("Epochs") plt.ylabel("Loss") plt.legend() plt.show() # Set image size image_size = 224 # Define labels labels = ["bridge", "excess", "good", "insuff", "no"] # Set data folders data_folders = [ "/content/gdrive/MyDrive/Deep learning/FYP_2/4 Dataset Ratio 60 20 20/jit012/jit0/b_dip/train", "/content/gdrive/MyDrive/Deep learning/FYP_2/4 Dataset Ratio 60 20 20/jit012/jit0/b_dip/val", "/content/gdrive/MyDrive/Deep learning/FYP_2/4 Dataset Ratio 60 20 20/jit012/jit0/b_dip/test",] # Load data X_data, y_class_labels, y_seg_labels = load_data(data_folders) # Define train:val:test ratio for each class (ratio x4 = exact) class_data_counts = { "bridge": [40, 80, 80], "excess": [40, 80, 80], "good": [40, 80, 80], "insuff": [40, 80, 80], "no": [40, 80, 80]} # Split data X_train, y_train_class, y_train_seg, X_val, y_val_class, y_val_seg, X_test, y_test_class, y_test_seg = split_data( X_data, y_class_labels, y_seg_labels, class_data_counts) ''' print("Number of train images:", len(X_train)) print("Number of train binary masks:", len(y_train_seg)) print("Number of validation images:", len(X_val)) print("Number of validation binary masks:", len(y_val_seg)) print("Number of test images:", len(X_test)) print("Number of test binary masks:", len(y_test_seg)) ''' # Initialize the label encoder label_encoder = LabelEncoder() label_encoder.fit(y_class_labels) # Count the number of images of each class in the train, validation, and test sets train_counts = count_labels(y_train_class, label_encoder) val_counts = count_labels(y_val_class, label_encoder) test_counts = count_labels(y_test_class, label_encoder) print("Train counts: ", train_counts," Total in train set:", sum(train_counts.values())) print("Validation counts:", val_counts, " Total in validation set:", sum(val_counts.values())) print("Test counts: ", test_counts," Total in test set:", sum(test_counts.values())) # Build model input_shape = (image_size, image_size, 3) num_classes = len(labels) model = build_model(input_shape, num_classes) model.summary() # Train model n times test_class_acc_list = [] for i in range(5): print(f"\nTrain {i+1}:\n") model = build_model(input_shape, num_classes) batch_size = 16 epochs = 50 history = train_model(model, X_train, y_train_class, y_train_seg, X_val, y_val_class, y_val_seg, batch_size, epochs) # Evaluate model on test data test_class_acc = evaluate_model(model, X_test, y_test_class, y_test_seg) plot_performance(history) test_class_acc_list.append(test_class_acc) # Calculate average test classification accuracy average_test_class_acc = sum(test_class_acc_list) / len(test_class_acc_list) print("Test Classification Accuracy List:", test_class_acc_list) print("Average Test Classification Accuracy:", average_test_class_acc) " The above is the Python code with Keras to do multi-task learning with binary segmentation and classification using one mult-task learning model. Modify the code to change the model to resnet50 (from keras library), son no need to perform segmentation, only perform classification.
974d45224d97b7d2a9ae49e16fcc3478
{ "intermediate": 0.3006076216697693, "beginner": 0.3237382769584656, "expert": 0.3756541907787323 }
42,696
وقتی یه سایت رو باز می‌کنم تو کنسول کروم این ارور رو می‌ده چطور حلش کنم؟ mozilla.social/:1 Access to CSS stylesheet at 'https://static.mozilla.social/packs/css/common-a729b6b0.css' from origin 'https://mozilla.social' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
d29504fd5fad4b32105429efc8b8c543
{ "intermediate": 0.3706667721271515, "beginner": 0.3324037790298462, "expert": 0.2969294488430023 }
42,697
You are a Python expert who can provide clear, concise, high-quality code. " import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns import cv2 import random import tensorflow as tf import tkinter as tk from tkinter import filedialog from PIL import ImageTk, Image from ipywidgets import interact, interactive, fixed, interact_manual import ipywidgets as widgets from IPython.display import display, clear_output from tensorflow.keras.preprocessing import image from tensorflow.keras.optimizers import Adam, SGD, RMSprop, AdamW, Adadelta, Adagrad, Adamax, Adafactor, Nadam, Ftrl from tensorflow.keras.preprocessing.image import ImageDataGenerator from tqdm import tqdm import os from sklearn.utils import shuffle from sklearn.preprocessing import LabelEncoder from sklearn.model_selection import train_test_split from tensorflow.keras.models import Sequential, Model, load_model from tensorflow.keras.layers import ( GlobalAveragePooling2D, Dropout, Dense, Conv2D, MaxPooling2D, Flatten, Dropout, BatchNormalization, Activation, concatenate, Conv2DTranspose, Input, Reshape, UpSampling2D, ) from tensorflow.keras.applications import ( EfficientNetV2B0, EfficientNetV2B1, EfficientNetV2B2, EfficientNetV2B3, EfficientNetV2L, EfficientNetV2M, EfficientNetV2S, ) from tensorflow.keras.applications import Xception from tensorflow.keras.applications import VGG16, VGG19 from tensorflow.keras.applications import ResNet50, ResNet101, ResNet152, ResNetRS50, ResNetRS101 from tensorflow.keras.applications import InceptionResNetV2, ConvNeXtXLarge, ConvNeXtBase, DenseNet121, MobileNetV2, NASNetLarge, NASNetMobile from tensorflow.keras.utils import to_categorical from tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau, TensorBoard, ModelCheckpoint from sklearn.metrics import classification_report, confusion_matrix import ipywidgets as widgets import io from PIL import Image from IPython.display import display, clear_output from warnings import filterwarnings from google.colab import drive drive.mount("/content/gdrive") def load_data(data_folders): X_data = [] # Combined data y_class_labels = [] # Combined classification labels y_seg_labels = [] # Combined segmentation labels for folderPath in data_folders: for label in labels: label_folder_path = os.path.join(folderPath, label) for filename in tqdm(os.listdir(label_folder_path)): if filename.endswith(".jpg"): img = cv2.imread(os.path.join(label_folder_path, filename)) img = cv2.resize(img, (image_size, image_size)) X_data.append(img) y_class_labels.append(label) seg_filename = filename.split(".")[0] + ".png" seg_img = cv2.imread(os.path.join(label_folder_path, seg_filename), 0) seg_img = cv2.resize(seg_img, (image_size, image_size)) seg_img = np.where(seg_img > 0, 1, 0) # Convert segmentation mask to binary y_seg_labels.append(seg_img) X_data = np.array(X_data) y_class_labels = np.array(y_class_labels) y_seg_labels = np.array(y_seg_labels) X_data, y_class_labels, y_seg_labels = shuffle(X_data, y_class_labels, y_seg_labels, random_state=101) return X_data, y_class_labels, y_seg_labels def split_data(X_data, y_class_labels, y_seg_labels, class_data_counts): X_train = [] y_train_class = [] y_train_seg = [] X_val = [] y_val_class = [] y_val_seg = [] X_test = [] y_test_class = [] y_test_seg = [] for label, count in class_data_counts.items(): label_indices = np.where(y_class_labels == label)[0] class_X_data = X_data[label_indices] class_y_class_labels = y_class_labels[label_indices] class_y_seg_labels = y_seg_labels[label_indices] train_count = count[0] val_count = count[1] test_count = count[2] class_X_train = class_X_data[:train_count] class_y_train_class = class_y_class_labels[:train_count] class_y_train_seg = class_y_seg_labels[:train_count] class_X_val = class_X_data[train_count: train_count + val_count] class_y_val_class = class_y_class_labels[train_count: train_count + val_count] class_y_val_seg = class_y_seg_labels[train_count: train_count + val_count] class_X_test = class_X_data[train_count + val_count: train_count + val_count + test_count] class_y_test_class = class_y_class_labels[train_count + val_count: train_count + val_count + test_count] class_y_test_seg = class_y_seg_labels[train_count + val_count: train_count + val_count + test_count] X_train.extend(class_X_train) y_train_class.extend(class_y_train_class) y_train_seg.extend(class_y_train_seg) X_val.extend(class_X_val) y_val_class.extend(class_y_val_class) y_val_seg.extend(class_y_val_seg) X_test.extend(class_X_test) y_test_class.extend(class_y_test_class) y_test_seg.extend(class_y_test_seg) # Convert class labels to categorical label_encoder = LabelEncoder() y_train_class_encoded = label_encoder.fit_transform(y_train_class) y_train_class_categorical = to_categorical(y_train_class_encoded) y_val_class_encoded = label_encoder.transform(y_val_class) y_val_class_categorical = to_categorical(y_val_class_encoded) y_test_class_encoded = label_encoder.transform(y_test_class) y_test_class_categorical = to_categorical(y_test_class_encoded) return ( np.array(X_train), np.array(y_train_class_categorical), np.array(y_train_seg), np.array(X_val), np.array(y_val_class_categorical), np.array(y_val_seg), np.array(X_test), np.array(y_test_class_categorical), np.array(y_test_seg), ) def count_labels(y_class_categorical, label_encoder): # Convert one-hot encoded labels back to label encoded y_class_labels = np.argmax(y_class_categorical, axis=1) # Convert label encoded labels back to original class names y_class_names = label_encoder.inverse_transform(y_class_labels) unique, counts = np.unique(y_class_names, return_counts=True) return dict(zip(unique, counts)) def build_model(input_shape, num_classes): num_filter = 32 # 16/32 best, 8: best classification but no segment # Encoder (Done) inputs = Input(input_shape) conv1 = Conv2D(num_filter * 1, 3, activation="linear", padding="same", strides=1)(inputs) bn1 = BatchNormalization()(conv1) relu1 = Activation("relu")(bn1) conv2 = Conv2D(num_filter * 1, 3, activation="linear", padding="same", strides=1)(relu1) bn2 = BatchNormalization()(conv2) relu2 = Activation("relu")(bn2) down1 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu2) conv3 = Conv2D(num_filter * 2, 3, activation="linear", padding="same", strides=1)(down1) bn3 = BatchNormalization()(conv3) relu3 = Activation("relu")(bn3) conv4 = Conv2D(num_filter * 2, 3, activation="linear", padding="same", strides=1)(relu3) bn4 = BatchNormalization()(conv4) relu4 = Activation("relu")(bn4) down2 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu4) conv5 = Conv2D(num_filter * 4, 3, activation="linear", padding="same", strides=1)(down2) bn5 = BatchNormalization()(conv5) relu5 = Activation("relu")(bn5) conv6 = Conv2D(num_filter * 4, 3, activation="linear", padding="same", strides=1)(relu5) bn6 = BatchNormalization()(conv6) relu6 = Activation("relu")(bn6) down3 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu6) conv7 = Conv2D(num_filter * 8, 3, activation="linear", padding="same", strides=1)(down3) bn7 = BatchNormalization()(conv7) relu7 = Activation("relu")(bn7) conv8 = Conv2D(num_filter * 8, 3, activation="linear", padding="same", strides=1)(relu7) bn8 = BatchNormalization()(conv8) relu8 = Activation("relu")(bn8) # Middle down4 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu8) conv9 = Conv2D(num_filter * 16, 3, activation="linear", padding="same", strides=1)(down4) bn9 = BatchNormalization()(conv9) relu9 = Activation("relu")(bn9) conv10 = Conv2D(num_filter * 16, 3, activation="linear", padding="same", strides=1)(relu9) bn10 = BatchNormalization()(conv10) relu10 = Activation("relu")(bn10) up1 = UpSampling2D(size=(2, 2), interpolation="bilinear")(relu10) # Decoder (Done) concat1 = concatenate([up1, relu8], axis=-1) # , axis=3 conv11 = Conv2D(num_filter * 8, 3, activation="linear", padding="same", strides=1)(concat1) bn11 = BatchNormalization()(conv11) relu11 = Activation("relu")(bn11) conv12 = Conv2D(num_filter * 8, 3, activation="linear", padding="same", strides=1)(relu11) bn12 = BatchNormalization()(conv12) relu12 = Activation("relu")(bn12) up2 = UpSampling2D(size=(2, 2), interpolation="bilinear")(relu12) concat2 = concatenate([up2, relu6], axis=-1) # , axis=3 conv13 = Conv2D(num_filter * 4, 3, activation="linear", padding="same", strides=1)(concat2) bn13 = BatchNormalization()(conv13) relu13 = Activation("relu")(bn13) conv14 = Conv2D(num_filter * 4, 3, activation="linear", padding="same", strides=1)(relu13) bn14 = BatchNormalization()(conv14) relu14 = Activation("relu")(bn14) up3 = UpSampling2D(size=(2, 2), interpolation="bilinear")(relu14) concat3 = concatenate([up3, relu4], axis=-1) # , axis=3 conv15 = Conv2D(num_filter * 2, 3, activation="linear", padding="same", strides=1)(concat3) bn15 = BatchNormalization()(conv15) relu15 = Activation("relu")(bn15) conv16 = Conv2D(num_filter * 2, 3, activation="linear", padding="same", strides=1)(relu15) bn16 = BatchNormalization()(conv16) relu16 = Activation("relu")(bn16) up4 = UpSampling2D(size=(2, 2), interpolation="bilinear")(relu16) concat4 = concatenate([up4, relu2], axis=-1) # , axis=3 conv17 = Conv2D(num_filter * 1, 3, activation="linear", padding="same", strides=1)(concat4) bn17 = BatchNormalization()(conv17) relu17 = Activation("relu")(bn17) conv18 = Conv2D(num_filter * 1, 3, activation="linear", padding="same", strides=1)(relu17) bn18 = BatchNormalization()(conv18) relu18 = Activation("relu")(bn18) # Segmentation branch segmentation_output = Conv2D(1, 1, activation="sigmoid", name="segmentation_output")(relu18) # original # Classification branch (Not done) gap1 = GlobalAveragePooling2D()(relu8) gap2 = GlobalAveragePooling2D()(relu10) gap3 = GlobalAveragePooling2D()(relu12) conv20 = Conv2D(16, 3, activation="linear", padding="same", strides=1)(segmentation_output) bn20 = BatchNormalization()(conv20) relu20 = Activation("relu")(bn20) down5 = MaxPooling2D(pool_size=(4, 4), strides=4)(relu20) conv21 = Conv2D(32, 3, activation="linear", padding="same", strides=1)(down5) bn21 = BatchNormalization()(conv21) relu21 = Activation("relu")(bn21) down6 = MaxPooling2D(pool_size=(4, 4), strides=4)(relu21) conv22 = Conv2D(64, 3, activation="linear", padding="same", strides=1)(down6) bn22 = BatchNormalization()(conv22) relu22 = Activation("relu")(bn22) down7 = MaxPooling2D(pool_size=(4, 4), strides=4)(relu22) flatten1 = Flatten()(down7) concat5 = concatenate([gap1, gap2, gap3, flatten1], axis=-1) # FC layers fc1 = Dense(1024, activation="relu")(concat5) dropout1 = Dropout(0.5)(fc1) fc2 = Dense(1024, activation="relu")(dropout1) dropout2 = Dropout(0.5)(fc2) classification_output = Dense(num_classes, activation="softmax", name="classification_output")(dropout2) # Define the model model = Model(inputs=inputs, outputs=[classification_output, segmentation_output]) return model def segmentation_loss(y_true, y_pred): y_true = tf.cast(y_true, tf.float32) y_pred = tf.cast(y_pred, tf.float32) bce_loss = tf.keras.losses.binary_crossentropy(y_true, y_pred) smooth = 1e-5 intersection = tf.reduce_sum(y_true * y_pred) union = tf.reduce_sum(y_true) + tf.reduce_sum(y_pred) dice_loss = 1.0 - 2.0 * (intersection + smooth) / (union + smooth) segmentation_loss = bce_loss + 1 * dice_loss return segmentation_loss def train_model(model, X_train, y_train_class, y_train_seg, X_val, y_val_class, y_val_seg, batch_size, epochs): checkpoint = ModelCheckpoint( "multitask_best_weights.h5", monitor="val_classification_output_accuracy", save_best_only=True, mode="max", verbose=1,) reduce_lr = ReduceLROnPlateau( monitor="val_classification_output_accuracy", factor=0.3, patience=2, min_delta=0.001, mode="auto", verbose=1,) tensorboard = TensorBoard(log_dir="logs") model.compile( optimizer=Adam(lr=0.001), loss={"classification_output": "categorical_crossentropy", "segmentation_output": segmentation_loss}, metrics={"classification_output": "accuracy", "segmentation_output": "accuracy"}, loss_weights={"classification_output": 1, "segmentation_output": 1},) history = model.fit( X_train, {"classification_output": y_train_class, "segmentation_output": y_train_seg}, validation_data=(X_val, {"classification_output": y_val_class, "segmentation_output": y_val_seg}), epochs=epochs, verbose=1, batch_size=batch_size, callbacks=[checkpoint, reduce_lr, tensorboard],) return history def evaluate_model(model, X_test, y_test_class, y_test_seg): with tf.keras.utils.custom_object_scope({"segmentation_loss": segmentation_loss}): # Load the best model weights best_model = load_model("multitask_best_weights.h5") # Evaluate the model on test data test_loss, test_class_loss, test_seg_loss, test_class_acc, test_seg_acc = best_model.evaluate( X_test, {"classification_output": y_test_class, "segmentation_output": y_test_seg}) print("Test Classification Loss:", test_class_loss) print("Test Segmentation Loss:", test_seg_loss) print("Test Classification Accuracy:", test_class_acc) print("Test Segmentation Accuracy:", test_seg_acc) # Evaluate the model on validation data val_loss, val_class_loss, val_seg_loss, val_class_acc, val_seg_acc = best_model.evaluate( X_val, {'classification_output': y_val_class, 'segmentation_output': y_val_seg}) print("Validation Classification Loss:", val_class_loss) print("Validation Segmentation Loss:", val_seg_loss) print("Validation Classification Accuracy:", val_class_acc) print("Validation Segmentation Accuracy:", val_seg_acc) # Evaluate the model on training data train_loss, train_class_loss, train_seg_loss, train_class_acc, train_seg_acc = best_model.evaluate(X_train, {'classification_output': y_train_class, 'segmentation_output': y_train_seg}) print("Train Classification Loss:", train_class_loss) print("Train Segmentation Loss:", train_seg_loss) print("Train Classification Accuracy:", train_class_acc) print("Train Segmentation Accuracy:", train_seg_acc) # Return test classification accuracy return test_class_acc def plot_performance(history): # Plot classification accuracy classification_train_accuracy = history.history["classification_output_accuracy"] classification_val_accuracy = history.history["val_classification_output_accuracy"] plt.figure(figsize=(7, 3)) plt.plot(classification_train_accuracy, label="Training Accuracy") plt.plot(classification_val_accuracy, label="Validation Accuracy") plt.title("Classification Accuracy") plt.xlabel("Epochs") plt.ylabel("Accuracy") plt.legend() plt.show() # Plot classification loss classification_train_loss = history.history["classification_output_loss"] classification_val_loss = history.history["val_classification_output_loss"] plt.figure(figsize=(7, 3)) plt.plot(classification_train_loss, "b", label="Training Loss") plt.plot(classification_val_loss, "r", label="Validation Loss") plt.title("Classification Loss") plt.xlabel("Epochs") plt.ylabel("Loss") plt.legend() plt.show() # Plot segmentation accuracy segmentation_train_accuracy = history.history["segmentation_output_accuracy"] segmentation_val_accuracy = history.history["val_segmentation_output_accuracy"] plt.figure(figsize=(7, 3)) plt.plot(segmentation_train_accuracy, label="Training Accuracy") plt.plot(segmentation_val_accuracy, label="Validation Accuracy") plt.title("Segmentation Accuracy") plt.xlabel("Epochs") plt.ylabel("Accuracy") plt.legend() plt.show() # Plot segmentation loss segmentation_train_loss = history.history["segmentation_output_loss"] segmentation_val_loss = history.history["val_segmentation_output_loss"] plt.figure(figsize=(7, 3)) plt.plot(segmentation_train_loss, "b", label="Training Loss") plt.plot(segmentation_val_loss, "r", label="Validation Loss") plt.title("Segmentation Loss") plt.xlabel("Epochs") plt.ylabel("Loss") plt.legend() plt.show() # Set image size image_size = 224 # Define labels labels = ["bridge", "excess", "good", "insuff", "no"] # Set data folders data_folders = [ "/content/gdrive/MyDrive/Deep learning/FYP_2/4 Dataset Ratio 60 20 20/jit012/jit0/b_dip/train", "/content/gdrive/MyDrive/Deep learning/FYP_2/4 Dataset Ratio 60 20 20/jit012/jit0/b_dip/val", "/content/gdrive/MyDrive/Deep learning/FYP_2/4 Dataset Ratio 60 20 20/jit012/jit0/b_dip/test",] # Load data X_data, y_class_labels, y_seg_labels = load_data(data_folders) # Define train:val:test ratio for each class (ratio x4 = exact) class_data_counts = { "bridge": [40, 80, 80], "excess": [40, 80, 80], "good": [40, 80, 80], "insuff": [40, 80, 80], "no": [40, 80, 80]} # Split data X_train, y_train_class, y_train_seg, X_val, y_val_class, y_val_seg, X_test, y_test_class, y_test_seg = split_data( X_data, y_class_labels, y_seg_labels, class_data_counts) ''' print("Number of train images:", len(X_train)) print("Number of train binary masks:", len(y_train_seg)) print("Number of validation images:", len(X_val)) print("Number of validation binary masks:", len(y_val_seg)) print("Number of test images:", len(X_test)) print("Number of test binary masks:", len(y_test_seg)) ''' # Initialize the label encoder label_encoder = LabelEncoder() label_encoder.fit(y_class_labels) # Count the number of images of each class in the train, validation, and test sets train_counts = count_labels(y_train_class, label_encoder) val_counts = count_labels(y_val_class, label_encoder) test_counts = count_labels(y_test_class, label_encoder) print("Train counts: ", train_counts," Total in train set:", sum(train_counts.values())) print("Validation counts:", val_counts, " Total in validation set:", sum(val_counts.values())) print("Test counts: ", test_counts," Total in test set:", sum(test_counts.values())) # Build model input_shape = (image_size, image_size, 3) num_classes = len(labels) model = build_model(input_shape, num_classes) model.summary() # Train model n times test_class_acc_list = [] for i in range(5): print(f"\nTrain {i+1}:\n") model = build_model(input_shape, num_classes) batch_size = 16 epochs = 50 history = train_model(model, X_train, y_train_class, y_train_seg, X_val, y_val_class, y_val_seg, batch_size, epochs) # Evaluate model on test data test_class_acc = evaluate_model(model, X_test, y_test_class, y_test_seg) plot_performance(history) test_class_acc_list.append(test_class_acc) # Calculate average test classification accuracy average_test_class_acc = sum(test_class_acc_list) / len(test_class_acc_list) print("Test Classification Accuracy List:", test_class_acc_list) print("Average Test Classification Accuracy:", average_test_class_acc) " The above is the Python code with Keras to do multi-task learning with binary segmentation and classification using one mult-task learning model. Modify the code to change the model to resnet50 (from keras library), so no need to perform segmentation, only perform classification. Do not modify the other part of my code.
2b4b65a2d7d7820c1f254451e8c7135a
{ "intermediate": 0.3006076216697693, "beginner": 0.3237382769584656, "expert": 0.3756541907787323 }
42,698
You are a Python expert who can provide clear, concise, high-quality code. " import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns import cv2 import random import tensorflow as tf import tkinter as tk from tkinter import filedialog from PIL import ImageTk, Image from ipywidgets import interact, interactive, fixed, interact_manual import ipywidgets as widgets from IPython.display import display, clear_output from tensorflow.keras.preprocessing import image from tensorflow.keras.optimizers import Adam, SGD, RMSprop, AdamW, Adadelta, Adagrad, Adamax, Adafactor, Nadam, Ftrl from tensorflow.keras.preprocessing.image import ImageDataGenerator from tqdm import tqdm import os from sklearn.utils import shuffle from sklearn.preprocessing import LabelEncoder from sklearn.model_selection import train_test_split from tensorflow.keras.models import Sequential, Model, load_model from tensorflow.keras.layers import ( GlobalAveragePooling2D, Dropout, Dense, Conv2D, MaxPooling2D, Flatten, Dropout, BatchNormalization, Activation, concatenate, Conv2DTranspose, Input, Reshape, UpSampling2D, ) from tensorflow.keras.applications import ( EfficientNetV2B0, EfficientNetV2B1, EfficientNetV2B2, EfficientNetV2B3, EfficientNetV2L, EfficientNetV2M, EfficientNetV2S, ) from tensorflow.keras.applications import Xception from tensorflow.keras.applications import VGG16, VGG19 from tensorflow.keras.applications import ResNet50, ResNet101, ResNet152, ResNetRS50, ResNetRS101 from tensorflow.keras.applications import InceptionResNetV2, ConvNeXtXLarge, ConvNeXtBase, DenseNet121, MobileNetV2, NASNetLarge, NASNetMobile from tensorflow.keras.utils import to_categorical from tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau, TensorBoard, ModelCheckpoint from sklearn.metrics import classification_report, confusion_matrix import ipywidgets as widgets import io from PIL import Image from IPython.display import display, clear_output from warnings import filterwarnings from google.colab import drive drive.mount("/content/gdrive") def load_data(data_folders): X_data = [] # Combined data y_class_labels = [] # Combined classification labels y_seg_labels = [] # Combined segmentation labels for folderPath in data_folders: for label in labels: label_folder_path = os.path.join(folderPath, label) for filename in tqdm(os.listdir(label_folder_path)): if filename.endswith(".jpg"): img = cv2.imread(os.path.join(label_folder_path, filename)) img = cv2.resize(img, (image_size, image_size)) X_data.append(img) y_class_labels.append(label) seg_filename = filename.split(".")[0] + ".png" seg_img = cv2.imread(os.path.join(label_folder_path, seg_filename), 0) seg_img = cv2.resize(seg_img, (image_size, image_size)) seg_img = np.where(seg_img > 0, 1, 0) # Convert segmentation mask to binary y_seg_labels.append(seg_img) X_data = np.array(X_data) y_class_labels = np.array(y_class_labels) y_seg_labels = np.array(y_seg_labels) X_data, y_class_labels, y_seg_labels = shuffle(X_data, y_class_labels, y_seg_labels, random_state=101) return X_data, y_class_labels, y_seg_labels def split_data(X_data, y_class_labels, y_seg_labels, class_data_counts): X_train = [] y_train_class = [] y_train_seg = [] X_val = [] y_val_class = [] y_val_seg = [] X_test = [] y_test_class = [] y_test_seg = [] for label, count in class_data_counts.items(): label_indices = np.where(y_class_labels == label)[0] class_X_data = X_data[label_indices] class_y_class_labels = y_class_labels[label_indices] class_y_seg_labels = y_seg_labels[label_indices] train_count = count[0] val_count = count[1] test_count = count[2] class_X_train = class_X_data[:train_count] class_y_train_class = class_y_class_labels[:train_count] class_y_train_seg = class_y_seg_labels[:train_count] class_X_val = class_X_data[train_count: train_count + val_count] class_y_val_class = class_y_class_labels[train_count: train_count + val_count] class_y_val_seg = class_y_seg_labels[train_count: train_count + val_count] class_X_test = class_X_data[train_count + val_count: train_count + val_count + test_count] class_y_test_class = class_y_class_labels[train_count + val_count: train_count + val_count + test_count] class_y_test_seg = class_y_seg_labels[train_count + val_count: train_count + val_count + test_count] X_train.extend(class_X_train) y_train_class.extend(class_y_train_class) y_train_seg.extend(class_y_train_seg) X_val.extend(class_X_val) y_val_class.extend(class_y_val_class) y_val_seg.extend(class_y_val_seg) X_test.extend(class_X_test) y_test_class.extend(class_y_test_class) y_test_seg.extend(class_y_test_seg) # Convert class labels to categorical label_encoder = LabelEncoder() y_train_class_encoded = label_encoder.fit_transform(y_train_class) y_train_class_categorical = to_categorical(y_train_class_encoded) y_val_class_encoded = label_encoder.transform(y_val_class) y_val_class_categorical = to_categorical(y_val_class_encoded) y_test_class_encoded = label_encoder.transform(y_test_class) y_test_class_categorical = to_categorical(y_test_class_encoded) return ( np.array(X_train), np.array(y_train_class_categorical), np.array(y_train_seg), np.array(X_val), np.array(y_val_class_categorical), np.array(y_val_seg), np.array(X_test), np.array(y_test_class_categorical), np.array(y_test_seg), ) def count_labels(y_class_categorical, label_encoder): # Convert one-hot encoded labels back to label encoded y_class_labels = np.argmax(y_class_categorical, axis=1) # Convert label encoded labels back to original class names y_class_names = label_encoder.inverse_transform(y_class_labels) unique, counts = np.unique(y_class_names, return_counts=True) return dict(zip(unique, counts)) def build_model(input_shape, num_classes): num_filter = 32 # 16/32 best, 8: best classification but no segment # Encoder (Done) inputs = Input(input_shape) conv1 = Conv2D(num_filter * 1, 3, activation="linear", padding="same", strides=1)(inputs) bn1 = BatchNormalization()(conv1) relu1 = Activation("relu")(bn1) conv2 = Conv2D(num_filter * 1, 3, activation="linear", padding="same", strides=1)(relu1) bn2 = BatchNormalization()(conv2) relu2 = Activation("relu")(bn2) down1 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu2) conv3 = Conv2D(num_filter * 2, 3, activation="linear", padding="same", strides=1)(down1) bn3 = BatchNormalization()(conv3) relu3 = Activation("relu")(bn3) conv4 = Conv2D(num_filter * 2, 3, activation="linear", padding="same", strides=1)(relu3) bn4 = BatchNormalization()(conv4) relu4 = Activation("relu")(bn4) down2 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu4) conv5 = Conv2D(num_filter * 4, 3, activation="linear", padding="same", strides=1)(down2) bn5 = BatchNormalization()(conv5) relu5 = Activation("relu")(bn5) conv6 = Conv2D(num_filter * 4, 3, activation="linear", padding="same", strides=1)(relu5) bn6 = BatchNormalization()(conv6) relu6 = Activation("relu")(bn6) down3 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu6) conv7 = Conv2D(num_filter * 8, 3, activation="linear", padding="same", strides=1)(down3) bn7 = BatchNormalization()(conv7) relu7 = Activation("relu")(bn7) conv8 = Conv2D(num_filter * 8, 3, activation="linear", padding="same", strides=1)(relu7) bn8 = BatchNormalization()(conv8) relu8 = Activation("relu")(bn8) # Middle down4 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu8) conv9 = Conv2D(num_filter * 16, 3, activation="linear", padding="same", strides=1)(down4) bn9 = BatchNormalization()(conv9) relu9 = Activation("relu")(bn9) conv10 = Conv2D(num_filter * 16, 3, activation="linear", padding="same", strides=1)(relu9) bn10 = BatchNormalization()(conv10) relu10 = Activation("relu")(bn10) up1 = UpSampling2D(size=(2, 2), interpolation="bilinear")(relu10) # Decoder (Done) concat1 = concatenate([up1, relu8], axis=-1) # , axis=3 conv11 = Conv2D(num_filter * 8, 3, activation="linear", padding="same", strides=1)(concat1) bn11 = BatchNormalization()(conv11) relu11 = Activation("relu")(bn11) conv12 = Conv2D(num_filter * 8, 3, activation="linear", padding="same", strides=1)(relu11) bn12 = BatchNormalization()(conv12) relu12 = Activation("relu")(bn12) up2 = UpSampling2D(size=(2, 2), interpolation="bilinear")(relu12) concat2 = concatenate([up2, relu6], axis=-1) # , axis=3 conv13 = Conv2D(num_filter * 4, 3, activation="linear", padding="same", strides=1)(concat2) bn13 = BatchNormalization()(conv13) relu13 = Activation("relu")(bn13) conv14 = Conv2D(num_filter * 4, 3, activation="linear", padding="same", strides=1)(relu13) bn14 = BatchNormalization()(conv14) relu14 = Activation("relu")(bn14) up3 = UpSampling2D(size=(2, 2), interpolation="bilinear")(relu14) concat3 = concatenate([up3, relu4], axis=-1) # , axis=3 conv15 = Conv2D(num_filter * 2, 3, activation="linear", padding="same", strides=1)(concat3) bn15 = BatchNormalization()(conv15) relu15 = Activation("relu")(bn15) conv16 = Conv2D(num_filter * 2, 3, activation="linear", padding="same", strides=1)(relu15) bn16 = BatchNormalization()(conv16) relu16 = Activation("relu")(bn16) up4 = UpSampling2D(size=(2, 2), interpolation="bilinear")(relu16) concat4 = concatenate([up4, relu2], axis=-1) # , axis=3 conv17 = Conv2D(num_filter * 1, 3, activation="linear", padding="same", strides=1)(concat4) bn17 = BatchNormalization()(conv17) relu17 = Activation("relu")(bn17) conv18 = Conv2D(num_filter * 1, 3, activation="linear", padding="same", strides=1)(relu17) bn18 = BatchNormalization()(conv18) relu18 = Activation("relu")(bn18) # Segmentation branch segmentation_output = Conv2D(1, 1, activation="sigmoid", name="segmentation_output")(relu18) # original # Classification branch (Not done) gap1 = GlobalAveragePooling2D()(relu8) gap2 = GlobalAveragePooling2D()(relu10) gap3 = GlobalAveragePooling2D()(relu12) conv20 = Conv2D(16, 3, activation="linear", padding="same", strides=1)(segmentation_output) bn20 = BatchNormalization()(conv20) relu20 = Activation("relu")(bn20) down5 = MaxPooling2D(pool_size=(4, 4), strides=4)(relu20) conv21 = Conv2D(32, 3, activation="linear", padding="same", strides=1)(down5) bn21 = BatchNormalization()(conv21) relu21 = Activation("relu")(bn21) down6 = MaxPooling2D(pool_size=(4, 4), strides=4)(relu21) conv22 = Conv2D(64, 3, activation="linear", padding="same", strides=1)(down6) bn22 = BatchNormalization()(conv22) relu22 = Activation("relu")(bn22) down7 = MaxPooling2D(pool_size=(4, 4), strides=4)(relu22) flatten1 = Flatten()(down7) concat5 = concatenate([gap1, gap2, gap3, flatten1], axis=-1) # FC layers fc1 = Dense(1024, activation="relu")(concat5) dropout1 = Dropout(0.5)(fc1) fc2 = Dense(1024, activation="relu")(dropout1) dropout2 = Dropout(0.5)(fc2) classification_output = Dense(num_classes, activation="softmax", name="classification_output")(dropout2) # Define the model model = Model(inputs=inputs, outputs=[classification_output, segmentation_output]) return model def segmentation_loss(y_true, y_pred): y_true = tf.cast(y_true, tf.float32) y_pred = tf.cast(y_pred, tf.float32) bce_loss = tf.keras.losses.binary_crossentropy(y_true, y_pred) smooth = 1e-5 intersection = tf.reduce_sum(y_true * y_pred) union = tf.reduce_sum(y_true) + tf.reduce_sum(y_pred) dice_loss = 1.0 - 2.0 * (intersection + smooth) / (union + smooth) segmentation_loss = bce_loss + 1 * dice_loss return segmentation_loss def train_model(model, X_train, y_train_class, y_train_seg, X_val, y_val_class, y_val_seg, batch_size, epochs): checkpoint = ModelCheckpoint( "multitask_best_weights.h5", monitor="val_classification_output_accuracy", save_best_only=True, mode="max", verbose=1,) reduce_lr = ReduceLROnPlateau( monitor="val_classification_output_accuracy", factor=0.3, patience=2, min_delta=0.001, mode="auto", verbose=1,) tensorboard = TensorBoard(log_dir="logs") model.compile( optimizer=Adam(lr=0.001), loss={"classification_output": "categorical_crossentropy", "segmentation_output": segmentation_loss}, metrics={"classification_output": "accuracy", "segmentation_output": "accuracy"}, loss_weights={"classification_output": 1, "segmentation_output": 1},) history = model.fit( X_train, {"classification_output": y_train_class, "segmentation_output": y_train_seg}, validation_data=(X_val, {"classification_output": y_val_class, "segmentation_output": y_val_seg}), epochs=epochs, verbose=1, batch_size=batch_size, callbacks=[checkpoint, reduce_lr, tensorboard],) return history def evaluate_model(model, X_test, y_test_class, y_test_seg): with tf.keras.utils.custom_object_scope({"segmentation_loss": segmentation_loss}): # Load the best model weights best_model = load_model("multitask_best_weights.h5") # Evaluate the model on test data test_loss, test_class_loss, test_seg_loss, test_class_acc, test_seg_acc = best_model.evaluate( X_test, {"classification_output": y_test_class, "segmentation_output": y_test_seg}) print("Test Classification Loss:", test_class_loss) print("Test Segmentation Loss:", test_seg_loss) print("Test Classification Accuracy:", test_class_acc) print("Test Segmentation Accuracy:", test_seg_acc) # Evaluate the model on validation data val_loss, val_class_loss, val_seg_loss, val_class_acc, val_seg_acc = best_model.evaluate( X_val, {'classification_output': y_val_class, 'segmentation_output': y_val_seg}) print("Validation Classification Loss:", val_class_loss) print("Validation Segmentation Loss:", val_seg_loss) print("Validation Classification Accuracy:", val_class_acc) print("Validation Segmentation Accuracy:", val_seg_acc) # Evaluate the model on training data train_loss, train_class_loss, train_seg_loss, train_class_acc, train_seg_acc = best_model.evaluate(X_train, {'classification_output': y_train_class, 'segmentation_output': y_train_seg}) print("Train Classification Loss:", train_class_loss) print("Train Segmentation Loss:", train_seg_loss) print("Train Classification Accuracy:", train_class_acc) print("Train Segmentation Accuracy:", train_seg_acc) # Return test classification accuracy return test_class_acc def plot_performance(history): # Plot classification accuracy classification_train_accuracy = history.history["classification_output_accuracy"] classification_val_accuracy = history.history["val_classification_output_accuracy"] plt.figure(figsize=(7, 3)) plt.plot(classification_train_accuracy, label="Training Accuracy") plt.plot(classification_val_accuracy, label="Validation Accuracy") plt.title("Classification Accuracy") plt.xlabel("Epochs") plt.ylabel("Accuracy") plt.legend() plt.show() # Plot classification loss classification_train_loss = history.history["classification_output_loss"] classification_val_loss = history.history["val_classification_output_loss"] plt.figure(figsize=(7, 3)) plt.plot(classification_train_loss, "b", label="Training Loss") plt.plot(classification_val_loss, "r", label="Validation Loss") plt.title("Classification Loss") plt.xlabel("Epochs") plt.ylabel("Loss") plt.legend() plt.show() # Plot segmentation accuracy segmentation_train_accuracy = history.history["segmentation_output_accuracy"] segmentation_val_accuracy = history.history["val_segmentation_output_accuracy"] plt.figure(figsize=(7, 3)) plt.plot(segmentation_train_accuracy, label="Training Accuracy") plt.plot(segmentation_val_accuracy, label="Validation Accuracy") plt.title("Segmentation Accuracy") plt.xlabel("Epochs") plt.ylabel("Accuracy") plt.legend() plt.show() # Plot segmentation loss segmentation_train_loss = history.history["segmentation_output_loss"] segmentation_val_loss = history.history["val_segmentation_output_loss"] plt.figure(figsize=(7, 3)) plt.plot(segmentation_train_loss, "b", label="Training Loss") plt.plot(segmentation_val_loss, "r", label="Validation Loss") plt.title("Segmentation Loss") plt.xlabel("Epochs") plt.ylabel("Loss") plt.legend() plt.show() # Set image size image_size = 224 # Define labels labels = ["bridge", "excess", "good", "insuff", "no"] # Set data folders data_folders = [ "/content/gdrive/MyDrive/Deep learning/FYP_2/4 Dataset Ratio 60 20 20/jit012/jit0/b_dip/train", "/content/gdrive/MyDrive/Deep learning/FYP_2/4 Dataset Ratio 60 20 20/jit012/jit0/b_dip/val", "/content/gdrive/MyDrive/Deep learning/FYP_2/4 Dataset Ratio 60 20 20/jit012/jit0/b_dip/test",] # Load data X_data, y_class_labels, y_seg_labels = load_data(data_folders) # Define train:val:test ratio for each class (ratio x4 = exact) class_data_counts = { "bridge": [40, 80, 80], "excess": [40, 80, 80], "good": [40, 80, 80], "insuff": [40, 80, 80], "no": [40, 80, 80]} # Split data X_train, y_train_class, y_train_seg, X_val, y_val_class, y_val_seg, X_test, y_test_class, y_test_seg = split_data( X_data, y_class_labels, y_seg_labels, class_data_counts) ''' print("Number of train images:", len(X_train)) print("Number of train binary masks:", len(y_train_seg)) print("Number of validation images:", len(X_val)) print("Number of validation binary masks:", len(y_val_seg)) print("Number of test images:", len(X_test)) print("Number of test binary masks:", len(y_test_seg)) ''' # Initialize the label encoder label_encoder = LabelEncoder() label_encoder.fit(y_class_labels) # Count the number of images of each class in the train, validation, and test sets train_counts = count_labels(y_train_class, label_encoder) val_counts = count_labels(y_val_class, label_encoder) test_counts = count_labels(y_test_class, label_encoder) print("Train counts: ", train_counts," Total in train set:", sum(train_counts.values())) print("Validation counts:", val_counts, " Total in validation set:", sum(val_counts.values())) print("Test counts: ", test_counts," Total in test set:", sum(test_counts.values())) # Build model input_shape = (image_size, image_size, 3) num_classes = len(labels) model = build_model(input_shape, num_classes) model.summary() # Train model n times test_class_acc_list = [] for i in range(5): print(f"\nTrain {i+1}:\n") model = build_model(input_shape, num_classes) batch_size = 16 epochs = 50 history = train_model(model, X_train, y_train_class, y_train_seg, X_val, y_val_class, y_val_seg, batch_size, epochs) # Evaluate model on test data test_class_acc = evaluate_model(model, X_test, y_test_class, y_test_seg) plot_performance(history) test_class_acc_list.append(test_class_acc) # Calculate average test classification accuracy average_test_class_acc = sum(test_class_acc_list) / len(test_class_acc_list) print("Test Classification Accuracy List:", test_class_acc_list) print("Average Test Classification Accuracy:", average_test_class_acc) " The above is the Python code with Keras to do multi-task learning with binary segmentation and classification using one mult-task learning model. Modify the code to change the model to resnet50 (from keras library), so no need to perform segmentation, only perform classification. Do not modify the other part of my code.
2cb945fabf73164edee09394dcba7272
{ "intermediate": 0.3006076216697693, "beginner": 0.3237382769584656, "expert": 0.3756541907787323 }
42,699
You are a Python expert who can provide clear, concise, high-quality code. " import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns import cv2 import random import tensorflow as tf import tkinter as tk from tkinter import filedialog from PIL import ImageTk, Image from ipywidgets import interact, interactive, fixed, interact_manual import ipywidgets as widgets from IPython.display import display, clear_output from tensorflow.keras.preprocessing import image from tensorflow.keras.optimizers import Adam, SGD, RMSprop, AdamW, Adadelta, Adagrad, Adamax, Adafactor, Nadam, Ftrl from tensorflow.keras.preprocessing.image import ImageDataGenerator from tqdm import tqdm import os from sklearn.utils import shuffle from sklearn.preprocessing import LabelEncoder from sklearn.model_selection import train_test_split from tensorflow.keras.models import Sequential, Model, load_model from tensorflow.keras.layers import ( GlobalAveragePooling2D, Dropout, Dense, Conv2D, MaxPooling2D, Flatten, Dropout, BatchNormalization, Activation, concatenate, Conv2DTranspose, Input, Reshape, UpSampling2D, ) from tensorflow.keras.applications import ( EfficientNetV2B0, EfficientNetV2B1, EfficientNetV2B2, EfficientNetV2B3, EfficientNetV2L, EfficientNetV2M, EfficientNetV2S, ) from tensorflow.keras.applications import Xception from tensorflow.keras.applications import VGG16, VGG19 from tensorflow.keras.applications import ResNet50, ResNet101, ResNet152, ResNetRS50, ResNetRS101 from tensorflow.keras.applications import InceptionResNetV2, ConvNeXtXLarge, ConvNeXtBase, DenseNet121, MobileNetV2, NASNetLarge, NASNetMobile from tensorflow.keras.utils import to_categorical from tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau, TensorBoard, ModelCheckpoint from sklearn.metrics import classification_report, confusion_matrix import ipywidgets as widgets import io from PIL import Image from IPython.display import display, clear_output from warnings import filterwarnings from google.colab import drive drive.mount("/content/gdrive") def load_data(data_folders): X_data = [] # Combined data y_class_labels = [] # Combined classification labels y_seg_labels = [] # Combined segmentation labels for folderPath in data_folders: for label in labels: label_folder_path = os.path.join(folderPath, label) for filename in tqdm(os.listdir(label_folder_path)): if filename.endswith(".jpg"): img = cv2.imread(os.path.join(label_folder_path, filename)) img = cv2.resize(img, (image_size, image_size)) X_data.append(img) y_class_labels.append(label) seg_filename = filename.split(".")[0] + ".png" seg_img = cv2.imread(os.path.join(label_folder_path, seg_filename), 0) seg_img = cv2.resize(seg_img, (image_size, image_size)) seg_img = np.where(seg_img > 0, 1, 0) # Convert segmentation mask to binary y_seg_labels.append(seg_img) X_data = np.array(X_data) y_class_labels = np.array(y_class_labels) y_seg_labels = np.array(y_seg_labels) X_data, y_class_labels, y_seg_labels = shuffle(X_data, y_class_labels, y_seg_labels, random_state=101) return X_data, y_class_labels, y_seg_labels def split_data(X_data, y_class_labels, y_seg_labels, class_data_counts): X_train = [] y_train_class = [] y_train_seg = [] X_val = [] y_val_class = [] y_val_seg = [] X_test = [] y_test_class = [] y_test_seg = [] for label, count in class_data_counts.items(): label_indices = np.where(y_class_labels == label)[0] class_X_data = X_data[label_indices] class_y_class_labels = y_class_labels[label_indices] class_y_seg_labels = y_seg_labels[label_indices] train_count = count[0] val_count = count[1] test_count = count[2] class_X_train = class_X_data[:train_count] class_y_train_class = class_y_class_labels[:train_count] class_y_train_seg = class_y_seg_labels[:train_count] class_X_val = class_X_data[train_count: train_count + val_count] class_y_val_class = class_y_class_labels[train_count: train_count + val_count] class_y_val_seg = class_y_seg_labels[train_count: train_count + val_count] class_X_test = class_X_data[train_count + val_count: train_count + val_count + test_count] class_y_test_class = class_y_class_labels[train_count + val_count: train_count + val_count + test_count] class_y_test_seg = class_y_seg_labels[train_count + val_count: train_count + val_count + test_count] X_train.extend(class_X_train) y_train_class.extend(class_y_train_class) y_train_seg.extend(class_y_train_seg) X_val.extend(class_X_val) y_val_class.extend(class_y_val_class) y_val_seg.extend(class_y_val_seg) X_test.extend(class_X_test) y_test_class.extend(class_y_test_class) y_test_seg.extend(class_y_test_seg) # Convert class labels to categorical label_encoder = LabelEncoder() y_train_class_encoded = label_encoder.fit_transform(y_train_class) y_train_class_categorical = to_categorical(y_train_class_encoded) y_val_class_encoded = label_encoder.transform(y_val_class) y_val_class_categorical = to_categorical(y_val_class_encoded) y_test_class_encoded = label_encoder.transform(y_test_class) y_test_class_categorical = to_categorical(y_test_class_encoded) return ( np.array(X_train), np.array(y_train_class_categorical), np.array(y_train_seg), np.array(X_val), np.array(y_val_class_categorical), np.array(y_val_seg), np.array(X_test), np.array(y_test_class_categorical), np.array(y_test_seg), ) def count_labels(y_class_categorical, label_encoder): # Convert one-hot encoded labels back to label encoded y_class_labels = np.argmax(y_class_categorical, axis=1) # Convert label encoded labels back to original class names y_class_names = label_encoder.inverse_transform(y_class_labels) unique, counts = np.unique(y_class_names, return_counts=True) return dict(zip(unique, counts)) def build_model(input_shape, num_classes): num_filter = 32 # 16/32 best, 8: best classification but no segment # Encoder (Done) inputs = Input(input_shape) conv1 = Conv2D(num_filter * 1, 3, activation="linear", padding="same", strides=1)(inputs) bn1 = BatchNormalization()(conv1) relu1 = Activation("relu")(bn1) conv2 = Conv2D(num_filter * 1, 3, activation="linear", padding="same", strides=1)(relu1) bn2 = BatchNormalization()(conv2) relu2 = Activation("relu")(bn2) down1 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu2) conv3 = Conv2D(num_filter * 2, 3, activation="linear", padding="same", strides=1)(down1) bn3 = BatchNormalization()(conv3) relu3 = Activation("relu")(bn3) conv4 = Conv2D(num_filter * 2, 3, activation="linear", padding="same", strides=1)(relu3) bn4 = BatchNormalization()(conv4) relu4 = Activation("relu")(bn4) down2 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu4) conv5 = Conv2D(num_filter * 4, 3, activation="linear", padding="same", strides=1)(down2) bn5 = BatchNormalization()(conv5) relu5 = Activation("relu")(bn5) conv6 = Conv2D(num_filter * 4, 3, activation="linear", padding="same", strides=1)(relu5) bn6 = BatchNormalization()(conv6) relu6 = Activation("relu")(bn6) down3 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu6) conv7 = Conv2D(num_filter * 8, 3, activation="linear", padding="same", strides=1)(down3) bn7 = BatchNormalization()(conv7) relu7 = Activation("relu")(bn7) conv8 = Conv2D(num_filter * 8, 3, activation="linear", padding="same", strides=1)(relu7) bn8 = BatchNormalization()(conv8) relu8 = Activation("relu")(bn8) # Middle down4 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu8) conv9 = Conv2D(num_filter * 16, 3, activation="linear", padding="same", strides=1)(down4) bn9 = BatchNormalization()(conv9) relu9 = Activation("relu")(bn9) conv10 = Conv2D(num_filter * 16, 3, activation="linear", padding="same", strides=1)(relu9) bn10 = BatchNormalization()(conv10) relu10 = Activation("relu")(bn10) up1 = UpSampling2D(size=(2, 2), interpolation="bilinear")(relu10) # Decoder (Done) concat1 = concatenate([up1, relu8], axis=-1) # , axis=3 conv11 = Conv2D(num_filter * 8, 3, activation="linear", padding="same", strides=1)(concat1) bn11 = BatchNormalization()(conv11) relu11 = Activation("relu")(bn11) conv12 = Conv2D(num_filter * 8, 3, activation="linear", padding="same", strides=1)(relu11) bn12 = BatchNormalization()(conv12) relu12 = Activation("relu")(bn12) up2 = UpSampling2D(size=(2, 2), interpolation="bilinear")(relu12) concat2 = concatenate([up2, relu6], axis=-1) # , axis=3 conv13 = Conv2D(num_filter * 4, 3, activation="linear", padding="same", strides=1)(concat2) bn13 = BatchNormalization()(conv13) relu13 = Activation("relu")(bn13) conv14 = Conv2D(num_filter * 4, 3, activation="linear", padding="same", strides=1)(relu13) bn14 = BatchNormalization()(conv14) relu14 = Activation("relu")(bn14) up3 = UpSampling2D(size=(2, 2), interpolation="bilinear")(relu14) concat3 = concatenate([up3, relu4], axis=-1) # , axis=3 conv15 = Conv2D(num_filter * 2, 3, activation="linear", padding="same", strides=1)(concat3) bn15 = BatchNormalization()(conv15) relu15 = Activation("relu")(bn15) conv16 = Conv2D(num_filter * 2, 3, activation="linear", padding="same", strides=1)(relu15) bn16 = BatchNormalization()(conv16) relu16 = Activation("relu")(bn16) up4 = UpSampling2D(size=(2, 2), interpolation="bilinear")(relu16) concat4 = concatenate([up4, relu2], axis=-1) # , axis=3 conv17 = Conv2D(num_filter * 1, 3, activation="linear", padding="same", strides=1)(concat4) bn17 = BatchNormalization()(conv17) relu17 = Activation("relu")(bn17) conv18 = Conv2D(num_filter * 1, 3, activation="linear", padding="same", strides=1)(relu17) bn18 = BatchNormalization()(conv18) relu18 = Activation("relu")(bn18) # Segmentation branch segmentation_output = Conv2D(1, 1, activation="sigmoid", name="segmentation_output")(relu18) # original # Classification branch (Not done) gap1 = GlobalAveragePooling2D()(relu8) gap2 = GlobalAveragePooling2D()(relu10) gap3 = GlobalAveragePooling2D()(relu12) conv20 = Conv2D(16, 3, activation="linear", padding="same", strides=1)(segmentation_output) bn20 = BatchNormalization()(conv20) relu20 = Activation("relu")(bn20) down5 = MaxPooling2D(pool_size=(4, 4), strides=4)(relu20) conv21 = Conv2D(32, 3, activation="linear", padding="same", strides=1)(down5) bn21 = BatchNormalization()(conv21) relu21 = Activation("relu")(bn21) down6 = MaxPooling2D(pool_size=(4, 4), strides=4)(relu21) conv22 = Conv2D(64, 3, activation="linear", padding="same", strides=1)(down6) bn22 = BatchNormalization()(conv22) relu22 = Activation("relu")(bn22) down7 = MaxPooling2D(pool_size=(4, 4), strides=4)(relu22) flatten1 = Flatten()(down7) concat5 = concatenate([gap1, gap2, gap3, flatten1], axis=-1) # FC layers fc1 = Dense(1024, activation="relu")(concat5) dropout1 = Dropout(0.5)(fc1) fc2 = Dense(1024, activation="relu")(dropout1) dropout2 = Dropout(0.5)(fc2) classification_output = Dense(num_classes, activation="softmax", name="classification_output")(dropout2) # Define the model model = Model(inputs=inputs, outputs=[classification_output, segmentation_output]) return model def segmentation_loss(y_true, y_pred): y_true = tf.cast(y_true, tf.float32) y_pred = tf.cast(y_pred, tf.float32) bce_loss = tf.keras.losses.binary_crossentropy(y_true, y_pred) smooth = 1e-5 intersection = tf.reduce_sum(y_true * y_pred) union = tf.reduce_sum(y_true) + tf.reduce_sum(y_pred) dice_loss = 1.0 - 2.0 * (intersection + smooth) / (union + smooth) segmentation_loss = bce_loss + 1 * dice_loss return segmentation_loss def train_model(model, X_train, y_train_class, y_train_seg, X_val, y_val_class, y_val_seg, batch_size, epochs): checkpoint = ModelCheckpoint( "multitask_best_weights.h5", monitor="val_classification_output_accuracy", save_best_only=True, mode="max", verbose=1,) reduce_lr = ReduceLROnPlateau( monitor="val_classification_output_accuracy", factor=0.3, patience=2, min_delta=0.001, mode="auto", verbose=1,) tensorboard = TensorBoard(log_dir="logs") model.compile( optimizer=Adam(lr=0.001), loss={"classification_output": "categorical_crossentropy", "segmentation_output": segmentation_loss}, metrics={"classification_output": "accuracy", "segmentation_output": "accuracy"}, loss_weights={"classification_output": 1, "segmentation_output": 1},) history = model.fit( X_train, {"classification_output": y_train_class, "segmentation_output": y_train_seg}, validation_data=(X_val, {"classification_output": y_val_class, "segmentation_output": y_val_seg}), epochs=epochs, verbose=1, batch_size=batch_size, callbacks=[checkpoint, reduce_lr, tensorboard],) return history def evaluate_model(model, X_test, y_test_class, y_test_seg): with tf.keras.utils.custom_object_scope({"segmentation_loss": segmentation_loss}): # Load the best model weights best_model = load_model("multitask_best_weights.h5") # Evaluate the model on test data test_loss, test_class_loss, test_seg_loss, test_class_acc, test_seg_acc = best_model.evaluate( X_test, {"classification_output": y_test_class, "segmentation_output": y_test_seg}) print("Test Classification Loss:", test_class_loss) print("Test Segmentation Loss:", test_seg_loss) print("Test Classification Accuracy:", test_class_acc) print("Test Segmentation Accuracy:", test_seg_acc) # Evaluate the model on validation data val_loss, val_class_loss, val_seg_loss, val_class_acc, val_seg_acc = best_model.evaluate( X_val, {'classification_output': y_val_class, 'segmentation_output': y_val_seg}) print("Validation Classification Loss:", val_class_loss) print("Validation Segmentation Loss:", val_seg_loss) print("Validation Classification Accuracy:", val_class_acc) print("Validation Segmentation Accuracy:", val_seg_acc) # Evaluate the model on training data train_loss, train_class_loss, train_seg_loss, train_class_acc, train_seg_acc = best_model.evaluate(X_train, {'classification_output': y_train_class, 'segmentation_output': y_train_seg}) print("Train Classification Loss:", train_class_loss) print("Train Segmentation Loss:", train_seg_loss) print("Train Classification Accuracy:", train_class_acc) print("Train Segmentation Accuracy:", train_seg_acc) # Return test classification accuracy return test_class_acc def plot_performance(history): # Plot classification accuracy classification_train_accuracy = history.history["classification_output_accuracy"] classification_val_accuracy = history.history["val_classification_output_accuracy"] plt.figure(figsize=(7, 3)) plt.plot(classification_train_accuracy, label="Training Accuracy") plt.plot(classification_val_accuracy, label="Validation Accuracy") plt.title("Classification Accuracy") plt.xlabel("Epochs") plt.ylabel("Accuracy") plt.legend() plt.show() # Plot classification loss classification_train_loss = history.history["classification_output_loss"] classification_val_loss = history.history["val_classification_output_loss"] plt.figure(figsize=(7, 3)) plt.plot(classification_train_loss, "b", label="Training Loss") plt.plot(classification_val_loss, "r", label="Validation Loss") plt.title("Classification Loss") plt.xlabel("Epochs") plt.ylabel("Loss") plt.legend() plt.show() # Plot segmentation accuracy segmentation_train_accuracy = history.history["segmentation_output_accuracy"] segmentation_val_accuracy = history.history["val_segmentation_output_accuracy"] plt.figure(figsize=(7, 3)) plt.plot(segmentation_train_accuracy, label="Training Accuracy") plt.plot(segmentation_val_accuracy, label="Validation Accuracy") plt.title("Segmentation Accuracy") plt.xlabel("Epochs") plt.ylabel("Accuracy") plt.legend() plt.show() # Plot segmentation loss segmentation_train_loss = history.history["segmentation_output_loss"] segmentation_val_loss = history.history["val_segmentation_output_loss"] plt.figure(figsize=(7, 3)) plt.plot(segmentation_train_loss, "b", label="Training Loss") plt.plot(segmentation_val_loss, "r", label="Validation Loss") plt.title("Segmentation Loss") plt.xlabel("Epochs") plt.ylabel("Loss") plt.legend() plt.show() # Set image size image_size = 224 # Define labels labels = ["bridge", "excess", "good", "insuff", "no"] # Set data folders data_folders = [ "/content/gdrive/MyDrive/Deep learning/FYP_2/4 Dataset Ratio 60 20 20/jit012/jit0/b_dip/train", "/content/gdrive/MyDrive/Deep learning/FYP_2/4 Dataset Ratio 60 20 20/jit012/jit0/b_dip/val", "/content/gdrive/MyDrive/Deep learning/FYP_2/4 Dataset Ratio 60 20 20/jit012/jit0/b_dip/test",] # Load data X_data, y_class_labels, y_seg_labels = load_data(data_folders) # Define train:val:test ratio for each class (ratio x4 = exact) class_data_counts = { "bridge": [40, 80, 80], "excess": [40, 80, 80], "good": [40, 80, 80], "insuff": [40, 80, 80], "no": [40, 80, 80]} # Split data X_train, y_train_class, y_train_seg, X_val, y_val_class, y_val_seg, X_test, y_test_class, y_test_seg = split_data( X_data, y_class_labels, y_seg_labels, class_data_counts) ''' print("Number of train images:", len(X_train)) print("Number of train binary masks:", len(y_train_seg)) print("Number of validation images:", len(X_val)) print("Number of validation binary masks:", len(y_val_seg)) print("Number of test images:", len(X_test)) print("Number of test binary masks:", len(y_test_seg)) ''' # Initialize the label encoder label_encoder = LabelEncoder() label_encoder.fit(y_class_labels) # Count the number of images of each class in the train, validation, and test sets train_counts = count_labels(y_train_class, label_encoder) val_counts = count_labels(y_val_class, label_encoder) test_counts = count_labels(y_test_class, label_encoder) print("Train counts: ", train_counts," Total in train set:", sum(train_counts.values())) print("Validation counts:", val_counts, " Total in validation set:", sum(val_counts.values())) print("Test counts: ", test_counts," Total in test set:", sum(test_counts.values())) # Build model input_shape = (image_size, image_size, 3) num_classes = len(labels) model = build_model(input_shape, num_classes) model.summary() # Train model n times test_class_acc_list = [] for i in range(5): print(f"\nTrain {i+1}:\n") model = build_model(input_shape, num_classes) batch_size = 16 epochs = 50 history = train_model(model, X_train, y_train_class, y_train_seg, X_val, y_val_class, y_val_seg, batch_size, epochs) # Evaluate model on test data test_class_acc = evaluate_model(model, X_test, y_test_class, y_test_seg) plot_performance(history) test_class_acc_list.append(test_class_acc) # Calculate average test classification accuracy average_test_class_acc = sum(test_class_acc_list) / len(test_class_acc_list) print("Test Classification Accuracy List:", test_class_acc_list) print("Average Test Classification Accuracy:", average_test_class_acc) " The above is the Python code with Keras to do multi-task learning with binary segmentation and classification using one mult-task learning model. Modify the code to change the model to resnet50 (from keras library), son no need to perform segmentation, only perform classification.
5783311a4b590d3781f241ee0e270625
{ "intermediate": 0.3006076216697693, "beginner": 0.3237382769584656, "expert": 0.3756541907787323 }
42,700
pw-config prints: "config.path": "/nix/store/19wv1f4znj1zxm0zysf5pp7smnjcavvh-pipewire-1.0.3/share/pipewire/pipewire.conf", "override.2.0.config.path": "/etc/pipewire/pipewire.conf.d/10-obs-only-sink.conf", "override.2.1.config.path": "/etc/pipewire/pipewire.conf.d/11-disable-x11-bell.conf" Contents of 10-obs-only-sink.conf are: { "context": { "objects": [ { "args": { "audio": { "position": "FL,FR" }, "factory": { "name": "support.null-audio-sink" }, "media": { "class": "Audio/Sink" }, "node": { "description": "Output for OBS", "name": "OBS-only" } }, "factory": "adapter" } ] } } But for some reason, pw-config merge context.objects does not show the null sink.
51b6fe828de3069563f8576f39fa55fe
{ "intermediate": 0.39457184076309204, "beginner": 0.30162858963012695, "expert": 0.3037995994091034 }
42,701
In NixOS, I'm running pipewire 1.0.3 currently. How can I test running 1.0.2 without changing the whole system to boot a previous config?
aa35e56a4ddf71e62d6e5b2d7409e20e
{ "intermediate": 0.5933524966239929, "beginner": 0.21908056735992432, "expert": 0.18756695091724396 }
42,702
./pages/shop/src/styles/BestSellers.css Global CSS cannot be imported from files other than your Custom <App>. Due to the Global nature of stylesheets, and to avoid conflicts, Please move all first-party global CSS imports to pages/_app.js. Or convert the import to Component-Level CSS (CSS Modules). Read more: https://nextjs.org/docs/messages/css-global Location: pages\shop\src\components\CartHold.js
1f4962d7f0d2a625f0a1ea4b4d992051
{ "intermediate": 0.34243258833885193, "beginner": 0.3903728127479553, "expert": 0.26719462871551514 }
42,703
As a business magnet, Karthikeya Srinivas is interested in purchasing real estate in Melbourne. Can you provide insights or predictions on the next big trend in the real estate market or identify reasonably priced 2 - bedroom units using a Random Forest Regressor? Additionally, please calculate the Mean Absolute Error for the predictions made by the model MELBOURNE_HOUSE_PRICES_LESS.csv:- Suburb Address Rooms Type Price Method SellerG Date Postcode Regionname Propertycount Distance CouncilArea Abbotsford 49 Lithgow St 3 h 1490000 S Jellis 01-04-2017 3067 Northern Metropolitan 4019 3 Yarra City Council Abbotsford 59A Turner St 3 h 1220000 S Marshall 01-04-2017 3067 Northern Metropolitan 4019 3 Yarra City Council Melbourne_housing_FULL.csv:- Suburb Address Rooms Type Price Method SellerG Date Distance Postcode Bedroom2 Bathroom Car Landsize BuildingArea YearBuilt CouncilArea Lattitude Longtitude Regionname Propertycount Abbotsford 68 Studley St 2 h SS Jellis 03-09-2016 2.5 3067 2 1 1 126 Yarra City Council -37.8014 144.9958 Northern Metropolitan 4019 write python program
3e1d1a9f80aea7b431985b6f7557bd4d
{ "intermediate": 0.41151106357574463, "beginner": 0.21343614161014557, "expert": 0.3750527799129486 }
42,704
Uncaught runtime errors: ERROR can't access property "style", document.querySelector(...) is null dontShowHandler@http://localhost:3000/static/js/bundle.js:514:14 callCallback@http://localhost:3000/static/js/bundle.js:36575:18 invokeGuardedCallbackDev@http://localhost:3000/static/js/bundle.js:36619:20 invokeGuardedCallback@http://localhost:3000/static/js/bundle.js:36676:35 invokeGuardedCallbackAndCatchFirstError@http://localhost:3000/static/js/bundle.js:36690:29 executeDispatch@http://localhost:3000/static/js/bundle.js:40833:46 processDispatchQueueItemsInOrder@http://localhost:3000/static/js/bundle.js:40859:26 processDispatchQueue@http://localhost:3000/static/js/bundle.js:40870:41 dispatchEventsForPlugins@http://localhost:3000/static/js/bundle.js:40879:27 ./node_modules/react-dom/cjs/react-dom.development.js/dispatchEventForPluginEventSystem/<@http://localhost:3000/static/js/bundle.js:41039:16 batchedUpdates$1@http://localhost:3000/static/js/bundle.js:55423:16 batchedUpdates@http://localhost:3000/static/js/bundle.js:36423:16 dispatchEventForPluginEventSystem@http://localhost:3000/static/js/bundle.js:41038:21 dispatchEventWithEnableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay@http://localhost:3000/static/js/bundle.js:38545:42 dispatchEvent@http://localhost:3000/static/js/bundle.js:38539:88 dispatchContinuousEvent@http://localhost:3000/static/js/bundle.js:38528:22 CODE: import React from 'react' import "../styles/Body.css"; import { useState } from 'react'; import { store } from '../productsStore/Store'; import HoverImage from "react-hover-image/build" import { Link } from 'react-router-dom'; const Body = () => { const [show, setShow] = useState(true); const [show2, setShow2] = useState(false); const [show3, setShow3] = useState(false); const [show4, setShow4] = useState(false); const showHandler = () => { setShow(true) document.querySelector(".bodyContent").classList.add("transition"); setShow2(false) setShow3(false) setShow4(false) document.querySelector(".bodyContent").style.opacity = "1"; document.querySelector(".hairContent").style.opacity = "0"; document.querySelector(".newContent").style.opacity = "0"; document.querySelector(".travelContent").style.opacity = "0"; } const showHandler2 = () => { setShow2(true) document.querySelector(".hairContent").classList.add("transition2"); setShow(false) setShow3(false) setShow4(false) document.querySelector(".hairContent").style.opacity = "1"; document.querySelector(".bodyContent").style.opacity = "0"; document.querySelector(".newContent").style.opacity = "0"; document.querySelector(".travelContent").style.opacity = "0"; } const showHandler3 = () => { setShow3(true) document.querySelector(".travelContent").classList.add("transition3"); //document.querySelector(".hairContent").style.opacity = "0"; //document.querySelector(".newContent").style.opacity="0" setShow(false) setShow2(false) setShow4(false) document.querySelector(".travelContent").style.opacity = "1"; document.querySelector(".hairContent").style.opacity = "0"; document.querySelector(".bodyContent").style.opacity = "0"; document.querySelector(".newContent").style.opacity = "0"; } const showHandler4 = () => { setShow4(true) document.querySelector(".newContent").classList.add("transition4"); //document.querySelector(".travelContent").style.opacity = "0"; setShow(false) setShow2(false) setShow3(false) document.querySelector(".newContent").style.opacity = "1"; document.querySelector(".hairContent").style.opacity = "0"; document.querySelector(".bodyContent").style.opacity = "0"; document.querySelector(".travelContent").style.opacity = "0"; } const dontShowHandler = () => { setShow(false) setShow2(false) setShow3(false) setShow4(false) document.querySelector(".newContent").style.opacity = "0"; document.querySelector(".hairContent").style.opacity = "0"; document.querySelector(".bodyContent").style.opacity = "0"; document.querySelector(".travelContent").style.opacity = "0"; } return ( <div> <div className='categoryHold flex flex-col gap-14 font-normal absolute left-16 top-11'> <div className='bodyHold lineHeight w-56 w56rem' onMouseMove={showHandler}> <p className=' font-semibold hover-underline-animation'>BODY</p> </div> <div className='hairHold lineHeight w-56' onMouseMove={showHandler2}> <p className=' font-semibold hover-underline-animation'>HAIR</p> </div> <div className='travelHold w-52 lineHeight' onMouseMove={showHandler3}> <p className=' font-semibold hover-underline-animation'>TRAVEL</p> </div> <div className='newHold lineHeight' onMouseMove={showHandler4}> <p className=' font-semibold hover-underline-animation'>NEW</p> </div> </div> {show && <div className=' z-50 bodyContent color text-base' onMouseLeave={dontShowHandler}> <p> Body Wash </p> <p> Body Scrub </p> <p> Body Lotions </p> <p> Body Oil </p> <p> Hand Wash </p> <p> Hand Creams </p> <div className='bodyTypeHold flex'> {store.map((item) => { if (item.type == "navbar-BodyType") { return ( <Link to={`/${item.id}`} key={item.id}> <div key={item.id} className="bodyTypeIndivitual"> <HoverImage src={item.primaryImage} hoverSrc={item.hoverImg} className="rounded-xl bodyTypeImage" /> <p className=' text-center fs bodyTypeName'> {item.name} </p> </div> </Link>) } })} </div> </div>} {show2 && <div className=' z-50 hairContent flex flex-col' onMouseLeave={dontShowHandler}> <div className='hairTypeCategoryONE flex flex-col gap-8'> <p className=' font-bold text-xl'> CATEGORY </p> <p> Shampoos </p> <p> Conditioners </p> <p> Treatments </p> </div> <div className='hairTypeCategoryTWO flex-col flex gap-10'> <p className='font-bold'> HAIR CONCERN </p> <p> Deep Cleanse </p> <p> Oily </p> <p> Dry </p> <p> Volume </p> <p> Normal </p> </div> <div className='hairImageHold flex flex-row gap-10'> <img src='https://cdn.shopify.com/s/files/1/0081/7374/8305/articles/Natural_Balance_Shampoo_02_540x.jpg?v=1550710011' className=' rounded-xl w-52' /> <img src='https://cdn.shopify.com/s/files/1/0081/7374/8305/articles/ee7ea9c87918e493665a3a84bdf6c00a_large_1b25100f-7d60-451b-9d01-e74d104141d5_540x.jpg?v=1550710009' className=' rounded-xl w-52' /> </div> <div className='hairTextHold flex flex-row relative font-semibold'> <p className='flex flex-row flex-wrap w-56'>Make The Switch! Why Natural Haircare Is Best</p> <p className='flex flex-row flex-wrap w-56'>How to lead a natural & sustainable lifestyle</p> </div> </div>} {show3 && <div className='z-50 travelContent' onMouseLeave={dontShowHandler}> <div className='flex flex-row'> <div className='TravelStoreHold flex flex-row gap-16'> {store.map((item) => { if (item.type == "navbar-TravelType") { return ( <Link to={`/${item.id}`} key={item.id}> <div key={item.id} className="TravelIndivitual"> <HoverImage src={item.primaryImage} hoverSrc={item.hoverImg} className=" rounded-xl w-40" /> <p className=' font-semibold text-base px'> {item.name} </p> <p className='text-base font-normal text-center'> ${item.price} </p> </div> </Link> ) } })} </div> </div> </div>} {show4 && <div className='newContent relative left-72 text-base text-gray-500 top-16' onMouseLeave={dontShowHandler}> <div className='newCategoryHold flex flex-col gap-9'> <p className='font-bold text-xl'> CATEGORY </p> <p> Brightening Range </p> <p> Facial Masks </p> <p> Rosehip Range </p> <p> Shop All New Arrivals </p> </div> <div className='newTypeHold relative flex felx-row gap-10'> {store.map((item) => { if (item.type == "navbar-NewType") { return ( <Link to={`/${item.id}`} key={item.id}> <div className='newIndivitual'> <HoverImage src={item.primaryImage} hoverSrc={item.hoverImg} className=" rounded-xl w-40" /> <p className='font-semibold text-center text-base px'> {item.name} </p> <p className='text-base font-normal text-center'> ${item.price} </p> </div> </Link> ) } })} </div> </div>} </div> ) } export default Body
815526ddfd779e1d1627ab849d084d6b
{ "intermediate": 0.2909665107727051, "beginner": 0.5266193747520447, "expert": 0.18241412937641144 }
42,705
fix ERROR can't access property "style", document.querySelector(...) is null in: import React from 'react' import "../styles/Body.css"; import { useState } from 'react'; import { store } from '../productsStore/Store'; import HoverImage from "react-hover-image/build" import { Link } from 'react-router-dom'; const Body = () => { const [show, setShow] = useState(true); const [show2, setShow2] = useState(false); const [show3, setShow3] = useState(false); const [show4, setShow4] = useState(false); const showHandler = () => { setShow(true) document.querySelector(".bodyContent").classList.add("transition"); setShow2(false) setShow3(false) setShow4(false) document.querySelector(".bodyContent").style.opacity = "1"; document.querySelector(".hairContent").style.opacity = "0"; document.querySelector(".newContent").style.opacity = "0"; document.querySelector(".travelContent").style.opacity = "0"; } const showHandler2 = () => { setShow2(true) document.querySelector(".hairContent").classList.add("transition2"); setShow(false) setShow3(false) setShow4(false) document.querySelector(".hairContent").style.opacity = "1"; document.querySelector(".bodyContent").style.opacity = "0"; document.querySelector(".newContent").style.opacity = "0"; document.querySelector(".travelContent").style.opacity = "0"; } const showHandler3 = () => { setShow3(true) document.querySelector(".travelContent").classList.add("transition3"); //document.querySelector(".hairContent").style.opacity = "0"; //document.querySelector(".newContent").style.opacity="0" setShow(false) setShow2(false) setShow4(false) document.querySelector(".travelContent").style.opacity = "1"; document.querySelector(".hairContent").style.opacity = "0"; document.querySelector(".bodyContent").style.opacity = "0"; document.querySelector(".newContent").style.opacity = "0"; } const showHandler4 = () => { setShow4(true) document.querySelector(".newContent").classList.add("transition4"); //document.querySelector(".travelContent").style.opacity = "0"; setShow(false) setShow2(false) setShow3(false) document.querySelector(".newContent").style.opacity = "1"; document.querySelector(".hairContent").style.opacity = "0"; document.querySelector(".bodyContent").style.opacity = "0"; document.querySelector(".travelContent").style.opacity = "0"; } const dontShowHandler = () => { setShow(false) setShow2(false) setShow3(false) setShow4(false) document.querySelector(".newContent").style.opacity = "0"; document.querySelector(".hairContent").style.opacity = "0"; document.querySelector(".bodyContent").style.opacity = "0"; document.querySelector(".travelContent").style.opacity = "0"; } return ( <div> <div className='categoryHold flex flex-col gap-14 font-normal absolute left-16 top-11'> <div className='bodyHold lineHeight w-56 w56rem' onMouseMove={showHandler}> <p className=' font-semibold hover-underline-animation'>BODY</p> </div> <div className='hairHold lineHeight w-56' onMouseMove={showHandler2}> <p className=' font-semibold hover-underline-animation'>HAIR</p> </div> <div className='travelHold w-52 lineHeight' onMouseMove={showHandler3}> <p className=' font-semibold hover-underline-animation'>TRAVEL</p> </div> <div className='newHold lineHeight' onMouseMove={showHandler4}> <p className=' font-semibold hover-underline-animation'>NEW</p> </div> </div> {show && <div className=' z-50 bodyContent color text-base' onMouseLeave={dontShowHandler}> <p> Body Wash </p> <p> Body Scrub </p> <p> Body Lotions </p> <p> Body Oil </p> <p> Hand Wash </p> <p> Hand Creams </p> <div className='bodyTypeHold flex'> {store.map((item) => { if (item.type == "navbar-BodyType") { return ( <Link to={`/${item.id}`} key={item.id}> <div key={item.id} className="bodyTypeIndivitual"> <HoverImage src={item.primaryImage} hoverSrc={item.hoverImg} className="rounded-xl bodyTypeImage" /> <p className=' text-center fs bodyTypeName'> {item.name} </p> </div> </Link>) } })} </div> </div>} {show2 && <div className=' z-50 hairContent flex flex-col' onMouseLeave={dontShowHandler}> <div className='hairTypeCategoryONE flex flex-col gap-8'> <p className=' font-bold text-xl'> CATEGORY </p> <p> Shampoos </p> <p> Conditioners </p> <p> Treatments </p> </div> <div className='hairTypeCategoryTWO flex-col flex gap-10'> <p className='font-bold'> HAIR CONCERN </p> <p> Deep Cleanse </p> <p> Oily </p> <p> Dry </p> <p> Volume </p> <p> Normal </p> </div> <div className='hairImageHold flex flex-row gap-10'> <img src='https://cdn.shopify.com/s/files/1/0081/7374/8305/articles/Natural_Balance_Shampoo_02_540x.jpg?v=1550710011' className=' rounded-xl w-52' /> <img src='https://cdn.shopify.com/s/files/1/0081/7374/8305/articles/ee7ea9c87918e493665a3a84bdf6c00a_large_1b25100f-7d60-451b-9d01-e74d104141d5_540x.jpg?v=1550710009' className=' rounded-xl w-52' /> </div> <div className='hairTextHold flex flex-row relative font-semibold'> <p className='flex flex-row flex-wrap w-56'>Make The Switch! Why Natural Haircare Is Best</p> <p className='flex flex-row flex-wrap w-56'>How to lead a natural & sustainable lifestyle</p> </div> </div>} {show3 && <div className='z-50 travelContent' onMouseLeave={dontShowHandler}> <div className='flex flex-row'> <div className='TravelStoreHold flex flex-row gap-16'> {store.map((item) => { if (item.type == "navbar-TravelType") { return ( <Link to={`/${item.id}`} key={item.id}> <div key={item.id} className="TravelIndivitual"> <HoverImage src={item.primaryImage} hoverSrc={item.hoverImg} className=" rounded-xl w-40" /> <p className=' font-semibold text-base px'> {item.name} </p> <p className='text-base font-normal text-center'> ${item.price} </p> </div> </Link> ) } })} </div> </div> </div>} {show4 && <div className='newContent relative left-72 text-base text-gray-500 top-16' onMouseLeave={dontShowHandler}> <div className='newCategoryHold flex flex-col gap-9'> <p className='font-bold text-xl'> CATEGORY </p> <p> Brightening Range </p> <p> Facial Masks </p> <p> Rosehip Range </p> <p> Shop All New Arrivals </p> </div> <div className='newTypeHold relative flex felx-row gap-10'> {store.map((item) => { if (item.type == "navbar-NewType") { return ( <Link to={`/${item.id}`} key={item.id}> <div className='newIndivitual'> <HoverImage src={item.primaryImage} hoverSrc={item.hoverImg} className=" rounded-xl w-40" /> <p className='font-semibold text-center text-base px'> {item.name} </p> <p className='text-base font-normal text-center'> ${item.price} </p> </div> </Link> ) } })} </div> </div>} </div> ) } export default Body
740585077edf07f3dab1f32a00f84aca
{ "intermediate": 0.32124897837638855, "beginner": 0.5261101722717285, "expert": 0.15264084935188293 }
42,706
give me tidal code for some drum and bass
437da1c7d05a39dc406ff859d50c4175
{ "intermediate": 0.4442211091518402, "beginner": 0.35553860664367676, "expert": 0.20024023950099945 }
42,707
give me tidal cycles code where you mix hindi song aaj jaane ki zid na karo with trap uisc
5af73baae74bfab8b356c9bebf458e24
{ "intermediate": 0.28803956508636475, "beginner": 0.32632893323898315, "expert": 0.3856315612792969 }
42,708
give me a unique sad music patten using tidaycycles code
2455b2af2b32c66657d52ee42d4ec0cc
{ "intermediate": 0.3305352032184601, "beginner": 0.4229894280433655, "expert": 0.24647530913352966 }
42,709
please explain like i am a layperson: ""LEARN Test Pinecone serverless at scale with AWSLearn more Rerankers and Two-Stage Retrieval Retrieval Augmented Generation (RAG) is an overloaded term. It promises the world, but after developing a RAG pipeline, there are many of us left wondering why it doesn't work as well as we had expected. As with most tools, RAG is easy to use but hard to master. The truth is that there is more to RAG than putting documents into a vector DB and adding an LLM on top. That can work, but it won't always. This ebook aims to tell you what to do when out-of-the-box RAG doesn't work. In this first chapter, we'll look at what is often the easiest and fastest to implement solution for suboptimal RAG pipelines — we'll be learning about rerankers. Video companion for this chapter. Recall vs. Context Windows Before jumping into the solution, let's talk about the problem. With RAG, we are performing a semantic search across many text documents — these could be tens of thousands up to tens of billions of documents. To ensure fast search times at scale, we typically use vector search — that is, we transform our text into vectors, place them all into a vector space, and compare their proximity to a query vector using a similarity metric like cosine similarity. For vector search to work, we need vectors. These vectors are essentially compressions of the "meaning" behind some text into (typically) 768 or 1536-dimensional vectors. There is some information loss because we're compressing this information into a single vector. Because of this information loss, we often see that the top three (for example) vector search documents will miss relevant information. Unfortunately, the retrieval may return relevant information below our top_k cutoff. What do we do if relevant information at a lower position would help our LLM formulate a better response? The easiest approach is to increase the number of documents we're returning (increase top_k) and pass them all to the LLM. The metric we would measure here is recall — meaning "how many of the relevant documents are we retrieving". Recall does not consider the total number of retrieved documents — so we can hack the metric and get perfect recall by returning everything. � � � � � � @ � = #    � �    � � � � � � � �    � � � �    � � � � � � � � #    � �    � � � � � � � �    � � � �    � �    � � � � � � � recall@K= #ofrelevantdocsindataset #ofrelevantdocsreturned ​ Unfortunately, we cannot return everything. LLMs have limits on how much text we can pass to them — we call this limit the context window. Some LLMs have huge context windows, like Anthropic's Claude, with a context window of 100K tokens [1]. With that, we could fit many tens of pages of text — so could we return many documents (not quite all) and "stuff" the context window to improve recall? Again, no. We cannot use context stuffing because this reduces the LLM's recall performance — note that this is the LLM recall, which is different from the retrieval recall we have been discussing so far. When storing information in the middle of a context window, an LLM's ability to recall that information becomes worse than had it not been provided in the first place When storing information in the middle of a context window, an LLM's ability to recall that information becomes worse than had it not been provided in the first place [2]. LLM recall refers to the ability of an LLM to find information from the text placed within its context window. Research shows that LLM recall degrades as we put more tokens in the context window [2]. LLMs are also less likely to follow instructions as we stuff the context window — so context stuffing is a bad idea. We can increase the number of documents returned by our vector DB to increase retrieval recall, but we cannot pass these to our LLM without damaging LLM recall. The solution to this issue is to maximize retrieval recall by retrieving plenty of documents and then maximize LLM recall by minimizing the number of documents that make it to the LLM. To do that, we reorder retrieved documents and keep just the most relevant for our LLM — to do that, we use reranking. Power of Rerankers A reranking model — also known as a cross-encoder — is a type of model that, given a query and document pair, will output a similarity score. We use this score to reorder the documents by relevance to our query. A two-stage retrieval system. The vector DB step will typically include a bi-encoder or sparse embedding model. A two-stage retrieval system. The vector DB step will typically include a bi-encoder or sparse embedding model. Search engineers have used rerankers in two-stage retrieval systems for a long time. In these two-stage systems, a first-stage model (an embedding model/retriever) retrieves a set of relevant documents from a larger dataset. Then, a second-stage model (the reranker) is used to rerank those documents retrieved by the first-stage model. We use two stages because retrieving a small set of documents from a large dataset is much faster than reranking a large set of documents — we'll discuss why this is the case soon — but TL;DR, rerankers are slow, and retrievers are fast. Why Rerankers? If a reranker is so much slower, why bother using them? The answer is that rerankers are much more accurate than embedding models. The intuition behind a bi-encoder's inferior accuracy is that bi-encoders must compress all of the possible meanings of a document into a single vector — meaning we lose information. Additionally, bi-encoders have no context on the query because we don't know the query until we receive it (we create embeddings before user query time). On the other hand, a reranker can receive the raw information directly into the large transformer computation, meaning less information loss. Because we are running the reranker at user query time, we have the added benefit of analyzing our document's meaning specific to the user query — rather than trying to produce a generic, averaged meaning. Rerankers avoid the information loss of bi-encoders — but they come with a different penalty — time. A bi-encoder model compresses the document or query meaning into a single vector. Note that the bi-encoder processes our query in the same way as it does documents, but at user query time. A bi-encoder model compresses the document or query meaning into a single vector. Note that the bi-encoder processes our query in the same way as it does documents, but at user query time. When using bi-encoder models with vector search, we frontload all of the heavy transformer computation to when we are creating the initial vectors — that means that when a user queries our system, we have already created the vectors, so all we need to do is: Run a single transformer computation to create the query vector. Compare the query vector to document vectors with cosine similarity (or another lightweight metric). With rerankers, we are not pre-computing anything. Instead, we're feeding our query and a single other document into the transformer, running a whole transformer inference step, and outputting a single similarity score. A reranker considers query and document to produce a single similarity score over a full transformer inference step. Note that document A here is equivalent to our query. A reranker considers query and document to produce a single similarity score over a full transformer inference step. Note that document A here is equivalent to our query. Given 40M records, if we use a small reranking model like BERT on a V100 GPU — we'd be waiting more than 50 hours to return a single query result [3]. We can do the same in <100ms with encoder models and vector search. Implementing Two-Stage Retrieval with Reranking Now that we understand the idea and reason behind two-stage retrieval with rerankers, let's see how to implement it (you can follow along with this notebook. To begin we will set up our prerequisite libraries: !pip install -qU \ datasets==2.14.5 \ openai==0.28.1 \ pinecone-client==2.2.4 \ cohere==4.27 Data Preparation Before setting up the retrieval pipeline, we need data to retrieve! We will use the jamescalam/ai-arxiv-chunked dataset from Hugging Face Datasets. This dataset contains more than 400 ArXiv papers on ML, NLP, and LLMs — including the Llama 2, GPTQ, and GPT-4 papers. from datasets import load_dataset data = load_dataset("jamescalam/ai-arxiv-chunked", split="train") data Downloading data files: 0%| | 0/1 [00:00<?, ?it/s] Downloading data: 0%| | 0.00/153M [00:00<?, ?B/s] Extracting data files: 0%| | 0/1 [00:00<?, ?it/s] Generating train split: 0 examples [00:00, ? examples/s] Dataset({ features: ['doi', 'chunk-id', 'chunk', 'id', 'title', 'summary', 'source', 'authors', 'categories', 'comment', 'journal_ref', 'primary_category', 'published', 'updated', 'references'], num_rows: 41584 }) The dataset contains 41.5K pre-chunked records. Each record is 1-2 paragraphs long and includes additional metadata about the paper from which it comes. Here is an example: data[0] {'doi': '1910.01108', 'chunk-id': '0', 'chunk': 'DistilBERT, a distilled version of BERT: smaller,\nfaster, cheaper and lighter\nVictor SANH, Lysandre DEBUT, Julien CHAUMOND, Thomas WOLF\nHugging Face\n{victor,lysandre,julien,<PRESIDIO_ANONYMIZED_EMAIL_ADDRESS>\nAbstract\nAs Transfer Learning from large-scale pre-trained models becomes more prevalent\nin Natural Language Processing (NLP), operating these large models in on-theedge and/or under constrained computational training or inference budgets remains\nchallenging. In this work, we propose a method to pre-train a smaller generalpurpose language representation model, called DistilBERT, which can then be finetuned with good performances on a wide range of tasks like its larger counterparts.\nWhile most prior work investigated the use of distillation for building task-specific\nmodels, we leverage knowledge distillation during the pre-training phase and show\nthat it is possible to reduce the size of a BERT model by 40%, while retaining 97%\nof its language understanding capabilities and being 60% faster. To leverage the\ninductive biases learned by larger models during pre-training, we introduce a triple\nloss combining language modeling, distillation and cosine-distance losses. Our\nsmaller, faster and lighter model is cheaper to pre-train and we demonstrate its', 'id': '1910.01108', 'title': 'DistilBERT, a distilled version of BERT: smaller, faster, cheaper and lighter', 'summary': 'As Transfer Learning from large-scale pre-trained models becomes more\nprevalent in Natural Language Processing (NLP), operating these large models in\non-the-edge and/or under constrained computational training or inference\nbudgets remains challenging. In this work, we propose a method to pre-train a\nsmaller general-purpose language representation model, called DistilBERT, which\ncan then be fine-tuned with good performances on a wide range of tasks like its\nlarger counterparts. While most prior work investigated the use of distillation\nfor building task-specific models, we leverage knowledge distillation during\nthe pre-training phase and show that it is possible to reduce the size of a\nBERT model by 40%, while retaining 97% of its language understanding\ncapabilities and being 60% faster. To leverage the inductive biases learned by\nlarger models during pre-training, we introduce a triple loss combining\nlanguage modeling, distillation and cosine-distance losses. Our smaller, faster\nand lighter model is cheaper to pre-train and we demonstrate its capabilities\nfor on-device computations in a proof-of-concept experiment and a comparative\non-device study.', 'source': 'http://arxiv.org/pdf/1910.01108', 'authors': ['Victor Sanh', 'Lysandre Debut', 'Julien Chaumond', 'Thomas Wolf'], 'categories': ['cs.CL'], 'comment': 'February 2020 - Revision: fix bug in evaluation metrics, updated\n metrics, argumentation unchanged. 5 pages, 1 figure, 4 tables. Accepted at\n the 5th Workshop on Energy Efficient Machine Learning and Cognitive Computing\n - NeurIPS 2019', 'journal_ref': None, 'primary_category': 'cs.CL', 'published': '20191002', 'updated': '20200301', 'references': [{'id': '1910.01108'}]} We'll be feeding this data into Pinecone, so let's reformat the dataset to be more Pinecone-friendly when it does come to the later embed and index process. The format will contain id, text (which we will embed), and metadata. For this example, we won't use metadata, but it can be helpful to include if we want to do metadata filtering in the future. data = data.map(lambda x: { "id": f'{x["id"]}-{x["chunk-id"]}', "text": x["chunk"], "metadata": { "title": x["title"], "url": x["source"], "primary_category": x["primary_category"], "published": x["published"], "updated": x["updated"], "text": x["chunk"], } }) # drop uneeded columns data = data.remove_columns([ "title", "summary", "source", "authors", "categories", "comment", "journal_ref", "primary_category", "published", "updated", "references", "doi", "chunk-id", "chunk" ]) data Map: 0%| | 0/41584 [00:00<?, ? examples/s] Dataset({ features: ['id', 'text', 'metadata'], num_rows: 41584 }) Embed and Index To store everything in the vector DB, we need to encode everything with an embedding / bi-encoder model. For simplicity, we will use text-embedding-ada-002 from OpenAI. We do need an OpenAI API key]() to authenticate ourselves via the OpenAI client: import openai # platform.openai.com # get API key from top-right dropdown on OpenAI website openai.api_key = "YOUR_OPENAI_API_KEY" embed_model = "text-embedding-ada-002" Now, we create our vector DB to store our vectors. For this, we need to get a free Pinecone API key — you can find the API key and environment variable in the "API Keys" section of the left navbar. import pinecone # initialize connection to pinecone (get API key at app.pinecone.io) api_key = "YOUR_PINECONE_API_KEY" # find your environment next to the api key in pinecone console env = "YOUR_PINECONE_ENV" pinecone.init(api_key=api_key, environment=env) After authentication, we create our index. We set dimension equal to the dimensionality of Ada-002 (1536) and use a metric compatible with Ada-002 — that can be either cosine or dotproduct. import time index_name = "rerankers" # check if index already exists (it shouldn't if this is first time) if index_name not in pinecone.list_indexes(): # if does not exist, create index pinecone.create_index( index_name, dimension=1536, # dimensionality of ada 002 metric='dotproduct' ) # wait for index to be initialized while not pinecone.describe_index(index_name).status['ready']: time.sleep(1) # connect to index index = pinecone.Index(index_name) We're now ready to begin populating the index using OpenAI's embedding model like so: from tqdm.auto import tqdm batch_size = 100 # how many embeddings we create and insert at once for i in tqdm(range(0, len(data), batch_size)): passed = False # find end of batch i_end = min(len(data), i+batch_size) # create batch batch = data[i:i_end] # create embeddings (exponential backoff to avoid RateLimitError) for j in range(5): # max 5 retries try: res = openai.Embedding.create(input=batch["text"], engine=embed_model) passed = True except openai.error.RateLimitError: time.sleep(2**j) # wait 2^j seconds before retrying print("Retrying...") if not passed: raise RuntimeError("Failed to create embeddings.") # get embeddings embeds = [record['embedding'] for record in res['data']] to_upsert = list(zip(batch["id"], embeds, batch["metadata"])) # upsert to Pinecone index.upsert(vectors=to_upsert) Our index is now populated and ready for us to query! Retrieval Without Reranking Before reranking, let's see how our results look without it. We will define a function called get_docs to return documents using the first stage of retrieval only: def get_docs(query: str, top_k: int): # encode query xq = embed([query])[0] # search pinecone index res = index.query(xq, top_k=top_k, include_metadata=True) # get doc text docs = {x["metadata"]['text']: i for i, x in enumerate(res["matches"])} return docs Let's ask about Reinforcement Learning with Human Feedback — a popular fine-tuning method behind the sudden performance gains demonstrated by ChatGPT when it was released. query = "can you explain why we would want to do rlhf?" docs = get_docs(query, top_k=25) print("\n---\n".join(docs.keys()[:3])) # print the first 3 docs whichmodels areprompted toexplain theirreasoningwhen givena complexproblem, inorder toincrease the likelihood that their final answer is correct. RLHF has emerged as a powerful strategy for fine-tuning Large Language Models, enabling significant improvements in their performance (Christiano et al., 2017). The method, first showcased by Stiennon et al. (2020) in the context of text-summarization tasks, has since been extended to a range of other applications. In this paradigm, models are fine-tuned based on feedback from human users, thus iteratively aligning the models’ responses more closely with human expectations and preferences. Ouyang et al. (2022) demonstrates that a combination of instruction fine-tuning and RLHF can help fix issues with factuality, toxicity, and helpfulness that cannot be remedied by simply scaling up LLMs. Bai et al. (2022b) partially automates this fine-tuning-plus-RLHF approach by replacing the human-labeled fine-tuningdatawiththemodel’sownself-critiquesandrevisions,andbyreplacinghumanraterswitha --- We examine the influence of the amount of RLHF training for two reasons. First, RLHF [13, 57] is an increasingly popular technique for reducing harmful behaviors in large language models [3, 21, 52]. Some of these models are already deployed [52], so we believe the impact of RLHF deserves further scrutiny. Second, previous work shows that the amount of RLHF training can significantly change metrics on a wide range of personality, political preference, and harm evaluations for a given model size [41]. As a result, it is important to control for the amount of RLHF training in the analysis of our experiments. 3.2 Experiments 3.2.1 Overview We test the effect of natural language instructions on two related but distinct moral phenomena: stereotyping and discrimination. Stereotyping involves the use of generalizations about groups in ways that are often harmful or undesirable.4To measure stereotyping, we use two well-known stereotyping benchmarks, BBQ [40] (§3.2.2) and Windogender [49] (§3.2.3). For discrimination, we focus on whether models make disparate decisions about individuals based on protected characteristics that should have no relevance to the outcome.5 To measure discrimination, we construct a new benchmark to test for the impact of race in a law school course --- model to estimate the eventual performance of a larger RL policy. The slopes of these lines also explain how RLHF training can produce such large effective gains in model size, and for example it explains why the RLHF and context-distilled lines in Figure 1 are roughly parallel. • One can ask a subtle, perhaps ill-defined question about RLHF training – is it teaching the model new skills or simply focusing the model on generating a sub-distribution of existing behaviors . We might attempt to make this distinction sharp by associating the latter class of behaviors with the region where RL reward remains linear inp KL. • To make some bolder guesses – perhaps the linear relation actually provides an upper bound on RL reward, as a function of the KL. One might also attempt to extend the relation further by replacingp KLwith a geodesic length in the Fisher geometry. By making RL learning more predictable and by identifying new quantitative categories of behavior, we might hope to detect unexpected behaviors emerging during RL training. 4.4 Tension Between Helpfulness and Harmlessness in RLHF Training Here we discuss a problem we encountered during RLHF training. At an earlier stage of this project, we found that many RLHF policies were very frequently reproducing the same exaggerated responses to all remotely sensitive questions (e.g. recommending users seek therapy and professional help whenever they ... We get reasonable performance here — notably relevant chunks of text: Document Chunk 0 "enabling significant improvements in their performance" 0 "iteratively aligning the models' responses more closely with human expectations and preferences" 0 "instruction fine-tuning and RLHF can help fix issues with factuality, toxicity, and helpfulness" 1 "increasingly popular technique for reducing harmful behaviors in large language models" The remaining documents and text cover RLHF but don't answer our specific question of "why we would want to do rlhf?". Reranking Responses We will use Cohere's rerank endpoint for reranking. You will need a Cohere API key to use it. With our API key, we authenticate like so: import cohere # init client co = cohere.Client("YOUR_COHERE_API_KEY") Now, we can rerank our results with co.rerank. Let's try increasing the number of results returned by the first-stage retrieval step to a top_k=25 and reranking them all (setting top_n=25) to see what the reordering we get looks like. The reordered results look like so: rerank_docs = co.rerank( query=query, documents=docs.keys(), top_n=25, model="rerank-english-v2.0" ) [docs[doc.document["text"]] for doc in rerank_docs] [0, 23, 14, 3, 12, 6, 9, 8, 1, 17, 7, 21, 2, 16, 10, 20, 18, 22, 24, 13, 19, 4, 15, 11, 5] We still have record 0 at the top — that is great because it contained plenty of relevant information to our query. However, the less relevant documents 1 and 2 have been replaced by documents 23 and 14, respectively. Let's create a function that will allow us to compare original vs. reranked results more quickly. def compare(query: str, top_k: int, top_n: int): # first get vec search results docs = get_docs(query, top_k=top_k) i2doc = {docs[doc]: doc for doc in docs.keys()} # rerank rerank_docs = co.rerank( query=query, documents=docs.keys(), top_n=top_n, model="rerank-english-v2.0" ) original_docs = [] reranked_docs = [] # compare order change for i, doc in enumerate(rerank_docs): rerank_i = docs[doc.document["text"]] print(str(i)+"\t->\t"+str(rerank_i)) if i != rerank_i: reranked_docs.append(f"[{rerank_i}]\n"+doc.document["text"]) original_docs.append(f"[{i}]\n"+i2doc[i]) for orig, rerank in zip(original_docs, reranked_docs): print("ORIGINAL:\n"+orig+"\n\nRERANKED:\n"+rerank+"\n\n---\n") We start with our RLHF query. This time, we do a more standard retrieval-rerank process of retrieving 25 documents (top_k=25) and reranking to the top three documents (top_n=3). compare(query, 25, 3) 0 -> 0 1 -> 23 2 -> 14 ORIGINAL: [1] We examine the influence of the amount of RLHF training for two reasons. First, RLHF [13, 57] is an increasingly popular technique for reducing harmful behaviors in large language models [3, 21, 52]. Some of these models are already deployed [52], so we believe the impact of RLHF deserves further scrutiny. Second, previous work shows that the amount of RLHF training can significantly change metrics on a wide range of personality, political preference, and harm evaluations for a given model size [41]. As a result, it is important to control for the amount of RLHF training in the analysis of our experiments. 3.2 Experiments 3.2.1 Overview We test the effect of natural language instructions on two related but distinct moral phenomena: stereotyping and discrimination. Stereotyping involves the use of generalizations about groups in ways that are often harmful or undesirable.4To measure stereotyping, we use two well-known stereotyping benchmarks, BBQ [40] (§3.2.2) and Windogender [49] (§3.2.3). For discrimination, we focus on whether models make disparate decisions about individuals based on protected characteristics that should have no relevance to the outcome.5 To measure discrimination, we construct a new benchmark to test for the impact of race in a law school course RERANKED: [23] We have shown that it’s possible to use reinforcement learning from human feedback to train language models that act as helpful and harmless assistants. Our RLHF training also improves honesty, though we expect other techniques can do better still. As in other recent works associated with aligning large language models [Stiennon et al., 2020, Thoppilan et al., 2022, Ouyang et al., 2022, Nakano et al., 2021, Menick et al., 2022], RLHF improves helpfulness and harmlessness by a huge margin when compared to simply scaling models up. Our alignment interventions actually enhance the capabilities of large models, and can easily be combined with training for specialized skills (such as coding or summarization) without any degradation in alignment or performance. Models with less than about 10B parameters behave differently, paying an ‘alignment tax’ on their capabilities. This provides an example where models near the state-of-the-art may have been necessary to derive the right lessons from alignment research. The overall picture we seem to find – that large models can learn a wide variety of skills, including alignment, in a mutually compatible way – does not seem very surprising. Behaving in an aligned fashion is just another capability, and many works have shown that larger models are more capable [Kaplan et al., 2020, --- ORIGINAL: [2] model to estimate the eventual performance of a larger RL policy. The slopes of these lines also explain how RLHF training can produce such large effective gains in model size, and for example it explains why the RLHF and context-distilled lines in Figure 1 are roughly parallel. • One can ask a subtle, perhaps ill-defined question about RLHF training – is it teaching the model new skills or simply focusing the model on generating a sub-distribution of existing behaviors . We might attempt to make this distinction sharp by associating the latter class of behaviors with the region where RL reward remains linear inp KL. • To make some bolder guesses – perhaps the linear relation actually provides an upper bound on RL reward, as a function of the KL. One might also attempt to extend the relation further by replacingp KLwith a geodesic length in the Fisher geometry. By making RL learning more predictable and by identifying new quantitative categories of behavior, we might hope to detect unexpected behaviors emerging during RL training. 4.4 Tension Between Helpfulness and Harmlessness in RLHF Training Here we discuss a problem we encountered during RLHF training. At an earlier stage of this project, we found that many RLHF policies were very frequently reproducing the same exaggerated responses to all remotely sensitive questions (e.g. recommending users seek therapy and professional help whenever they RERANKED: [14] the model outputs safe responses, they are often more detailed than what the average annotator writes. Therefore, after gathering only a few thousand supervised demonstrations, we switched entirely to RLHF to teachthemodelhowtowritemorenuancedresponses. ComprehensivetuningwithRLHFhastheadded benefit that it may make the model more robust to jailbreak attempts (Bai et al., 2022a). WeconductRLHFbyfirstcollectinghumanpreferencedataforsafetysimilartoSection3.2.2: annotators writeapromptthattheybelievecanelicitunsafebehavior,andthencomparemultiplemodelresponsesto theprompts,selectingtheresponsethatissafestaccordingtoasetofguidelines. Wethenusethehuman preference data to train a safety reward model (see Section 3.2.2), and also reuse the adversarial prompts to sample from the model during the RLHF stage. BetterLong-TailSafetyRobustnesswithoutHurtingHelpfulness Safetyisinherentlyalong-tailproblem, wherethe challengecomesfrom asmallnumber ofveryspecific cases. Weinvestigatetheimpact ofSafety --- Looking at these, we have dropped the one relevant chunk of text from document 1 and no relevant chunks of text from document 2 — the following relevant pieces of information now replace these: Original Position Rerank Position Chunk 23 1 "train language models that act as helpful and harmless assistants" 23 1 "RLHF training also improves honesty" 23 1 "RLHF improves helpfulness and harmlessness by a huge margin" 23 1 "enhance the capabilities of large models" 14 2 "the model outputs safe responses" 14 2 "often more detailed than what the average annotator writes" 14 2 "RLHF to reach the model how to write more nuanced responses" 14 2 "make the model more robust to jailbreak attempts" We have far more relevant information after reranking. Naturally, this can result in significantly better performance for RAG. It means we maximize relevant information while minimizing noise input into our LLM. Reranking is one of the simplest methods for dramatically improving recall performance in Retrieval Augmented Generation (RAG) or any other retrieval-based pipeline. We've explored why rerankers can provide so much better performance than their embedding model counterparts — and how a two-stage retrieval system allows us to get the best of both, enabling search at scale while maintaining quality performance. References [1] Introducing 100K Context Windows (2023), Anthropic [2] N. Liu, K. Lin, J. Hewitt, A. Paranjape, M. Bevilacqua, F. Petroni, P. Liang, Lost in the Middle: How Language Models Use Long Contexts (2023), [3] N. Reimers, I. Gurevych, Sentence-BERT: Sentence Embeddings using Siamese BERT-Networks (2019), UKP-TUDA Share via: Learn how to build advanced retrieval augmented generation (RAG) pipelines. (series cover image) Retrieval Augmented Generation Chapters Rerankers for RAG Recall vs. Context Windows Power of Rerankers Implementing Two-Stage Retrieval with Reranking References Embedding Models Agent Evaluation © Pinecone Systems, Inc. | San Francisco, CA Pinecone is a registered trademark of Pinecone Systems, Inc. ""
517785c51f19fa87a7d691ad1ec1ef89
{ "intermediate": 0.2631674110889435, "beginner": 0.3816886246204376, "expert": 0.3551439344882965 }
42,710
FIXY ANY ERROS MY CODE IS NOT SENDING ANYTHING TO THE SERVER import requests import time from requests.exceptions import ConnectTimeout from urllib3.exceptions import MaxRetryError # URL url = “https://lucky.mzansigaming.com/store-score” # Headers headers = { ‘accept’: “/”, ‘accept-language’: “en-US,en;q=0.9”, ‘content-type’: “application/json”, ‘sec-ch-ua’: ‘“Chromium”;v=“122”, “Not(A:Brand”;v=“24”, “Google Chrome”;v=“122”’, ‘sec-ch-ua-mobile’: “?1”, ‘sec-ch-ua-platform’: ‘“Android”’, ‘sec-fetch-dest’: “empty”, ‘sec-fetch-mode’: “cors”, ‘sec-fetch-site’: “same-origin”, ‘Referer’: “https://lucky.mzansigaming.com/blue-switcheroo/?unique_id=b325312e-8633-f235-112f-6469607f6e12&game_id=b735f7d9-cc7c-a977-c3d5-65f2ad89f320”, } # JSON Body json_data = { “unique_id”: “b325312e-8633-f235-112f-6469607f6e12”, “game_id”: “b735f7d9-cc7c-a977-c3d5-65f2ad89f320”, “score”: 1 } # Number of times you want to send the request num_times = 10 # Example: Change this to your desired number # Delay between requests (in seconds) delay = 1 # Example: Adjust the delay as needed successful_responses = 0 for i in range(num_times): while True: try: # Send the request response = requests.post(url, headers=headers, json=json_data, timeout=316) # Print the response and increment the successful responses count print(f"Response {successful_responses+1}:\n{response.text}\n") successful_responses += 1 break except ConnectTimeout: print(“Connection timed out. Retrying…”) except MaxRetryError: print(“Max retries exceeded. Retrying…”) except Exception as e: print(f"An error occurred: {e}. Retrying…“) # Delay before sending the next request time.sleep(delay) print(f"Total successful responses: {successful_responses}”)
1b60c51b4942d40f5d6483284bd546e1
{ "intermediate": 0.30545076727867126, "beginner": 0.4812715947628021, "expert": 0.2132776379585266 }
42,711
# Convert 'WeekDate' to datetime format dataset_lowvolume = dataset_lowvolume.with_columns( pl.col("WeekDate").str.strptime(pl.Datetime, "%Y-%m-%d") ) # Group by ‘MaterialID’, ‘SalesOrg’, ‘DistrChan’, 'CL4' and 'WeekDate', then sum 'OrderQuantity' y_cl4 = dataset_lowvolume.groupby(['MaterialID', 'SalesOrg', 'DistrChan', 'CL4', 'WeekDate']).agg( pl.sum("OrderQuantity").alias("OrderQuantity") ) # Sort by 'WeekDate' y_cl4 = y_cl4.sort("WeekDate") # Concatenate ‘MaterialID’, ‘SalesOrg’, ‘DistrChan’, ‘CL4’ to a new column ‘unique_id’ y_cl4 = y_cl4.with_columns( pl.concat_str([pl.col('MaterialID'), pl.col('SalesOrg'), pl.col('DistrChan'), pl.col('CL4')], separator='_').alias('unique_id') ) # Drop the original columns y_cl4 = y_cl4.drop(['MaterialID', 'SalesOrg', 'DistrChan', 'CL4']) # Renaming columns to 'ds' and 'y' to meet the input requirements of the StatsForecast library y_cl4 = y_cl4.rename({'WeekDate': 'ds', 'OrderQuantity': 'y'}) y_cl4.head() ds y unique_id datetime[μs] f64 str 2020-11-30 00:00:00 3.0 "12158538_US01_… 2020-11-30 00:00:00 150.0 "12495546_US01_… 2020-11-30 00:00:00 780.0 "12039064_US05_… 2020-11-30 00:00:00 10.0 "11003273_US03_… 2020-11-30 00:00:00 4.0 "12420671_US01_… cl4 level after aggregating to 4 columns materialID-salesorg-distrchan-cl4. this is the dataset before aggregation dataset_lowvolume.head() shape: (5, 15) MaterialID SalesOrg DistrChan SoldTo DC WeekDate OrderQuantity DeliveryQuantity ParentProductCode PL2 PL3 PL4 PL5 CL4 Item Type i64 str i64 i64 str datetime[μs] f64 f64 i64 str str str str str str 12434031 "US01" 8 6387196 "5583" 2022-03-07 00:00:00 1.0 1.0 12434031 "US6" "US66M" "US66M6MA4" "US66M6MA46MA4N… "6067472" "Low Volume" 12434072 "US01" 8 6465348 "5583" 2022-03-28 00:00:00 1.0 1.0 12434072 "US6" "US66J" "US66J6J24" "US66J6J246J24L… "6067445" "Low Volume" MaterialID: unique ID represents one unique item. · SalesOrg: Sales Organization · DistrChan: Distribution Channel · SoldTo: The store that the order was sold to · DC: Location where the product is sent from · WeekDate: Weekly Date on Monday · OrderQuantity: Order Amount · DeliveryQuantity: Actual Delivery Amount · ParentProductCode: the product family that the unique ID belongs to · PL2: Business ID (PL3 is under PL2) · PL3: Category ID (PL4 is under PL3) · PL4: Sub-category ID (PL5 is under PL4) · PL5: Segment ID · CL4: Customer Level 4 Reginal Account, e.g. Target, Walmart (Sold to is under CL4) this is the description of each column, I want to add these as exogenous variables, PL2, PL3, PL4, PL5, and ParentProductCode: While these product categorization levels may not fully capture the complex seasonality, they could still provide some useful information related to product-specific trends or patterns. adjust my code
aa493713f0e3337141b1c2303f528431
{ "intermediate": 0.25800052285194397, "beginner": 0.4229426383972168, "expert": 0.3190568685531616 }
42,712
Write a code for woth 26 different characters with the English alphabet for me to write in
3e8cf9c6c28e6d0fc87f928d2a25cff5
{ "intermediate": 0.32426586747169495, "beginner": 0.20036174356937408, "expert": 0.47537240386009216 }
42,713
hi
3a6ea1056d8cab4c9f877f168ce3d0be
{ "intermediate": 0.3246487081050873, "beginner": 0.27135494351387024, "expert": 0.40399640798568726 }
42,714
add this and give visual plots of high price and low price here: data_combined[‘High_Price’] = (data_combined[‘Price’] > median_price).astype(int) # Additional segment - Focusing on 2-bedroom units prediction within the ‘data_full’ specifically data_full.dropna(subset=[‘Price’], inplace=True) # Dropping NA values specifically in ‘data_full’ for clear separation of concerns data_2_bed = data_full[data_full[‘Bedroom2’] == 2] # Note: Encoding and imputation steps would be here if new data were filtered X = data_2_bed[features] # Assuming ‘features’ list matches your available columns in ‘data_full’ y = data_2_bed[‘Price’] import pandas as pd from sklearn.model_selection import train_test_split from sklearn.ensemble import RandomForestRegressor, RandomForestClassifier from sklearn.metrics import mean_absolute_error, r2_score, classification_report, f1_score, accuracy_score, roc_curve, auc, confusion_matrix from sklearn.preprocessing import LabelEncoder from sklearn.impute import SimpleImputer import matplotlib.pyplot as plt import seaborn as sns # Load datasets data_less = pd.read_csv(‘MELBOURNE_HOUSE_PRICES_LESS.csv’) data_full = pd.read_csv(‘Melbourne_housing_FULL.csv’) # Merge data based on common columns data_combined = pd.merge(data_less[[‘Suburb’, ‘Rooms’, ‘Type’, ‘Price’]], data_full[[‘Suburb’, ‘Rooms’, ‘Type’, ‘Price’, ‘Distance’, ‘Postcode’, ‘Bathroom’, ‘Car’, ‘Landsize’, ‘BuildingArea’, ‘YearBuilt’]], on=[‘Suburb’, ‘Rooms’, ‘Type’, ‘Price’], how=‘outer’) # Drop rows with missing ‘Price’ values data_combined.dropna(subset=[‘Price’], inplace=True) # Encode categorical variables label_encoder = LabelEncoder() data_combined[‘Suburb’] = label_encoder.fit_transform(data_combined[‘Suburb’]) data_combined[‘Type’] = label_encoder.fit_transform(data_combined[‘Type’]) # Choose features features = [‘Suburb’, ‘Rooms’, ‘Type’, ‘Distance’, ‘Postcode’, ‘Bathroom’, ‘Car’, ‘Landsize’, ‘BuildingArea’, ‘YearBuilt’] X = data_combined[features] y = data_combined[‘Price’] # Split the data X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) # Handle missing values (here using median for simplicity) imputer = SimpleImputer(strategy=‘median’) X_train = imputer.fit_transform(X_train) X_test = imputer.transform(X_test) # Train a RandomForestRegressor model = RandomForestRegressor(n_estimators=100, random_state=42) model.fit(X_train, y_train) # Make predictions predictions = model.predict(X_test) # Evaluate predictions mae = mean_absolute_error(y_test, predictions) r2 = r2_score(y_test, predictions) print(“Mean Absolute Error (MAE):”, mae) print(“R^2 Score:”, r2) # Additional segment - Hypothetical Classification Task based on Median Price median_price = data_combined[‘Price’].median() data_combined[‘High_Price’] = (data_combined[‘Price’] > median_price).astype(int) y_class = data_combined[‘High_Price’] X_train_class, X_test_class, y_train_class, y_test_class = train_test_split(X, y_class, test_size=0.2, random_state=42) X_train_class = imputer.fit_transform(X_train_class) X_test_class = imputer.transform(X_test_class) # Train a RandomForestClassifier classifier = RandomForestClassifier(n_estimators=100, random_state=42) classifier.fit(X_train_class, y_train_class) # Make predictions predictions_class = classifier.predict(X_test_class) predictions_proba = classifier.predict_proba(X_test_class)[:,1] # Classification metrics print(classification_report(y_test_class, predictions_class)) print(“F1 Score:”, f1_score(y_test_class, predictions_class)) print(“Accuracy Score:”, accuracy_score(y_test_class, predictions_class)) # ROC Curve fpr, tpr, thresholds = roc_curve(y_test_class, predictions_proba) roc_auc = auc(fpr, tpr) plt.figure() plt.plot(fpr, tpr, color=‘darkorange’, lw=2, label=‘ROC curve (area = %0.2f)’ % roc_auc) plt.plot([0, 1], [0, 1], color=‘navy’, lw=2, linestyle=‘–’) plt.xlim([0.0, 1.0]) plt.ylim([0.0, 1.05]) plt.xlabel(‘False Positive Rate’) plt.ylabel(‘True Positive Rate’) plt.title(‘Receiver Operating Characteristic’) plt.legend(loc=“lower right”) plt.show() # Confusion Matrix Plot conf_mat = confusion_matrix(y_test_class, predictions_class) sns.heatmap(conf_mat, annot=True, fmt=“d”, cmap=“Blues”) plt.title(‘Confusion Matrix’) plt.xlabel(‘Predicted’) plt.ylabel(‘Actual’) plt.show() # Density Plots for Predicted Probabilities sns.kdeplot(predictions_proba[y_test_class == 0], label=‘Not High Price’, shade=True) sns.kdeplot(predictions_proba[y_test_class == 1], label=‘High Price’, shade=True) plt.title(‘Density plot of Predicted Probabilities’) plt.xlabel(‘Probability’) plt.ylabel(‘Density’) plt.legend() plt.show()
31274ec278da73bbec59dffe9d86095e
{ "intermediate": 0.35461440682411194, "beginner": 0.377726674079895, "expert": 0.26765891909599304 }
42,715
{ "LoRA_type": "Standard", "LyCORIS_preset": "full", "adaptive_noise_scale": 0, "additional_parameters": "--network_train_unet_only", "block_alphas": "", "block_dims": "", "block_lr_zero_threshold": "", "bucket_no_upscale": true, "bucket_reso_steps": 32, "cache_latents": true, "cache_latents_to_disk": true, "caption_dropout_every_n_epochs": 0.0, "caption_dropout_rate": 0, "caption_extension": ".txt", "clip_skip": "1", "color_aug": false, "constrain": 0.0, "conv_alpha": 64, "conv_block_alphas": "", "conv_block_dims": "", "conv_dim": 64, "debiased_estimation_loss": true, "decompose_both": false, "dim_from_weights": false, "down_lr_weight": "", "enable_bucket": false, "epoch": 1, "factor": -1, "flip_aug": false, "fp8_base": false, "full_bf16": true, "full_fp16": false, "gpu_ids": "", "gradient_accumulation_steps": 26, "gradient_checkpointing": true, "keep_tokens": 0, "learning_rate": 0.9, "logging_dir": "X:/katrinTest-test2/KatrinTest0003_SGDNesterov/log", "lora_network_weights": "", "lr_scheduler": "cosine", "lr_scheduler_args": "", "lr_scheduler_num_cycles": "1", "lr_scheduler_power": "", "lr_warmup": 0, "max_bucket_reso": 2048, "max_data_loader_n_workers": "1", "max_grad_norm": 1, "max_resolution": "1024,1024", "max_timestep": 1000, "max_token_length": "150", "max_train_epochs": "1500", "max_train_steps": "", "mem_eff_attn": false, "mid_lr_weight": "", "min_bucket_reso": 256, "min_snr_gamma": 5, "min_timestep": 0, "mixed_precision": "bf16", "model_list": "custom", "module_dropout": 0, "multi_gpu": false, "multires_noise_discount": 0.2, "multires_noise_iterations": 8, "network_alpha": 128, "network_dim": 128, "network_dropout": 0, "noise_offset": 0.0357, "noise_offset_type": "Original", "num_cpu_threads_per_process": 2, "num_machines": 1, "num_processes": 1, "optimizer": "SGDNesterov", "optimizer_args": "momentum=0.8 weight_decay=0.001 ", "output_dir": "X:/katrinTest-test2/KatrinTest0003_SGDNesterov/out0002", "output_name": "SDXL_Kohya_SGDNesterov", "persistent_data_loader_workers": true, "pretrained_model_name_or_path": "stabilityai/stable-diffusion-xl-base-1.0", "prior_loss_weight": 1.0, "random_crop": false, "rank_dropout": 0, "rank_dropout_scale": false, "reg_data_dir": "", "rescaled": false, "resume": "", "sample_every_n_epochs": 10, "sample_every_n_steps": 0, "sample_prompts": "katrintest standing topless in a desert,face closeup, looking at camera,nude, 4k, --w 1024, --h 1024, --l 7, --d 7777, --s 30", "sample_sampler": "euler_a", "save_every_n_epochs": 10, "save_every_n_steps": 0, "save_last_n_steps": 0, "save_last_n_steps_state": 0, "save_model_as": "safetensors", "save_precision": "fp16", "save_state": false, "scale_v_pred_loss_like_noise_pred": false, "scale_weight_norms": 1, "sdxl": true, "sdxl_cache_text_encoder_outputs": false, "sdxl_no_half_vae": false, "seed": "1337", "shuffle_caption": true, "stop_text_encoder_training": 0, "text_encoder_lr": 0.9, "train_batch_size": 1, "train_data_dir": "X:/katrinTest-test2/KatrinTest0000/img", "train_norm": false, "train_on_input": true, "training_comment": "trigger: katrintest", "unet_lr": 0.9, "unit": 1, "up_lr_weight": "", "use_cp": false, "use_scalar": false, "use_tucker": false, "use_wandb": false, "v2": false, "v_parameterization": false, "v_pred_like_loss": 0, "vae": "", "vae_batch_size": 0, "wandb_api_key": "", "weighted_captions": false, "xformers": "none" } can you tell me why this sgdnesterov settings dont show any good results?
8c5e121988c1b31850fee9762be12be7
{ "intermediate": 0.3198249042034149, "beginner": 0.3893689215183258, "expert": 0.2908061742782593 }
42,716
Hello
13c675f4194c20d56214442e0e2f8421
{ "intermediate": 0.3123404085636139, "beginner": 0.2729349136352539, "expert": 0.4147246778011322 }
42,717
Add federated learning to my code below of using differential prinvacy to train gan opt = parser.parse_args() try: os.makedirs(opt.outf) except OSError: pass if opt.manualSeed is None: opt.manualSeed = random.randint(1, 10000) print("Random Seed: ", opt.manualSeed) random.seed(opt.manualSeed) torch.manual_seed(opt.manualSeed) cudnn.benchmark = True try: dataset = dset.MNIST( root=opt.data_root, download=True, transform=transforms.Compose( [ transforms.Resize(opt.imageSize), transforms.ToTensor(), transforms.Normalize((0.5,), (0.5,)), ] ), ) idx = dataset.targets == opt.target_digit dataset.targets = dataset.targets[idx] dataset.data = dataset.data[idx] nc = 1 except ValueError: print("Cannot load dataset") dataloader = torch.utils.data.DataLoader( dataset, num_workers=int(opt.workers), batch_size=opt.batch_size, ) device = torch.device(opt.device) ngpu = int(opt.ngpu) nz = int(opt.nz) ngf = int(opt.ngf) ndf = int(opt.ndf) # custom weights initialization called on netG and netD def weights_init(m): classname = m.__class__.__name__ if classname.find("Conv") != -1: m.weight.data.normal_(0.0, 0.02) elif classname.find("BatchNorm") != -1: m.weight.data.normal_(1.0, 0.02) m.bias.data.fill_(0) class Generator(nn.Module): def __init__(self, ngpu): super(Generator, self).__init__() self.ngpu = ngpu self.main = nn.Sequential( # input is Z, going into a convolution nn.ConvTranspose2d(nz, ngf * 8, 4, 1, 0, bias=False), nn.GroupNorm(min(32, ndf * 8), ndf * 8), nn.ReLU(True), # state size. (ngf*8) x 4 x 4 nn.ConvTranspose2d(ngf * 8, ngf * 4, 4, 2, 1, bias=False), nn.GroupNorm(min(32, ndf * 4), ndf * 4), nn.ReLU(True), # state size. (ngf*4) x 8 x 8 nn.ConvTranspose2d(ngf * 4, ngf * 2, 4, 2, 1, bias=False), nn.GroupNorm(min(32, ndf * 2), ndf * 2), nn.ReLU(True), # state size. (ngf*2) x 16 x 16 nn.ConvTranspose2d(ngf * 2, ngf, 4, 2, 1, bias=False), nn.GroupNorm(min(32, ndf), ndf), nn.ReLU(True), # state size. (ngf) x 32 x 32 nn.ConvTranspose2d(ngf, nc, 4, 2, 1, bias=False), nn.Tanh(), # state size. (nc) x 64 x 64 ) def forward(self, input): if input.is_cuda and self.ngpu > 1: output = nn.parallel.data_parallel(self.main, input, range(self.ngpu)) else: output = self.main(input) return output netG = Generator(ngpu) netG = netG.to(device) netG.apply(weights_init) if opt.netG != "": netG.load_state_dict(torch.load(opt.netG)) class Discriminator(nn.Module): def __init__(self, ngpu): super(Discriminator, self).__init__() self.ngpu = ngpu self.main = nn.Sequential( # input is (nc) x 64 x 64 nn.Conv2d(nc, ndf, 4, 2, 1, bias=False), nn.LeakyReLU(0.2, inplace=True), # state size. (ndf) x 32 x 32 nn.Conv2d(ndf, ndf * 2, 4, 2, 1, bias=False), nn.GroupNorm(min(32, ndf * 2), ndf * 2), nn.LeakyReLU(0.2, inplace=True), # state size. (ndf*2) x 16 x 16 nn.Conv2d(ndf * 2, ndf * 4, 4, 2, 1, bias=False), nn.GroupNorm(min(32, ndf * 4), ndf * 4), nn.LeakyReLU(0.2, inplace=True), # state size. (ndf*4) x 8 x 8 nn.Conv2d(ndf * 4, ndf * 8, 4, 2, 1, bias=False), nn.GroupNorm(min(32, ndf * 8), ndf * 8), nn.LeakyReLU(0.2, inplace=True), # state size. (ndf*8) x 4 x 4 nn.Conv2d(ndf * 8, 1, 4, 1, 0, bias=False), nn.Sigmoid(), ) def forward(self, input): if input.is_cuda and self.ngpu > 1: output = nn.parallel.data_parallel(self.main, input, range(self.ngpu)) else: output = self.main(input) return output.view(-1, 1).squeeze(1) netD = Discriminator(ngpu) netD = netD.to(device) netD.apply(weights_init) if opt.netD != "": netD.load_state_dict(torch.load(opt.netD)) criterion = nn.BCELoss() FIXED_NOISE = torch.randn(opt.batch_size, nz, 1, 1, device=device) REAL_LABEL = 1.0 FAKE_LABEL = 0.0 # setup optimizer optimizerD = optim.Adam(netD.parameters(), lr=opt.lr, betas=(opt.beta1, 0.999)) if not opt.disable_dp: privacy_engine = PrivacyEngine(secure_mode=opt.secure_rng) netD, optimizerD, dataloader = privacy_engine.make_private( module=netD, optimizer=optimizerD, data_loader=dataloader, noise_multiplier=opt.sigma, max_grad_norm=opt.max_per_sample_grad_norm, ) optimizerG = optim.Adam(netG.parameters(), lr=opt.lr, betas=(opt.beta1, 0.999)) for epoch in range(opt.epochs): data_bar = tqdm(dataloader) for i, data in enumerate(data_bar, 0): ############################ # (1) Update D network: maximize log(D(x)) + log(1 - D(G(z))) ########################### optimizerD.zero_grad(set_to_none=True) real_data = data[0].to(device) batch_size = real_data.size(0) # train with real label_true = torch.full((batch_size,), REAL_LABEL, device=device) output = netD(real_data) errD_real = criterion(output, label_true) D_x = output.mean().item() # train with fake noise = torch.randn(batch_size, nz, 1, 1, device=device) fake = netG(noise) label_fake = torch.full((batch_size,), FAKE_LABEL, device=device) output = netD(fake.detach()) errD_fake = criterion(output, label_fake) # below, you actually have two backward passes happening under the hood # which opacus happens to treat as a recursive network # and therefore doesn't add extra noise for the fake samples # noise for fake samples would be unnecesary to preserve privacy errD = errD_real + errD_fake errD.backward() optimizerD.step() optimizerD.zero_grad(set_to_none=True) D_G_z1 = output.mean().item() ############################ # (2) Update G network: maximize log(D(G(z))) ########################### optimizerG.zero_grad() label_g = torch.full((batch_size,), REAL_LABEL, device=device) output_g = netD(fake) errG = criterion(output_g, label_g) errG.backward() D_G_z2 = output_g.mean().item() optimizerG.step() if not opt.disable_dp: epsilon = privacy_engine.accountant.get_epsilon(delta=opt.delta) data_bar.set_description( f"epoch: {epoch}, Loss_D: {errD.item()} " f"Loss_G: {errG.item()} D(x): {D_x} " f"D(G(z)): {D_G_z1}/{D_G_z2}" "(ε = %.2f, δ = %.2f)" % (epsilon, opt.delta) ) else: data_bar.set_description( f"epoch: {epoch}, Loss_D: {errD.item()} " f"Loss_G: {errG.item()} D(x): {D_x} " f"D(G(z)): {D_G_z1}/{D_G_z2}" ) if i % 100 == 0: vutils.save_image( real_data, "%s/real_samples.png" % opt.outf, normalize=True ) fake = netG(FIXED_NOISE) vutils.save_image( fake.detach(), "%s/fake_samples_epoch_%03d.png" % (opt.outf, epoch), normalize=True, ) # do checkpointing torch.save(netG.state_dict(), "%s/netG_epoch_%d.pth" % (opt.outf, epoch)) torch.save(netD.state_dict(), "%s/netD_epoch_%d.pth" % (opt.outf, epoch))
d02810be6757731f1efcd6d29d4df55d
{ "intermediate": 0.385297030210495, "beginner": 0.3012516498565674, "expert": 0.3134513199329376 }
42,718
Create a home page for the music midi samples
6790053cf282cc76046f997ceaee4894
{ "intermediate": 0.36345645785331726, "beginner": 0.3011043965816498, "expert": 0.33543920516967773 }
42,719
“Coinbase” can’t be opened because Security Policy is set to Permissive Security. How do I bypass this? I need permissive security to run Asahi linux
0afb1a1c7c7a70dab7a48e07fd265238
{ "intermediate": 0.4417804777622223, "beginner": 0.27585166692733765, "expert": 0.28236791491508484 }
42,720
hi
795fe8519753a266faf5e24de4263ea9
{ "intermediate": 0.3246487081050873, "beginner": 0.27135494351387024, "expert": 0.40399640798568726 }
42,721
hello , kindly write a code in python language for a telegram bot that can extract or convert .txt files containing these types of links for example (https://videocdn.adda247.com/GS_SPECIAL_24/GEOGRAPHY/4Earth_Structure_And_Related_Theories/hls/B8SK9A2S14SMA0TJFKME/masterpl.m3u8 ) , (https://cpvod.testbook.com/643851c238a3dd0bd9794dc5/playlist.m3u8) and ( https://d26g5bnklkwsh4.cloudfront.net/062645f7-838b-436e-9829-558d8667e718/master.m3u8 ) and can be deployed on heroku . thus creating a github repository
e308d57e92371926202aaf6c87c54768
{ "intermediate": 0.44903814792633057, "beginner": 0.24830181896686554, "expert": 0.3026599884033203 }
42,722
hello , kindly write a code in python language for a telegram bot that can extract or convert .txt files containing these types of links for example (https://videocdn.adda247.com/GS_SPECIAL_24/GEOGRAPHY/4Earth_Structure_And_Related_Theories/hls/B8SK9A2S14SMA0TJFKME/masterpl.m3u8 ) , (https://cpvod.testbook.com/643851c238a3dd0bd9794dc5/playlist.m3u8) and ( https://d26g5bnklkwsh4.cloudfront.net/062645f7-838b-436e-9829-558d8667e718/master.m3u8 ) and can be deployed on heroku .
5a40a8d387b83a10278ab3e26b0e115e
{ "intermediate": 0.39906495809555054, "beginner": 0.2871902585029602, "expert": 0.31374478340148926 }
42,723
class Bot(): def Message(self, text, files): ... some code.... message.ip = get_ip() bot1 = Bot() bot1.Message(text, files) bot1.Message.ip why last line doesnt work?
f5a05a80a71aeae2a450ad09ac55c0e1
{ "intermediate": 0.43477919697761536, "beginner": 0.3660086393356323, "expert": 0.1992122232913971 }
42,724
kindly write a code in python language for a telegram bot that can extract or convert .txt files containing these types of links for example (https://videocdn.adda247.com/GS_SPECIAL_24/GEOGRAPHY/4Earth_Structure_And_Related_Theories/hls/B8SK9A2S14SMA0TJFKME/masterpl.m3u8 ) , (https://cpvod.testbook.com/643851c238a3dd0bd9794dc5/playlist.m3u8) and ( https://d26g5bnklkwsh4.cloudfront.net/062645f7-838b-436e-9829-558d8667e718/master.m3u8 ) and can be deployed on heroku . take help from this code import os import re import sys import json import time import asyncio import requests import subprocess import core as helper from utils import progress_bar from vars import api_id, api_hash, bot_token from aiohttp import ClientSession from pyromod import listen from subprocess import getstatusoutput from pyrogram import Client, filters from pyrogram.types import Message from pyrogram.errors import FloodWait from pyrogram.errors.exceptions.bad_request_400 import StickerEmojiInvalid from pyrogram.types.messages_and_media import message from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup bot = Client( "bot", api_id=api_id, api_hash=api_hash, bot_token=bot_token) @bot.on_message(filters.command(["start"])) async def account_login(bot: Client, m: Message): editable = await m.reply_text("Hi!\n\nGive /txt Command to Downlaod From a Text file.\n") @bot.on_message(filters.command("restart")) async def restart_handler(_, m): await m.reply_text("**Restarted**🚦", True) os.execl(sys.executable, sys.executable, *sys.argv) @bot.on_message(filters.command(["txt"])) async def account_login(bot: Client, m: Message): editable = await m.reply_text('Hi\n\nTO download a test file send here » ') input: Message = await bot.listen(editable.chat.id) x = await input.download() await input.delete(True) path = f"./downloads/{m.chat.id}" try: with open(x, "r") as f: content = f.read() content = content.split("\n") links = [] for i in content: links.append(i.split("://", 1)) os.remove(x) # print(len(links) except: await m.reply_text("Invalid file input.") os.remove(x) return await editable.edit(f"Total links found are **{len(links)}**\n\nSend From where you want to download initial is **1**") input0: Message = await bot.listen(editable.chat.id) raw_text = input0.text await input0.delete(True) await editable.edit("**Enter Batch Name**") input1: Message = await bot.listen(editable.chat.id) raw_text0 = input1.text await input1.delete(True) await editable.edit("**Enter resolution**") input2: Message = await bot.listen(editable.chat.id) raw_text2 = input2.text await input2.delete(True) try: if raw_text2 == "144": res = "256x144" elif raw_text2 == "240": res = "426x240" elif raw_text2 == "360": res = "640x360" elif raw_text2 == "480": res = "854x480" elif raw_text2 == "720": res = "1280x720" elif raw_text2 == "1080": res = "1920x1080" else: res = "UN" except Exception: res = "UN" await editable.edit("Enter A Captio to add Otherwise send **no**") input3: Message = await bot.listen(editable.chat.id) raw_text3 = input3.text await input3.delete(True) highlighter = f"️ " if raw_text3 == 'no': MR = highlighter else: MR = raw_text3 await editable.edit("Now send the **Thumb url**\nEg »
b76498fcca6b09d6b147abc37a7cd231
{ "intermediate": 0.3062097132205963, "beginner": 0.47895461320877075, "expert": 0.21483570337295532 }
42,725
class Bot(): def __init__(self, bot_number): self.bot_number = bot_number def Message(self, text): Message.text_sent = text def print_sent_post(self): print(Message.sent_post) bot1 = Bot('1') bot1.Message('abc') print(bot1.Message.text_sent) why am i getting name 'Message' is not defined error?
e4d7b8b2c46a503dea886929257c5ab2
{ "intermediate": 0.2594811022281647, "beginner": 0.5229625701904297, "expert": 0.21755631268024445 }
42,726
Explain the following like i am a layperson: ""License: CC BY 4.0 arXiv:2401.18059v1 [cs.CL] 31 Jan 2024 RAPTOR: Recursive Abstractive Processing for Tree-Organized Retrieval Parth Sarthi, Salman Abdullah, Aditi Tuli, Shubh Khanna, Anna Goldie, Christopher D. Manning Stanford University <PRESIDIO_ANONYMIZED_EMAIL_ADDRESS> Abstract Retrieval-augmented language models can better adapt to changes in world state and incorporate long-tail knowledge. However, most existing methods retrieve only short contiguous chunks from a retrieval corpus, limiting holistic understanding of the overall document context. We introduce the novel approach of recursively embedding, clustering, and summarizing chunks of text, constructing a tree with differing levels of summarization from the bottom up. At inference time, our RAPTOR model retrieves from this tree, integrating information across lengthy documents at different levels of abstraction. Controlled experiments show that retrieval with recursive summaries offers significant improvements over traditional retrieval-augmented LMs on several tasks. On question-answering tasks that involve complex, multi-step reasoning, we show state-of-the-art results; for example, by coupling RAPTOR retrieval with the use of GPT-4, we can improve the best performance on the QuALITY benchmark by 20% in absolute accuracy. 1Introduction Large Language Models (LLMs) have emerged as transformative tools showing impressive performance on many tasks. With the growing size of LLMs, they can serve standalone as very effective knowledge stores, with facts encoded within their parameters (Petroni et al., 2019; Jiang et al., 2020; Talmor et al., 2020; Rae et al., 2021; Hoffmann et al., 2022; Chowdhery et al., 2022; Bubeck et al., 2023; Kandpal et al., 2023) and models can be further improved with fine-tuning on downstream tasks (Roberts et al., 2020). Nevertheless, even a large model does not contain sufficient domain-specific knowledge for particular tasks and the world continues to change, invalidating facts in the LLM. Updating the knowledge of these models through additional fine-tuning or editing is difficult, particularly when dealing with vast text corpora (Lewis et al., 2020; Mitchell et al., 2022). An alternative approach, pioneered in open domain question answering systems (Chen et al., 2017; Yu et al., 2018), is to index large quantities of text, after splitting it into chunks (paragraphs), in a separate information retrieval system. Retrieved information is then presented to the LLM along with the question as context (“retrieval augmentation”, Lewis et al., 2020; Izacard et al., 2022; Min et al., 2023; Ram et al., 2023), making it easy to provide a system with current knowledge particular to some domain and enabling easy interpretability and provenance tracking, whereas the parametric knowledge of LLMs is opaque and difficult to trace back to its source (Akyurek et al., 2022). Refer to caption Figure 1:Tree construction process: RAPTOR recursively clusters chunks of text based on their vector embeddings and generates text summaries of those clusters, constructing a tree from the bottom up. Nodes clustered together are siblings; a parent node contains the text summary of that cluster. Nevertheless, existing retrieval-augmented approaches also have flaws. The one we tackle is that most existing methods retrieve only a few short, contiguous text chunks, which limits their ability to represent and leverage large-scale discourse structure. This is particularly relevant for thematic questions that require integrating knowledge from multiple parts of a text, such as understanding an entire book, as in the NarrativeQA dataset (Kočiskỳ et al., 2018). Consider the fairy tale of Cinderella, and the question “How did Cinderella reach her happy ending?”. The top- � retrieved short contiguous texts will not contain enough context to answer the question. To address this, we design an indexing and retrieval system that uses a tree structure to capture both high-level and low-level details about a text. As shown in Figure 1, our system, RAPTOR, clusters chunks of text, generates text summaries of those clusters, and then repeats, generating a tree from the bottom up. This structure enables RAPTOR to load into an LLM’s context chunks representing the text at different levels so that it can effectively and efficiently answer questions at different levels. Our main contribution is the idea of using text summarization to allow retrieval augmentation of context at different scales, and to show its effectiveness in experiments on collections of long documents. Controlled experiments with three language models (UnifiedQA (Khashabi et al., 2020), GPT-3 (Brown et al., 2020) and GPT-4 (OpenAI, 2023)) show that RAPTOR outperforms current retrieval augmentation. Moreover, RAPTOR coupled with GPT-4, and sometimes even with UnifiedQA, gives new state-of-the-art results on three QA tasks: free text response questions on books and movies (NarrativeQA, Kočiskỳ et al. 2018), full-text NLP papers (QASPER, Dasigi et al. 2021), and multiple-choice questions based on medium-length passages (QuALITY, Pang et al. 2022).1 2Related Work Why Retrieval? Recent advances in hardware and algorithms have indeed expanded the context lengths that models can handle, leading to questions about the need for retrieval systems (Dai et al., 2019; Dao et al., 2022; Liu et al., 2023). However, as Liu et al. (2023) and Sun et al. (2021) have noted, models tend to underutilize long-range context and see diminishing performance as context length increases, especially when pertinent information is embedded within a lengthy context. Moreover, practically, use of long contexts is expensive and slow. This suggests that selecting the most relevant information for knowledge-intensive tasks is still crucial. Retrieval Methods Retrieval-augmented language models (RALMs) have seen improvements in various components: the retriever, the reader, and end-to-end system training. Retrieval methods have transitioned from traditional term-based techniques like TF-IDF (Spärck Jones, 1972) and BM25 (Robertson et al., 1995; Roberts et al., 2020) to deep learning–based strategies (Karpukhin et al., 2020; Khattab & Zaharia, 2020; Sachan et al., 2023). Some recent work proposes using large language models as retrievers due to their ability to memorize extensive knowledge (Yu et al., 2022; Sun et al., 2022). Research on the reader component includes Fusion-in-Decoder (FiD) (Izacard & Grave, 2022), which employs both DPR and BM25 for retrieval and processes passages independently in the encoder and RETRO (Borgeaud et al., 2022; Wang et al., 2023), which utilizes cross-chunked attention and chunkwise retrieval to generate text grounded on retrieved context. End-to-end system training work includes Atlas (Izacard et al., 2022), which fine-tunes an encoder-decoder model in conjunction with the retriever; REALM (Guu et al., 2020), a bidirectional, masked LM fine-tuned for open-domain question answering; and RAG (Retrieval-Augmented Generation) (Lewis et al., 2020), which integrates pre-trained sequence-to-sequence models with a neural retriever. Min et al. (2021) introduced Joint Passage Retrieval (JPR) model which uses a tree-decoding algorithm to handle passage diversity and relevance in multi-answer retrieval. Dense Hierarchical Retrieval (DHR) and Hybrid Hierarchical Retrieval (HHR) represent advancements in retrieval accuracy by combining document and passage level retrievals and integrating sparse and dense retrieval methods, respectively (Liu et al., 2021; Arivazhagan et al., 2023). Despite a diversity in methods, the retrieving components of models predominantly rely on standard approaches, i.e., chunking corpora and encoding with BERT-based retrievers. Although this approach is widely adopted, Nair et al. (2023) highlights a potential shortcoming: contiguous segmentation might not capture the complete semantic depth of the text. Reading extracted snippets from technical or scientific documents may lack important context making them difficult to read or even misleading. (Cohan & Goharian, 2017; Newman et al., 2023; Zhang et al., 2023). Recursive summarization as Context Summarization techniques provide a condensed view of documents, enabling more focused engagement with the content (Angelidis & Lapata, 2018). The summarization/snippet model by Gao et al. (2023) uses summarizations and snippets of passages, which improves correctness on most datasets but can sometimes be a lossy means of compression. The recursive-abstractive summarization model by Wu et al. (2021) employs task decomposition to summarize smaller text chunks, which are later integrated to form summaries of larger sections. While this method is effective for capturing broader themes, it can miss granular details. LlamaIndex (Liu, 2022) mitigates this issue by similarly summarizing adjacent text chunks but also retaining intermediate nodes thus storing varying levels of detail, keeping granular details. However, both methods, due to their reliance on adjacency for grouping or summarizing adjacent nodes, may still overlook distant interdependencies within the text, which we can find and group with RAPTOR. 3Methods Overview of RAPTOR Building on the idea that long texts often present subtopics and hierarchical structures (Cao & Wang, 2022; Dong et al., 2023b), RAPTOR addresses the issue of semantic depth and connection in reading by building a recursive tree structure that balances broader thematic comprehension with granular details and which allows nodes to be grouped based on semantic similarity not just order in the text. Construction of the RAPTOR tree begins with segmenting the retrieval corpus into short, contiguous texts of length 100, similar to traditional retrieval augmentation techniques. If a sentence exceeds the 100-token limit, we move the entire sentence to the next chunk, rather than cutting it mid-sentence. This preserves the contextual and semantic coherence of the text within each chunk. These texts are then embedded using SBERT, a BERT-based encoder (multi-qa-mpnet-base-cos-v1) (Reimers & Gurevych, 2019). The chunks and their corresponding SBERT embeddings form the leaf nodes of our tree structure. To group similar text chunks, we employ a clustering algorithm. Once clustered, a Language Model is used to summarize the grouped texts. These summarized texts are then re-embedded, and the cycle of embedding, clustering, and summarization continues until further clustering becomes infeasible, resulting in a structured, multi-layered tree representation of the original documents. An important aspect of RAPTOR is its computational efficiency. The system scales linearly in terms of both build time and token expenditure, making it suitable for processing large and complex corpora. For a comprehensive discussion on RAPTOR’s scalability, please refer to the Appendix A. For querying within this tree, we introduce two distinct strategies: tree traversal and collapsed tree. The tree traversal method traverses the tree layer-by-layer, pruning and selecting the most relevant nodes at each level. The collapsed tree method evaluates nodes collectively across all layers to find the most relevant ones. Clustering Algorithm Clustering plays a key role in building the RAPTOR tree, organizing text segments into cohesive groups. This step groups related content together, which helps the subsequent retrieval process. One of the unique aspects of our clustering approach is the use of soft clustering, where nodes can belong to multiple clusters without requiring a fixed number of clusters. This flexibility is essential because individual text segments often contain information relevant to various topics, thereby warranting their inclusion in multiple summaries. Our clustering algorithm is based on Gaussian Mixture Models (GMMs), an approach that offers both flexibility and a probabilistic framework. GMMs assume that data points are generated from a mixture of several Gaussian distributions. Given a set of � text segments, each represented as a � -dimensional dense vector embedding, the likelihood of a text vector, 𝐱 , given its membership in the � � ⁢ ℎ Gaussian distribution, is denoted by � ⁢ ( 𝐱 | � ) = 𝒩 ⁢ ( 𝐱 ; � � , 𝚺 � ) . The overall probability distribution is a weighted combination � ⁢ ( 𝐱 ) = ∑ � = 1 � � � ⁢ 𝒩 ⁢ ( 𝐱 ; � � , 𝚺 � ) , where � � signifies the mixture weight for the � th Gaussian distribution. The high dimensionality of vector embeddings presents a challenge for traditional GMMs, as distance metrics may behave poorly when used to measure similarity in high-dimensional spaces (Aggarwal et al., 2001). To mitigate this, we employ Uniform Manifold Approximation and Projection (UMAP), a manifold learning technique for dimensionality reduction (McInnes et al., 2018). The number of nearest neighbors parameter, � ⁢ _ ⁢ � ⁢ � ⁢ � ⁢ � ⁢ ℎ ⁢ � ⁢ � ⁢ � ⁢ � , in UMAP determines the balance between the preservation of local and global structures. Our algorithm varies � ⁢ _ ⁢ � ⁢ � ⁢ � ⁢ � ⁢ ℎ ⁢ � ⁢ � ⁢ � ⁢ � to create a hierarchical clustering structure: it first identifies global clusters and then performs local clustering within these global clusters. This two-step clustering process captures a broad spectrum of relationships among the text data, from broad themes to specific details. Should a local cluster’s combined context ever exceed the summarization model’s token threshold, our algorithm recursively applies clustering within the cluster, ensuring that the context remains within the token threshold. To determine the optimal number of clusters, we employ the Bayesian Information Criterion (BIC) for model selection. BIC not only penalizes model complexity but also rewards goodness of fit (Schwarz, 1978). The BIC for a given GMM is � ⁢ � ⁢ � = ln ⁡ ( � ) ⁢ � − 2 ⁢ ln ⁡ ( � ^ ) , where � is the number of text segments (or data points), � is the number of model parameters, and � ^ is the maximized value of the likelihood function of the model. In the context of GMM, the number of parameters � is a function of the dimensionality of the input vectors and the number of clusters. With the optimal number of clusters determined by BIC, the Expectation-Maximization algorithm is then used to estimate the GMM parameters, namely the means, covariances, and mixture weights. While the Gaussian assumption in GMMs may not perfectly align with the nature of text data, which often exhibits a sparse and skewed distribution, our empirical observations suggest that it offers an effective model for our purpose. We run an ablation comparing GMM Clustering with summarizing contiguous chunks and provide details in Appendix B. Model-Based Summarization After clustering the nodes using Gaussian Mixture Models, the nodes in each cluster are sent to a language model for summarization. This step allows the model to transform large chunks of text into concise, coherent summaries of the selected nodes. For our experiments, we use gpt-3.5-turbo to generate the summaries. The summarization step condenses the potentially large volume of retrieved information into a manageable size. We provide statistics on the compression due to the summarization in Appendix C and the prompt used for summarization in Appendix D. While the summarization model generally produces reliable summaries, a focused annotation study revealed that about 4% of the summaries contained minor hallucinations. These did not propagate to parent nodes and had no discernible impact on question-answering tasks. For an in-depth analysis of hallucinations, refer to the appendix E. Refer to caption Figure 2:Illustration of the tree traversal and collapsed tree retrieval mechanisms. Tree traversal starts at the root level of the tree and retrieves the top- � (here, top- 1 ) node(s) based on cosine similarity to the query vector. At each level, it retrieves the top- � node(s) from the child nodes of the previous layer’s top- � . Collapsed tree collapses the tree into a single layer and retrieves nodes until a threshold number of tokens is reached, based on cosine similarity to the query vector. The nodes on which cosine similarity search is performed are highlighted in both illustrations. Querying In this section, we elaborate on the two querying mechanisms employed by RAPTOR: tree traversal and collapsed tree. These methods offer unique ways of traversing the multi-layered RAPTOR tree to retrieve relevant information, each with its own advantages and trade-offs. We provide the pseudocode of both methods in Appendix F. Note that we embed all nodes using SBERT. The tree traversal method first selects the top-k most relevant root nodes based on their cosine similarity to the query embedding. The children of these selected nodes are considered at the next layer and the top-k nodes are selected from this pool again based on their cosine similarity to the query vector. This process is repeated until we reach the leaf nodes. Finally, the text from all selected nodes is concatenated to form the retrieved context. The algorithm’s steps are outlined below: 1. Start at the root layer of the RAPTOR tree. Compute the cosine similarity between the query embedding and the embeddings of all nodes present at this initial layer. 2. Choose the top- � nodes based on the highest cosine similarity scores, forming the set � 1 . 3. Proceed to the child nodes of the elements in set � 1 . Compute the cosine similarity between the query vector and the vector embeddings of these child nodes. 4. Select the top � child nodes with the highest cosine similarity scores to the query, forming the set � 2 . 5. Continue this process recursively for � layers, producing sets � 1 , � 2 , … , � � . 6. Concatenate sets � 1 through � � to assemble the relevant context to the query. By adjusting the depth � and the number of nodes � selected at each layer, the tree traversal method offers control over the specificity and breadth of the information retrieved. The algorithm starts with a broad outlook by considering the top layers of the tree and progressively focuses on finer details as it descends through the lower layers. The collapsed tree approach offers a simpler way to search for relevant information by considering all nodes in the tree simultaneously, as depicted in Figure 2. Instead of going layer-by-layer, this method flattens the multi-layered tree into a single layer, essentially bringing all the nodes onto the same level for comparison. The steps for this method are outlined below: 1. First, collapse the entire RAPTOR tree into a single layer. This new set of nodes, denoted as � , contains nodes from every layer of the original tree. 2. Next, calculate the cosine similarity between the query embedding and the embeddings of all nodes present in the collapsed set � . 3. Finally, pick the top- � nodes that have the highest cosine similarity scores with the query. Keep adding nodes to the result set until you reach a predefined maximum number of tokens, ensuring you don’t exceed the model’s input limitations. We tested both approaches on 20 stories from the QASPER dataset. Figure 3 shows the performance of tree traversal with different top- sizes and collapsed tree with different maximum token numbers. The collapsed tree approach consistently performs better. We believe collapsed tree retrieval is better due to offering greater flexibility than tree traversal; i.e., by searching through all the nodes simultaneously, it retrieves information that is at the correct level of granularity for a given question. In comparison, while using tree traversal with the same values of � and � , the ratio of nodes from each level of the tree will be constant. So, the ratio of higher-order thematic information to granular details will remain the same regardless of the question. One drawback, however, of the collapsed tree approach is that it requires cosine similarity search to be performed on all nodes in the tree. However, this can be made more efficient with fast � -nearest neighbor libraries such as FAISS (Johnson et al., 2019). Refer to caption Figure 3:Comparison of querying methods. Results on 20 stories from the QASPER dataset using tree traversal with different top-k values, and collapsed tree with different context lengths. Collapsed tree with 2000 tokens produces the best results, so we use this querying strategy for our main results. Overall, given the collapsed tree approach’s greater flexibility and its superior performance on the subset of the QASPER dataset, this is the querying approach with which we proceed. Specifically, we use the collapsed tree with 2000 maximum tokens, which approximately equates to retrieving the top-20 nodes. Using a token-based approach ensures the context does not exceed model context constraints as token counts can vary across nodes. For experiments with the UnifiedQA model, we provide 400 tokens of context, as UnifiedQA has a max context length of 512 tokens. We provide the same amount of tokens of context to RAPTOR and to the baselines. Qualitative Study We conduct a qualitative analysis to understand the benefits of RAPTOR’s retrieval process compared to Dense Passage Retrieval (DPR) methods. Our study focuses on thematic, multi-hop questions using a 1500-word Cinderella fairytale. As illustrated in Figure 4, RAPTOR’s tree-based retrieval allows it to choose nodes from different tree layers, matching the question’s detail level. This approach often yields more relevant and comprehensive information for downstream tasks than DPR. For a detailed discussion and examples, including the text retrieved by both RAPTOR and DPR for specific questions, please refer to the appendix G. 4Experiments Datasets We measure RAPTOR’s performance across three question-answering datasets: NarrativeQA, QASPER, and QuALITY. NarrativeQA is a dataset that comprises question-answer pairs based on the full texts of books and movie transcripts, totaling 1,572 documents (Kočiskỳ et al., 2018; Wu et al., 2021). The NarrativeQA-Story task requires a comprehensive understanding of the entire narrative in order to accurately answer its questions, thus testing the model’s ability to comprehend longer texts in the literary domain. We measure performance on this dataset using the standard BLEU (B-1, B-4), ROUGE (R-L), and METEOR (M) metrics. Please see appendix H for more details on the NarrativeQA evaluation script used in our experiments. The QASPER dataset includes 5,049 questions across 1,585 NLP papers, with each question probing for information embedded within the full text (Dasigi et al., 2021). The answer types in QASPER are categorized as Answerable/Unanswerable, Yes/No, Abstractive, and Extractive. Accuracy is measured using standard F1. Lastly, the QuALITY dataset consists of multiple-choice questions, each accompanied by context passages averaging approximately 5,000 tokens in length (Pang et al., 2022). This dataset calls for reasoning over the entire document for QA tasks, enabling us to measure the performance of our retrieval system on medium-length documents. The dataset includes a challenging subset, QuALITY-HARD, which contains questions that a majority of human annotators answered incorrectly in a speed-setting. We report accuracies for both the entire test set and the HARD subset. Refer to caption Figure 4:Querying Process: Illustration of how RAPTOR retrieves information for two questions about the Cinderella story: “What is the central theme of the story?” and “How did Cinderella find a happy ending?”. Highlighted nodes indicate RAPTOR’s selections, while arrows point to DPR’s leaf nodes. Notably, RAPTOR’s context often encompasses the information retrieved by DPR, either directly or within higher-layer summaries. Controlled Baseline Comparisons We first present controlled comparisons using the UnifiedQA 3B as the reader, with SBERT (Reimers & Gurevych, 2019), BM25 (Robertson et al., 1995; 2009), and DPR (Karpukhin et al., 2020) as the embedding models with and without the RAPTOR tree structure, on three datasets: QASPER, NarrativeQA, and QuALITY. As shown in Tables 1 and 2, our results demonstrate that RAPTOR, when combined with any retriever, consistently outperforms the respective retriever across all datasets. 2 Since RAPTOR with SBERT has the best performance, we use it in all subsequent experiments. We now compare RAPTOR with BM25 and DPR, using three different LLMs: GPT-3, GPT-4, and UnifiedQA. As shown in Table 3, RAPTOR consistently outperforms BM25 and DPR across all three Language Models on the QASPER dataset. RAPTOR’s F-1 Match scores are 53.1%, 55.7%, and 36.6% when using GPT-3, GPT-4, and UnifiedQA, respectively. These scores surpass DPR by margins of 1.8, 2.7, and 4.5 points, and outdo BM25 by 6.5, 5.5, and 10.2 points across the respective LLMs. QASPER requires synthesizing information within NLP papers, so it is unsurprising that RAPTOR’s higher-level summary nodes would allow it to outperform methods that can only extract the top- � most similar raw chunks of text, which may not contain the correct response in isolation. Table 1:NarrativeQA Performance With + Without RAPTOR: Performance comparison of various retrieval methods (SBERT, BM25, DPR) with and without RAPTOR on the NarrativeQA dataset, using UnifiedQA-3B as the language model. RAPTOR outperforms baselines of each respective retrieval method. Model ROUGE BLEU-1 BLEU-4 METEOR SBERT with RAPTOR 30.87% 23.50% 6.42% 19.20% SBERT without RAPTOR 29.26% 22.56% 5.95% 18.15% BM25 with RAPTOR 27.93% 21.17% 5.70% 17.03% BM25 without RAPTOR 23.52% 17.73% 4.65% 13.98% DPR with RAPTOR 30.94% 23.51% 6.45% 19.05% DPR without RAPTOR 29.56% 22.84% 6.12% 18.44% Likewise, in the QuALITY dataset as shown in Table 5, RAPTOR achieves an accuracy of 62.4%, which is a 2% and 5.1% improvement over DPR and BM25. Similar trends are observed when UnifiedQA is employed, with RAPTOR outperforming DPR and BM25 by 2.7% and 6.7%, respectively. Finally, in the NarrativeQA dataset, as presented in Table 6, RAPTOR excels across multiple metrics. For ROUGE-L, it surpasses BM25 and DPR by 7.3 and 2.7 points, respectively. In other metrics like BLEU-1, BLEU-4, and METEOR, RAPTOR outperforms BM25 and DPR by margins ranging from 1.7 to 5.8 and 0.7 to 2.1 points, respectively. Table 2:QuALITY and QASPER Performance With + Without RAPTOR: Performance comparison across the QuALITY and QASPER datasets of various retrieval methods (SBERT, BM25, DPR) with and without RAPTOR. UnifiedQA-3B is used as the language model. RAPTOR outperforms baselines of each respective retrieval method for both datasets. Model Accuracy (QuALITY) Answer F1 (QASPER) SBERT with RAPTOR 56.6% 36.70% SBERT without RAPTOR 54.9% 36.23% BM25 with RAPTOR 52.1% 27.00% BM25 without RAPTOR 49.9% 26.47% DPR with RAPTOR 54.7% 32.23% DPR without RAPTOR 53.1% 31.70% Table 3:Controlled comparison of F-1 scores on the QASPER dataset, using three different language models (GPT-3, GPT-4, UnifiedQA 3B) and various retrieval methods. The column ”Title + Abstract” reflects performance when only the title and abstract of the papers are used for context. RAPTOR outperforms the established baselines BM25 and DPR across all tested language models. Specifically, RAPTOR’s F-1 scores are at least 1.8% points higher than DPR and at least 5.3% points higher than BM25. Retriever GPT-3 F-1 Match GPT-4 F-1 Match UnifiedQA F-1 Match Title + Abstract 25.2 22.2 17.5 BM25 46.6 50.2 26.4 DPR 51.3 53.0 32.1 RAPTOR 53.1 55.7 36.6 Table 4:Comparison of accuracies on the QuALITY dev dataset for two different language models (GPT-3, UnifiedQA 3B) using various retrieval methods. RAPTOR outperforms the baselines of BM25 and DPR by at least 2.0% in accuracy. Table 5:Results on F-1 Match scores of various models on the QASPER dataset. Model GPT-3 Acc. UnifiedQA Acc. BM25 57.3 49.9 DPR 60.4 53.9 RAPTOR 62.4 56.6 Model F-1 Match LongT5 XL (Guo et al., 2022) 53.1 CoLT5 XL (Ainslie et al., 2023) 53.9 RAPTOR + GPT-4 55.7 Table 5:Results on F-1 Match scores of various models on the QASPER dataset. Comparison to State-of-the-art Systems Building upon our controlled comparisons, we examine RAPTOR’s performance relative to other state-of-the-art models. As shown in Table 5, RAPTOR with GPT-4 sets a new benchmark on QASPER, with a 55.7% F-1 score, surpassing the CoLT5 XL’s score of 53.9%. In the QuALITY dataset, as shown in Table 7, RAPTOR paired with GPT-4 sets a new state-of-the-art with an accuracy of 82.6%, surpassing the previous best result of 62.3%. In particular, it outperforms CoLISA by 21.5% on QuALITY-HARD, which represents questions that humans took unusually long to correctly answer, requiring rereading parts of the text, difficult reasoning, or both. For the NarrativeQA dataset, as represented in Table 6, RAPTOR paired with UnifiedQA sets a new state-of-the-art METEOR score. When compared to the recursively summarizing model by Wu et al. (2021), which also employs UnifiedQA, RAPTOR outperforms it on all metrics. While Wu et al. (2021) rely solely on the summary in the top root node of the tree structure, RAPTOR benefits from its intermediate layers and clustering approaches, which allows it to capture a range of information, from general themes to specific details, contributing to its overall strong performance. Table 6:Performance comparison on the NarrativeQA dataset across multiple models, focusing on four metrics: ROUGE-L, BLEU-1, BLEU-4, and METEOR. RAPTOR, when paired with UnifiedQA 3B, not only surpasses retrieval methods like BM25 and DPR but also sets a new state-of-the-art in the METEOR metric. Model ROUGE-L BLEU-1 BLEU-4 METEOR BiDAF (Kočiskỳ et al., 2018) 6.2 5.7 0.3 3.7 BM25 + BERT (Mou et al., 2020) 15.5 14.5 1.4 5.0 Recursively Summarizing Books (Wu et al., 2021) 21.6 22.3 4.2 10.6 Retriever + Reader (Izacard & Grave, 2022) 32.0 35.3 7.5 11.1 RAPTOR + UnifiedQA 30.8 23.5 6.4 19.1 Table 7:Accuracies of the QuALITY dataset on both the overall test set and the more challenging hard subset. GPT-4 with RAPTOR sets a new state-of-the-art. Model Accuracy Test Set Hard Subset Longformer-base (Beltagy et al., 2020) 39.5 35.3 DPR and DeBERTaV3-large (Pang et al., 2022) 55.4 46.1 CoLISA (DeBERTaV3-large) (Dong et al., 2023a) 62.3 54.7 RAPTOR + GPT-4 82.6 76.2 4.1Contribution of the tree structure Table 8:Performance of RAPTOR when querying different tree layers for Story 1 from the QuALITY dataset. Columns represent different starting points (highest layer) and rows represent different numbers of layers queried. Layers Queried / Start Layer Layer 0 (Leaf Nodes) Layer 1 Layer 2 1 layer 57.9 57.8 57.9 2 layers - 52.6 63.15 3 layers - - 73.68 We examine the contribution of each layer of nodes to RAPTOR’s retrieval capabilities. We hypothesized that upper nodes play a crucial role in handling thematic or multi-hop queries requiring a broader understanding of the text. We validated this hypothesis both quantitatively and qualitatively. We present qualitative analysis in appendix G. To quantitatively understand the contribution of the upper-level nodes, we used stories from the QuALITY dataset. The RAPTOR tree is built for each of these stories, as described in Section 3. However, during retrieval, we limit the search to different subsets of layers. For example, we exclusively retrieve from the leaf nodes and each upper layer, as well as from different contiguous subsets of the layers. We show findings specific to one story in Table 8, revealing that a full-tree search, utilizing all layers, outperformed retrieval strategies that focused only on specific layers. These findings highlight the importance of the full tree structure in RAPTOR. By providing both the original text and higher-level summaries for retrieval, RAPTOR can effectively handle a wider range of questions, from higher-order thematic queries to detail-oriented questions. Detailed results for additional stories and an ablation study on layer contributions can be found in Appendix I. 5Conclusion In this paper, we have presented RAPTOR, a novel tree-based retrieval system that augments the parametric knowledge of large language models with contextual information at various levels of abstraction. By employing recursive clustering and summarization techniques, RAPTOR creates a hierarchical tree structure that is capable of synthesizing information across various sections of the retrieval corpora. During the query phase, RAPTOR leverages this tree structure for more effective retrieval. Our controlled experiments demonstrated that RAPTOR not only outperforms traditional retrieval methods but also sets new performance benchmarks on several question-answering tasks. 6Reproducibility Statement Language Models for QA and Summarization Four language models are used in our RAPTOR experiments: GPT-3 and GPT-4 for QA tasks, and GPT-3.5-turbo for summarization. The gpt-3, gpt-4, and gpt-3.5-turbo models can be accessed via API calls (OpenAI API). UnifiedQA, which is used for QA tasks, is publicly available at Hugging Face. Evaluation Datasets The three evaluation datasets used in our experiments—QuALITY, QASPER, and NarrativeQA—are all publicly accessible. These datasets ensure that the retrieval and QA tests conducted in this study can be replicated. Source Code The source code for RAPTOR will be publicly available here. References Aggarwal et al. (2001) Charu C Aggarwal, Alexander Hinneburg, and Daniel A Keim.On the Surprising Behavior of Distance Metrics in High Dimensional Space.In Database Theory—ICDT 2001: 8th International Conference London, UK, January 4–6, 2001 Proceedings 8, pp. 420–434. Springer, 2001.URL https://link.springer.com/chapter/10.1007/3-540-44503-x_27. Ainslie et al. (2023) Joshua Ainslie, Tao Lei, Michiel de Jong, Santiago Ontañón, Siddhartha Brahma, Yury Zemlyanskiy, David Uthus, Mandy Guo, James Lee-Thorp, Yi Tay, et al.CoLT5: Faster long-range transformers with conditional computation.arXiv preprint arXiv:2303.09752, 2023.URL https://arxiv.org/abs/2303.09752. Akyurek et al. (2022) Ekin Akyurek, Tolga Bolukbasi, Frederick Liu, Binbin Xiong, Ian Tenney, Jacob Andreas, and Kelvin Guu.Towards tracing knowledge in language models back to the training data.In Findings of the Association for Computational Linguistics: EMNLP 2022, pp. 2429–2446, Abu Dhabi, United Arab Emirates, December 2022. Association for Computational Linguistics.doi: 10.18653/v1/2022.findings-emnlp.180.URL https://aclanthology.org/2022.findings-emnlp.180. Angelidis & Lapata (2018) Stefanos Angelidis and Mirella Lapata.Summarizing opinions: Aspect extraction meets sentiment prediction and they are both weakly supervised.arXiv preprint arXiv:1808.08858, 2018.URL https://arxiv.org/abs/1808.08858. Arivazhagan et al. (2023) Manoj Ghuhan Arivazhagan, Lan Liu, Peng Qi, Xinchi Chen, <PRESIDIO_ANONYMIZED_PERSON>, and Zhiheng Huang.Hybrid hierarchical retrieval for open-domain question answering.In Anna Rogers, Jordan Boyd-Graber, and Naoaki Okazaki (eds.), Findings of the Association for Computational Linguistics: ACL 2023, pp. 10680–10689, Toronto, Canada, July 2023. Association for Computational Linguistics.doi: 10.18653/v1/2023.findings-acl.679.URL https://aclanthology.org/2023.findings-acl.679. Beltagy et al. (2020) Iz Beltagy, Matthew E. Peters, and Arman Cohan.Longformer: The Long-document Transformer, 2020.URL https://arxiv.org/abs/2004.05150.arXiv preprint arXiv:2004.05150. Borgeaud et al. (2022) Sebastian Borgeaud, Arthur Mensch, Jordan Hoffmann, Trevor Cai, Eliza Rutherford, Katie Millican, George Bm Van Den Driessche, Jean-Baptiste Lespiau, Bogdan Damoc, Aidan Clark, et al.Improving language models by retrieving from trillions of tokens.In International conference on machine learning, pp. 2206–2240. PMLR, 2022.URL https://arxiv.org/abs/2112.04426. Brown et al. (2020) Tom Brown, Benjamin Mann, Nick Ryder, Melanie Subbiah, Jared D Kaplan, Prafulla Dhariwal, Arvind Neelakantan, Pranav Shyam, Girish Sastry, Amanda Askell, Sandhini Agarwal, Ariel Herbert-Voss, Gretchen Krueger, Tom Henighan, Rewon Child, Aditya Ramesh, Daniel Ziegler, Jeffrey Wu, Clemens Winter, Chris Hesse, Mark Chen, Eric Sigler, Mateusz Litwin, Scott Gray, Benjamin Chess, Jack Clark, Christopher Berner, Sam McCandlish, Alec Radford, Ilya Sutskever, and Dario Amodei.Language Models are Few-Shot Learners.In H. Larochelle, M. Ranzato, R. Hadsell, M.F. Balcan, and H. Lin (eds.), Advances in Neural Information Processing Systems, volume 33, pp. 1877–1901. Curran Associates, Inc., 2020.URL https://proceedings.neurips.cc/paper_files/paper/2020/file/1457c0d6bfcb4967418bfb8ac142f64a-Paper.pdf. Bubeck et al. (2023) Sébastien Bubeck, Varun Chandrasekaran, Ronen Eldan, Johannes Gehrke, Eric Horvitz, Ece Kamar, Peter Lee, Yin Tat Lee, Yuanzhi Li, <PRESIDIO_ANONYMIZED_PERSON>, et al.Sparks of Artificial General Intelligence: Early Experiments with GPT-4.arXiv preprint arXiv:2303.12712, 2023.URL https://arxiv.org/abs/2303.12712. Cao & Wang (2022) Shuyang Cao and Lu Wang.HIBRIDS: Attention with hierarchical biases for structure-aware long document summarization.In Proceedings of the 60th Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers), pp. 786–807, Dublin, Ireland, May 2022. Association for Computational Linguistics.doi: 10.18653/v1/2022.acl-long.58.URL https://aclanthology.org/2022.acl-long.58. Chen et al. (2017) Danqi Chen, Adam Fisch, Jason Weston, and Antoine Bordes.Reading Wikipedia to Answer Open-Domain Questions.In Proceedings of the 55th Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers), pp. 1870–1879, Vancouver, Canada, July 2017. Association for Computational Linguistics.doi: 10.18653/v1/P17-1171.URL https://aclanthology.org/P17-1171. Chowdhery et al. (2022) Aakanksha Chowdhery, Sharan Narang, Jacob Devlin, Maarten Bosma, Gaurav Mishra, Adam Roberts, Paul Barham, Hyung Won Chung, Charles Sutton, Sebastian Gehrmann, et al.PaLM: Scaling Language Modeling with Pathways.arXiv preprint arXiv:2204.02311, 2022.URL https://arxiv.org/abs/2204.02311. Cohan & Goharian (2017) Arman Cohan and Nazli Goharian.Contextualizing citations for scientific summarization using word embeddings and domain knowledge.In Proceedings of the 40th International ACM SIGIR Conference on Research and Development in Information Retrieval, pp. 1133–1136, 2017.URL https://dl.acm.org/doi/abs/10.1145/3077136.3080740. Dai et al. (2019) Zihang Dai, Zhilin Yang, Yiming Yang, Jaime Carbonell, Quoc Le, and Ruslan Salakhutdinov.Transformer-XL: Attentive language models beyond a fixed-length context.In Proceedings of the 57th Annual Meeting of the Association for Computational Linguistics, pp. 2978–2988, Florence, Italy, July 2019. Association for Computational Linguistics.doi: 10.18653/v1/P19-1285.URL https://aclanthology.org/P19-1285. Dao et al. (2022) Tri Dao, Dan Fu, Stefano Ermon, Atri Rudra, and Christopher Ré.FlashAttention: Fast and memory-efficient exact attention with IO-Awareness.Advances in Neural Information Processing Systems, 35:16344–16359, 2022.URL https://arxiv.org/abs/2205.14135. Dasigi et al. (2021) Pradeep Dasigi, Kyle Lo, Iz Beltagy, Arman Cohan, Noah A. Smith, and Matt Gardner.A Dataset of Information-Seeking Questions and Answers Anchored in Research Papers.In Proceedings of the 2021 Conference of the North American Chapter of the Association for Computational Linguistics: Human Language Technologies, pp. 4599–4610, Online, June 2021. Association for Computational Linguistics.doi: 10.18653/v1/2021.naacl-main.365.URL https://aclanthology.org/2021.naacl-main.365. Dong et al. (2023a) Mengxing Dong, Bowei Zou, Yanling Li, and Yu Hong.CoLISA: Inner Interaction via Contrastive Learning for Multi-choice Reading Comprehension.In Advances in Information Retrieval: 45th European Conference on Information Retrieval, ECIR 2023, Dublin, Ireland, April 2–6, 2023, Proceedings, Part I, pp. 264–278. Springer, 2023a.URL https://link.springer.com/chapter/10.1007/978-3-031-28244-7_17. Dong et al. (2023b) Zican Dong, Tianyi Tang, Lunyi Li, and Wayne Xin Zhao.A survey on long text modeling with transformers.arXiv preprint arXiv:2302.14502, 2023b.URL https://arxiv.org/abs/2302.14502. Gao et al. (2023) Tianyu Gao, Howard Yen, Jiatong Yu, and Danqi Chen.Enabling large language models to generate text with citations.arXiv preprint arXiv:2305.14627, 2023.URL https://arxiv.org/abs/2305.14627. Guo et al. (2022) Mandy Guo, Joshua Ainslie, David Uthus, Santiago Ontanon, Jianmo Ni, Yun-Hsuan Sung, and Yinfei Yang.LongT5: Efficient text-to-text transformer for long sequences.In Findings of the Association for Computational Linguistics: NAACL 2022, pp. 724–736, Seattle, United States, July 2022. Association for Computational Linguistics.doi: 10.18653/v1/2022.findings-naacl.55.URL https://aclanthology.org/2022.findings-naacl.55. Guu et al. (2020) Kelvin Guu, Kenton Lee, Zora Tung, Panupong Pasupat, and Mingwei Chang.Retrieval Augmented Language Model Pre-Training.In International conference on machine learning, pp. 3929–3938. PMLR, 2020.URL https://doi.org/10.48550/arXiv.2002.08909. Hoffmann et al. (2022) Jordan Hoffmann, Sebastian Borgeaud, Arthur Mensch, Elena Buchatskaya, Trevor Cai, Eliza Rutherford, Diego de Las Casas, Lisa Anne Hendricks, Johannes Welbl, Aidan Clark, et al.Training compute-optimal large language models.arXiv preprint arXiv:2203.15556, 2022.URL https://arxiv.org/abs/2203.15556. Izacard & Grave (2022) Gautier Izacard and Edouard Grave.Distilling Knowledge from Reader to Retriever for Question Answering, 2022.URL https://arxiv.org/abs/2012.04584.arXiv preprint arXiv:2012.04584. Izacard et al. (2022) Gautier Izacard, Patrick Lewis, Maria Lomeli, Lucas Hosseini, Fabio Petroni, Timo Schick, Jane Dwivedi-Yu, Armand Joulin, Sebastian Riedel, and Edouard Grave.Few-shot learning with retrieval augmented language models.arXiv preprint arXiv:2208.03299, 2022.URL https://arxiv.org/abs/2208.03299. Jiang et al. (2020) Zhengbao Jiang, Frank F Xu, Jun Araki, and Graham Neubig.How can we know what language models know?Transactions of the Association for Computational Linguistics, 8:423–438, 2020.URL https://arxiv.org/abs/1911.12543. Johnson et al. (2019) Jeff Johnson, Matthijs Douze, and Hervé Jégou.Billion-Scale Similarity Search with GPUs.IEEE Transactions on Big Data, 7(3):535–547, 2019.URL https://arxiv.org/abs/1702.08734. Kandpal et al. (2023) Nikhil Kandpal, Haikang Deng, Adam Roberts, Eric Wallace, and Colin Raffel.Large Language Models struggle to learn Long-Tail Knowledge.In International Conference on Machine Learning, pp. 15696–15707. PMLR, 2023.URL https://proceedings.mlr.press/v202/kandpal23a/kandpal23a.pdf. Karpukhin et al. (2020) Vladimir Karpukhin, Barlas Oguz, Sewon Min, Patrick Lewis, Ledell Wu, Sergey Edunov, Danqi Chen, and Wen-tau Yih.Dense Passage Retrieval for Open-Domain Question Answering.In Proceedings of the 2020 Conference on Empirical Methods in Natural Language Processing (EMNLP), pp. 6769–6781, Online, November 2020. Association for Computational Linguistics.doi: 10.18653/v1/2020.emnlp-main.550.URL https://aclanthology.org/2020.emnlp-main.550. Khashabi et al. (2020) Daniel Khashabi, Sewon Min, Tushar Khot, Ashish Sabharwal, Oyvind Tafjord, Peter Clark, and Hannaneh Hajishirzi.UNIFIEDQA: Crossing format boundaries with a single QA system.In Findings of the Association for Computational Linguistics: EMNLP 2020, pp. 1896–1907, Online, November 2020. Association for Computational Linguistics.doi: 10.18653/v1/2020.findings-emnlp.171.URL https://aclanthology.org/2020.findings-emnlp.171. Khattab & Zaharia (2020) Omar Khattab and Matei Zaharia.ColBERT: Efficient and effective passage search via contextualized late interaction over bert.In Proceedings of the 43rd International ACM SIGIR conference on research and development in Information Retrieval, pp. 39–48, 2020.URL https://arxiv.org/abs/2004.12832. Kočiskỳ et al. (2018) Tomáš Kočiskỳ, Jonathan Schwarz, Phil Blunsom, Chris Dyer, Karl Moritz Hermann, Gábor Melis, and Edward Grefenstette.The NarrativeQA Reading Comprehension Challenge.Transactions of the Association for Computational Linguistics, 6:317–328, 2018.URL https://arxiv.org/abs/1712.07040. Lewis et al. (2020) Patrick Lewis, Ethan Perez, Aleksandra Piktus, Fabio Petroni, Vladimir Karpukhin, Naman Goyal, Heinrich Küttler, Mike Lewis, Wen-tau Yih, Tim Rocktäschel, et al.Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks.Advances in Neural Information Processing Systems, 33:9459–9474, 2020.URL https://doi.org/10.48550/arXiv.2005.11401. Liu (2022) Jerry Liu.LlamaIndex, 2022.URL https://github.com/jerryjliu/llama_index. Liu et al. (2023) Nelson F Liu, Kevin Lin, John Hewitt, Ashwin Paranjape, Michele Bevilacqua, Fabio Petroni, and Percy Liang.Lost in the middle: How language models use long contexts.arXiv preprint arXiv:2307.03172, 2023.URL https://arxiv.org/abs/2307.03172. Liu et al. (2021) Ye Liu, Kazuma Hashimoto, Yingbo Zhou, Semih Yavuz, Caiming Xiong, and Philip Yu.Dense hierarchical retrieval for open-domain question answering.In Marie-Francine Moens, Xuanjing Huang, Lucia Specia, and Scott Wen-tau Yih (eds.), Findings of the Association for Computational Linguistics: EMNLP 2021, pp. 188–200, Punta Cana, Dominican Republic, November 2021. Association for Computational Linguistics.doi: 10.18653/v1/2021.findings-emnlp.19.URL https://aclanthology.org/2021.findings-emnlp.19. McInnes et al. (2018) Leland McInnes, John Healy, and James Melville.UMAP: Uniform Manifold Approximation and Projection for Dimension Reduction, 2018.URL https://arxiv.org/abs/1802.03426.arXiv preprint arXiv:1802.03426. Min et al. (2021) Sewon Min, Kenton Lee, Ming-Wei Chang, Kristina Toutanova, and Hannaneh Hajishirzi.Joint passage ranking for diverse multi-answer retrieval.In Marie-Francine Moens, Xuanjing Huang, Lucia Specia, and Scott Wen-tau Yih (eds.), Proceedings of the 2021 Conference on Empirical Methods in Natural Language Processing, pp. 6997–7008, Online and Punta Cana, Dominican Republic, November 2021. Association for Computational Linguistics.doi: 10.18653/v1/2021.emnlp-main.560.URL https://aclanthology.org/2021.emnlp-main.560. Min et al. (2023) Sewon Min, Weijia Shi, Mike Lewis, Xilun Chen, Wen-tau Yih, Hannaneh Hajishirzi, and Luke Zettlemoyer.Nonparametric masked language modeling.In Findings of the Association for Computational Linguistics: ACL 2023, pp. 2097–2118, Toronto, Canada, July 2023. Association for Computational Linguistics.doi: 10.18653/v1/2023.findings-acl.132.URL https://aclanthology.org/2023.findings-acl.132. Mitchell et al. (2022) Eric Mitchell, Charles Lin, Antoine Bosselut, Christopher D Manning, and Chelsea Finn.Memory-based model editing at scale.In International Conference on Machine Learning, pp. 15817–15831. PMLR, 2022.URL https://proceedings.mlr.press/v162/mitchell22a/mitchell22a.pdf. Mou et al. (2020) Xiangyang Mou, Mo Yu, Bingsheng Yao, Chenghao Yang, Xiaoxiao Guo, Saloni Potdar, and Hui Su.Frustratingly hard evidence retrieval for QA over books.In Proceedings of the First Joint Workshop on Narrative Understanding, Storylines, and Events, pp. 108–113, Online, July 2020. Association for Computational Linguistics.doi: 10.18653/v1/2020.nuse-1.13.URL https://aclanthology.org/2020.nuse-1.13. Nair et al. (2023) Inderjeet Nair, Aparna Garimella, Balaji Vasan Srinivasan, Natwar Modani, Niyati Chhaya, Srikrishna Karanam, and Sumit Shekhar.A neural CRF-based hierarchical approach for linear text segmentation.In Findings of the Association for Computational Linguistics: EACL 2023, pp. 883–893, Dubrovnik, Croatia, May 2023. Association for Computational Linguistics.doi: 10.18653/v1/2023.findings-eacl.65.URL https://aclanthology.org/2023.findings-eacl.65. Newman et al. (2023) Benjamin Newman, Luca Soldaini, Raymond Fok, Arman Cohan, and Kyle Lo.A controllable qa-based framework for decontextualization.arXiv preprint arXiv:2305.14772, 2023.URL https://arxiv.org/pdf/2305.14772.pdf. OpenAI (2023) OpenAI.GPT-4 Technical Report.ArXiv, abs/2303.08774, 2023.URL https://arxiv.org/abs/2303.08774. Pang et al. (2022) Richard Yuanzhe Pang, Alicia Parrish, Nitish Joshi, Nikita Nangia, Jason Phang, Angelica Chen, Vishakh Padmakumar, Johnny Ma, Jana Thompson, He He, and Samuel Bowman.QuALITY: Question Answering with Long Input Texts, Yes!In Proceedings of the 2022 Conference of the North American Chapter of the Association for Computational Linguistics: Human Language Technologies, pp. 5336–5358, Seattle, United States, July 2022. Association for Computational Linguistics.URL https://aclanthology.org/2022.naacl-main.391. Petroni et al. (2019) Fabio Petroni, Tim Rocktäschel, Patrick Lewis, Anton Bakhtin, Yuxiang Wu, Alexander H Miller, and Sebastian Riedel.Language models as knowledge bases?arXiv preprint arXiv:1909.01066, 2019.URL https://arxiv.org/abs/1909.01066. Rae et al. (2021) Jack W Rae, Sebastian Borgeaud, Trevor Cai, Katie Millican, Jordan Hoffmann, Francis Song, John Aslanides, Sarah Henderson, Roman Ring, Susannah Young, et al.Scaling language models: Methods, Analysis & Insights from Training Gopher.arXiv preprint arXiv:2112.11446, 2021.URL https://arxiv.org/abs/2112.11446. Ram et al. (2023) Ori Ram, Yoav Levine, Itay Dalmedigos, Dor Muhlgay, Amnon Shashua, Kevin Leyton-Brown, and Yoav Shoham.In-context retrieval-augmented language models.arXiv preprint arXiv:2302.00083, 2023.URL https://arxiv.org/abs/2302.00083. Reimers & Gurevych (2019) Nils Reimers and Iryna Gurevych.Sentence-BERT: Sentence embeddings using Siamese BERT-networks.In Proceedings of the 2019 Conference on Empirical Methods in Natural Language Processing and the 9th International Joint Conference on Natural Language Processing (EMNLP-IJCNLP), pp. 3982–3992, Hong Kong, China, November 2019. Association for Computational Linguistics.doi: 10.18653/v1/D19-1410.URL https://aclanthology.org/D19-1410. Roberts et al. (2020) Adam Roberts, Colin Raffel, and Noam Shazeer.How Much Knowledge Can You Pack Into the Parameters of a Language Model?In Proceedings of the 2020 Conference on Empirical Methods in Natural Language Processing (EMNLP), pp. 5418–5426, Online, November 2020. Association for Computational Linguistics.doi: 10.18653/v1/2020.emnlp-main.437.URL https://aclanthology.org/2020.emnlp-main.437. Robertson et al. (2009) Stephen Robertson, Hugo Zaragoza, et al.The Probabilistic Relevance Framework: BM25 and Beyond.Foundations and Trends in Information Retrieval, 3(4):333–389, 2009.URL https://doi.org/10.1561/1500000019. Robertson et al. (1995) Stephen E Robertson, Steve Walker, Susan Jones, Micheline M Hancock-Beaulieu, Mike Gatford, et al.Okapi at TREC-3.Nist Special Publication Sp, 109:109, 1995.URL https://www.microsoft.com/en-us/research/publication/okapi-at-trec-3/. Sachan et al. (2023) Devendra Singh Sachan, Mike Lewis, Dani Yogatama, Luke Zettlemoyer, Joelle Pineau, and Manzil Zaheer.Questions are all you need to train a dense passage retriever.Transactions of the Association for Computational Linguistics, 11:600–616, 2023.doi: 10.1162/tacl˙a˙00564.URL https://aclanthology.org/2023.tacl-1.35. Schwarz (1978) Gideon Schwarz.Estimating the Dimension of a Model.The annals of statistics, pp. 461–464, 1978.URL https://projecteuclid.org/journals/annals-of-statistics/volume-6/issue-2/Estimating-the-Dimension-of-a-Model/10.1214/aos/1176344136.full. Spärck Jones (1972) Karen Spärck Jones.A Statistical Interpretation of Term Specificity and its Application in Retrieval.Journal of documentation, 28(1):11–21, 1972.URL https://doi.org/10.1108/eb026526. Sun et al. (2021) Simeng Sun, Kalpesh Krishna, Andrew Mattarella-Micke, and Mohit Iyyer.Do long-range language models actually use long-range context?In Marie-Francine Moens, Xuanjing Huang, Lucia Specia, and Scott Wen-tau Yih (eds.), Proceedings of the 2021 Conference on Empirical Methods in Natural Language Processing, pp. 807–822, Online and Punta Cana, Dominican Republic, November 2021. Association for Computational Linguistics.doi: 10.18653/v1/2021.emnlp-main.62.URL https://aclanthology.org/2021.emnlp-main.62. Sun et al. (2022) Zhiqing Sun, Xuezhi Wang, <PRESIDIO_ANONYMIZED_PERSON>, <PRESIDIO_ANONYMIZED_PERSON>, and Denny Zhou.Recitation-augmented language models.arXiv preprint arXiv:2210.01296, 2022.URL https://arxiv.org/abs/2210.01296. Talmor et al. (2020) Alon Talmor, Yanai Elazar, Yoav Goldberg, and Jonathan Berant.oLMpics– on what language model pre-training captures.Transactions of the Association for Computational Linguistics, 8:743–758, 2020.URL https://arxiv.org/abs/1912.13283. Wang et al. (2023) Boxin Wang, Wei Ping, Peng Xu, Lawrence McAfee, Zihan Liu, Mohammad Shoeybi, Yi Dong, Oleksii Kuchaiev, Bo Li, Chaowei Xiao, et al.Shall we pretrain autoregressive language models with retrieval? a comprehensive study.arXiv preprint arXiv:2304.06762, 2023.URL https://arxiv.org/abs/2304.06762. Wu et al. (2021) Jeff Wu, Long Ouyang, Daniel M. Ziegler, Nisan Stiennon, Ryan Lowe, Jan Leike, and Paul Christiano.Recursively Summarizing Books with Human Feedback, 2021.URL https://arxiv.org/abs/2109.10862. Yu et al. (2018) Adams Wei Yu, David Dohan, Minh-Thang Luong, Rui Zhao, Kai Chen, Mohammad Norouzi, and Quoc V. Le.QANet: Combining Local Convolution with Global Self-Attention for Reading Comprehension, 2018.URL https://arxiv.org/abs/1804.09541.arXiv preprint arXiv:1804.09541. Yu et al. (2022) Wenhao Yu, Dan Iter, Shuohang Wang, Yichong Xu, Mingxuan Ju, Soumya Sanyal, Chenguang Zhu, Michael Zeng, and Meng Jiang.Generate rather than retrieve: Large Language Models are strong context generators, 2022.URL https://arxiv.org/abs/2209.10063. Zhang et al. (2023) Shiyue Zhang, David Wan, and Mohit Bansal.Extractive is not faithful: An investigation of broad unfaithfulness problems in extractive summarization.In Anna Rogers, Jordan Boyd-Graber, and Naoaki Okazaki (eds.), Proceedings of the 61st Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers), pp. 2153–2174, Toronto, Canada, July 2023. Association for Computational Linguistics.doi: 10.18653/v1/2023.acl-long.120.URL https://aclanthology.org/2023.acl-long.120. Appendix AScalability and Computational Efficiency of the Tree-Building Process To assess the computational efficiency and cost-effectiveness of RAPTOR’s tree-building process, we conducted experiments on a consumer-grade laptop, specifically an Apple M1 Mac with 16GB of RAM. These experiments aimed to demonstrate the scalability and feasibility of RAPTOR on typical hardware. We varied the context length from 12,500 to 78,000 tokens and measured both the token expenditure and the time required to complete the tree-building process, from initial splitting and embedding to the construction of the final root node. Refer to caption Figure 5:Token cost as a function of document length for QASPER, NarrativeQA, and QuALITY. RAPTOR tree construction costs scale linearly with document length for each of the datasets. Token Expenditure We empirically investigated the relationship between the initial document length and the total number of tokens expended during the tree-building process, which includes both the prompt and completion tokens. The document lengths varied significantly across the three datasets examined: QuALITY, QASPER, and NarrativeQA. Figure 5 illustrates a clear linear correlation between the initial document length and the total token expenditure, emphasizing that RAPTOR maintains a linear token scaling regardless of document complexity or length. Refer to caption Figure 6:Build time as a function of document length for documents of up to 80,000 tokens. RAPTOR tree construction time scales linearly with document length for each of the datasets. Build Time We also empirically observed a consistent linear trend between the document length and the build time, as shown in Figure 6. This suggests that RAPTOR scales linearly in terms of time, making it a viable solution for efficiently processing large corpora of varying lengths. Conclusion Overall, our empirical results indicate that RAPTOR scales both in terms of tokens expended and build time. Even as the complexity and volume of the input text grow, the cost of constructing the tree scales predictably and linearly. This demonstrates that RAPTOR is computationally efficient and well-suited for processing large and diverse corpora. Appendix BAblation Study on Clustering Mechanism in RAPTOR To assess the effectiveness of the clustering mechanism in our RAPTOR approach, we conducted an ablation study on the QuALITY dataset. This study compares RAPTOR’s performance with a balanced tree-style encoding and summarization of contiguous chunks, in contrast to our standard clustering method. B.1Methodology Both configurations in this ablation study utilized SBERT embeddings and UnifiedQA to maintain consistency in retrieval. For RAPTOR, we employed our typical clustering and summarization process. In contrast, the alternative setup involved creating a balanced tree by recursively encoding and summarizing contiguous text chunks. We determined the window size for this setup based on the average cluster size observed in RAPTOR, which is approximately 6.7 nodes. Hence, we chose a window size of 7 nodes. The collapsed tree approach was applied for retrieval in both models. B.2Results & Discussion The results of the ablation study are presented in table 9. The results from this ablation study clearly indicate an improvement in accuracy when employing RAPTOR’s clustering mechanism over the recency-based tree approach. This finding substantiates our hypothesis that the clustering strategy in RAPTOR is more effective in capturing homogeneous content for summarization, thereby enhancing the overall retrieval performance. Table 9:Ablation study results comparing RAPTOR with a recency-based tree approach Configuration Accuracy RAPTOR + SBERT embeddings + UnifiedQA 56.6% Recency-based tree + SBERT embeddings + UnifiedQA 55.8% Appendix CDataset Statistics and Compression Ratios The average ratio of the summary length to the sum of child node lengths across all datasets is 0.28, indicating a 72% compression rate. On average, the summary length is 131 tokens, and the average child node length is 86 tokens. Below are the detailed statistics for all three datasets: Table 10:Statistics of Average Summary Length and Child Node Length Across Datasets Dataset Avg. Summary Length (tokens) Avg. Child Node Text Length (tokens) Avg. # of Child Nodes Per Parent Avg. Compression Ratio (%) All Datasets 131 85.6 6.7 .28 QuALITY 124.4 87.9 5.7 .28 NarrativeQA 129.7 85.5 6.8 .27 QASPER 145.9 86.2 5.7 .35 Appendix DSummarization Prompt Table 11 shows the prompt used for summarization. Table 11:Prompt for Summarization Role Content system You are a Summarizing Text Portal user Write a summary of the following, including as many key details as possible: {context}: Appendix EHallucination Analysis To assess the quality and accuracy of the summarizations within our RAPTOR model, we conducted an analysis focusing on hallucinations in the generated summaries. The summaries were generated by gpt-3.5-turbo and subsequently annotated to quantify the rates of hallucinations, to examine whether such inaccuracies propagate to parent nodes, and to evaluate their impact on question-answering (QA) tasks. E.1Methodology We randomly sampled 150 nodes across 40 stories and evaluated them for hallucinations. This sampling strategy provides a broad view of the model’s performance across different contexts. Each node was annotated by hand, and determined if it contained a hallucination. E.2Findings Out of the 150 nodes sampled, 4% (6 nodes) contained some form of hallucination. Most commonly, these hallucinations originated from the model adding minor information possibly from its training data that was not present in the text being summarized, or from incorrectly extrapolating some information when creating the summary. Example: Text of the child nodes: ”And you will come with me to my people? We may live here among them, and you will be a great warrior–oh, when Jor dies you may even be chief, for there is none so mighty as my warrior…”But your father will not permit it–Jor, my father, High Chief of the Galus, will not permit it, for like me you are cos-ata-lo. Oh, Co-Tan, if we but could!… Bradley noticed that she spoke in English–broken English like Co-Tan’s but equally appealing. Summary found in the parent of that node: The protagonist, Bradley, is being asked by Co-Tan to stay with her people and become a great warrior, but he refuses and must return to his own country. Tom Billings of Santa Monica arrives and tells them he came to search for a man named Bowen J. Tyler, Jr. Ajor, Co-Tan’s sister, is excited about the possibility of going to Tom’s country to see strange and wonderful things… The hallucination here is that the summary states that Jr. Ajor and Co-Tan are sisters, but does not explicitly mention or imply this. Upon reviewing all parent nodes, we found that hallucinations did not propagate to higher layers. Generally, the hallucinations were minor and did not alter the thematic interpretation of the text. E.3Impact on QA Tasks In our findings, hallucinations had no discernible impact on the performance of QA tasks. This suggests that hallucination is not a major concerns for the summarization component in our RAPTOR architecture. Appendix FPseudocode for Retrieval Methods Algorithm 1 Tree Traversal Algorithm function TraverseTree( tree , query , � ) � current ← tree.layer ⁢ [ 0 ] for layer in range(tree.num_layers) do � ⁢ � ⁢ � � ← [ ] for node in ⁢ � current do � ⁢ � ⁢ � ⁢ � ⁢ � ← dot_product(query, node) top_k.append ⁢ ( ( node, score ) ) end for � layer ← sorted(top_k)[:k].nodes � current ← � layer end for return � 0 ∪ � 1 ∪ � 2 ∪ … ∪ � � end function Algorithm 2 Collapsed Tree Algorithm function CollapsedTree( tree , query , � , max_tokens ) tree ← flatten(tree) ▷ Flatten tree into 1D top_nodes ← [ ] for node in tree do top_nodes.append ( ( node, dot_product(query, node)) end for top_nodes ← sorted(top_nodes) result ← [ ] total_tokens ← 0 for node in top_nodes do if total_tokens + node.token_size < max_tokens then result.append(node) end if total_tokens ← total_tokens + node.token_size end for return result end function Question: What is the central theme of the story? RAPTOR Fairy Godmother helps Cinderella attend a ball by transforming her rags… Cinderella impresses the Prince at the ball… she loses track of time and has to run home alone in the darkness. The Prince is unable to find Cinderella and goes in search of her … She forgave her sisters, and treated them always very kindly, and the Prince had great cause to be glad that he had found the glass slipper. DPR Two mice were turned into footmen; four grasshoppers into white horses. Next, the Fairy touched Cinderella’s rags, and they became rich satin robes, trimmed with point lace. … Alas! the clock had struck Eleven. She found no coach, only a pumpkin, and the rat and mice ran quickly away when they saw her; while all her fine dress turned to rags, and she had to run home alone…They told her a beautiful Princess had been at the ball, with whom the Prince was delighted. They did not know it was Cinderella. Question: How does Cinderella find a happy ending? RAPTOR The story of Cinderella involves her godmother, a fairy, who transforms a pumpkin into a grand coach with her wand and allows Cinderella to attend the ball. However, Cinderella must return home before the clock strikes eleven or her dress will turn back into rags… Cinderella impresses the Prince at the ball but leaves before he can find out who she is… The Prince searched for the owner of a lost glass slipper and found it belonged to Cinderella. She forgave her sisters and the Prince was glad to have found her. DPR the clock had struck Eleven… The Prince was very much surprised when he missed Cinderella again, and leaving the ball, went in search of her… Fairy touched Cinderella’s rags, and they became rich satin robes, trimmed with point lace… Her old shoes became a charming pair of glass slippers, which shone like diamonds. “Now go to the ball, my love,” she said, “and enjoy yourself. But remember, you must leave the room before the clock strikes eleven. If you do not your dress will return to its original rags.” Table 12:Relevant excerpts from text retrieved by RAPTOR and DPR for the questions on the fairytale Cinderella. Appendix GQualitative Analysis To qualitatively examine RAPTOR’s retrieval process, we test it on thematic, multi-hop questions about a 1500-word version of the fairytale Cinderella. We compare the context retrieved by RAPTOR with the context retrieved by Dense Passage Retrieval (DPR). Figure 4 in the main paper details the retrieval process within RAPTOR’s tree structure for two questions. The nodes that RAPTOR selects for each question are highlighted, while the leaf nodes that DPR selects for the same question are indicated with arrows. This comparison illustrates the advantage of RAPTOR’s tree structure. RAPTOR selects nodes from different layers depending on the level of granularity required by the question at hand. Further, the information that would be retrieved by DPR is more often than not included in the context retrieved by RAPTOR, either directly as a leaf node or indirectly as part of a summary from a higher layer. ”The first question we examine is “How does Cinderella find a happy ending?”, a multi-hop question best answered by synthesizing information from various text segments. To control for the language model’s potential familiarity with the Cinderella story, we instructed it to rely solely on the retrieved information for its answers. Table 13 shows the text retrieved by both RAPTOR and DPR for this question. RAPTOR’s context succinctly describes Cinderella’s journey to happiness, while DPR’s leaf nodes primarily focus on her initial transformation. The difference in retrieved information significantly impacts downstream tasks. When GPT-4 is provided with RAPTOR’s context, it generates a detailed answer: “Cinderella finds a happy ending when the Prince searches for the owner of the lost glass slipper and discovers it belongs to Cinderella. They eventually marry, transforming Cinderella’s life for the better.” In contrast, using DPR’s context, GPT-4 states: “Based on the given context, it is not possible to determine how Cinderella finds a happy ending, as the text lacks information about the story’s conclusion.” The second question we examine is “What is the central theme of the story?”, a thematic question that requires holistic understanding of the entire text. The text retrieved by RAPTOR and DPR for this question is shown in Table 13. The text retrieved by RAPTOR contains short descriptions of all the major parts of the story, whereas the text retrieved by DPR contains detailed descriptions of a narrow subset of the story. Again, the difference in retrieval mechanisms affects the performance of GPT-4 when answering the question. Given DPR’s context, it outputs “The central theme of the story is transformation and the power of inner beauty, as Cinderella, a kind and humble girl, is magically transformed into a beautiful princess, capturing the attention and admiration of the Prince and others at the ball.” This answer only takes into account the first portion of the story, up until Cinderella first meets the prince. In contrast, given RAPTOR’s context, GPT-4 outputs “The central theme of the story is transformation and overcoming adversity, as Cinderella, with the help of her Fairy Godmother, transforms from a mistreated and downtrodden girl into a beautiful and confident young woman who ultimately finds happiness and love with the Prince.” This is a more complete answer, demonstrating a comprehensive understanding of the story. This qualitative analysis indicates that RAPTOR outperforms prior retrieval mechanisms because the information that it retrieves is more relevant and exhaustive, allowing for better performance on downstream tasks. We also created a 2600-word story along with questions about its narrative and theme. An excerpt from the story is present below and the full PDF of this story is linked here. For questions like “What is the central theme of the story?”, an upper-level node is retrieved which includes the sentence: “This story is about the power of human connection… inspiring and uplifting each other as they pursued their passions.” This summary, not explicitly present in the original text, almost directly answers the question. Excerpt from ”The Eager Writer”: ”Ethan’s passion for writing had always been a part of him. As a child, he would often scribble stories and poems in his notebook, and as he grew older, his love for writing only intensified. His evenings were often spent in the dim light of his room, typing away at his laptop. He had recently taken a job as a content writer for an online marketing firm to pay the bills, but his heart still longed for the world of storytelling. However, like many aspiring writers, he struggled to find a foothold in the industry. He took a job as a content writer for an online marketing firm, but it was growing increasingly evident to him that this was not the path he wanted to pursue. It was during this time that he stumbled upon the Pathways app. The app offered a platform for people in similar professions to connect and share knowledge, and he saw it as an opportunity to finally connect with others who shared his passion for writing. Ethan saw an opportunity to meet others who shared his passion and could offer guidance and mentorship. He quickly signed up and was surprised by the number of writers he found on the platform, from well establish professionals to beginners just starting out in the business.” Appendix HNarrativeQA Evaluation Script We made several modifications to AllenNLP’s evaluation script3 to better fit our evaluation needs: • Added Smoothing: Smoothing was incorporated to handle cases where BLEU score is zero, due to no n-gram matches occurring in the reference text. A BLEU score of zero skews the results, leading to an overly harsh evaluation for rare or novel phrases. By adding a smoothing function, we prevent the BLEU scores from dropping to zero, providing a more fair evaluation. • Modified BLEU-4 Weighting: The original script applied a weight of 1 to the highest order n-gram (4-gram) and 0 to the rest in its BLEU-4 calculation (i.e., weights=(0, 0, 0, 1)). This approach may overly focus on 4-gram matches while neglecting lower-order matches. To provide a more balanced evaluation, we evenly distributed the weight across all n-gram levels, changing the weights for the BLEU-4 calculation to (0.25, 0.25, 0.25, 0.25). • Tokenization before Mapping in METEOR Calculation: The original script utilized a simple split and map method for METEOR calculation. We fixed this by first tokenizing the text and then mapping the tokens. This amendment improves the accuracy of the METEOR calculation by taking into account the correct linguistic boundaries of words. Question: What is the central theme of the story? RAPTOR Fairy Godmother helps Cinderella attend a ball by transforming her rags… Cinderella impresses the Prince at the ball… she loses track of time and has to run home alone in the darkness. The Prince is unable to find Cinderella and goes in search of her … She forgave her sisters, and treated them always very kindly, and the Prince had great cause to be glad that he had found the glass slipper. DPR Two mice were turned into footmen; four grasshoppers into white horses. Next, the Fairy touched Cinderella’s rags, and they became rich satin robes, trimmed with point lace. … Alas! the clock had struck Eleven. She found no coach, only a pumpkin, and the rat and mice ran quickly away when they saw her; while all her fine dress turned to rags, and she had to run home alone…They told her a beautiful Princess had been at the ball, with whom the Prince was delighted. They did not know it was Cinderella. Question: How does Cinderella find a happy ending? RAPTOR The story of Cinderella involves her godmother, a fairy, who transforms a pumpkin into a grand coach with her wand and allows Cinderella to attend the ball. However, Cinderella must return home before the clock strikes eleven or her dress will turn back into rags… Cinderella impresses the Prince at the ball but leaves before he can find out who she is… The Prince searched for the owner of a lost glass slipper and found it belonged to Cinderella. She forgave her sisters and the Prince was glad to have found her. DPR the clock had struck Eleven… The Prince was very much surprised when he missed Cinderella again, and leaving the ball, went in search of her… Fairy touched Cinderella’s rags, and they became rich satin robes, trimmed with point lace… Her old shoes became a charming pair of glass slippers, which shone like diamonds. “Now go to the ball, my love,” she said, “and enjoy yourself. But remember, you must leave the room before the clock strikes eleven. If you do not your dress will return to its original rags.” Table 13:Relevant excerpts from text retrieved by RAPTOR and DPR for the questions on the fairytale Cinderella. Appendix IAnalysis of Different Layers on RAPTOR’s Performance I.1How do different Layers impact performance ? In this section, we present a detailed breakdown of RAPTOR’s retrieval performance when querying different layers of the hierarchical tree structure for various stories. These tables validate the utility of RAPTOR’s multi-layered structure for diverse query requirements. Refer to caption Figure 7:Histogram showing the percentage of nodes retrieved from different layers of the RAPTOR tree across three datasets (NarrativeQA, Quality, and Qasper) using three retrievers (SBERT, BM25, and DPR). The data indicate that a substantial portion of the nodes contributing to the final retrieval comes from non-leaf layers, with a notable percentage from the first and second layers, highlighting the importance of RAPTOR’s hierarchical summarization in the retrieval process. Table 14:Performance of RAPTOR when querying different layers of the tree for Story 2. Layers Queried / Start Layer Layer 0 (Leaf Nodes) Layer 1 Layer 2 1 layer 58.8 47.1 41.1 2 layers - 64.7 52.9 3 layers - - 47.1 Table 15:Performance of RAPTOR when querying different layers of the tree for Story 3. Layers Queried / Start Layer Layer 0 (Leaf Nodes) Layer 1 Layer 2 1 layer 66.6 61.1 61.1 2 layers - 66.6 66.6 3 layers - - 83.3 Table 16:Performance of RAPTOR when querying different layers of the tree for Story 4. Layers Queried / Start Layer Layer 0 (Leaf Nodes) Layer 1 1 layer 94.7 84.2 2 layers - 89.4 Table 17:Performance of RAPTOR when querying different layers of the tree for Story 5. Layers Queried / Start Layer Layer 0 (Leaf Nodes) Layer 1 1 layer 57.9 47.3 2 layers - 68.4 I.2Which Layers do Retrieved Nodes come from ? We further conduct an ablation study across all three datasets and across three different retrievers with RAPTOR with the collapsed tree retrieval to examine the layers from which the retrieved nodes originate. We observe that between 18.5% to 57% of the retrieved nodes come from non-leaf nodes. As illustrated in Figure 7, the retrieval pattern across layers reveals the importance of RAPTOR’s multi-layered tree structure. Notably, a significant percentage of the nodes retrieved by RAPTOR using the DPR retriever for the NarrativeQA dataset come from the first and second layers of the tree, as opposed to the leaf nodes. This pattern is consistent across the other datasets and retrievers, albeit with varying percentages. Table 18:Percentage of nodes from non-leaf nodes across different datasets and retrievers Dataset DPR SBERT BM25 NarrativeQA 57.36% 36.78% 34.96% Quality 32.28% 24.41% 32.36% Qasper 22.93% 18.49% 22.76% Table 19:Percentage of nodes from different layers with DPR as the retriever Layer NarrativeQA Quality Qasper 0 42.64% 67.71% 77.07% 1 45.00% 29.43% 21.88% 2 10.57% 2.85% 1.05% 3 1.78% - - 4 0.003% - - Table 20:Percentage of nodes from different layers with SBERT as the retriever Layer NarrativeQA Quality Qasper 0 63.22% 75.59% 81.51% 1 31.51% 22.78% 17.84% 2 4.85% 1.63% 0.65% 3 0.42% - - Table 21:Percentage of nodes from different layers with BM25 as the retriever Layer NarrativeQA Quality Qasper 0 65.04% 67.64% 77.24% 1 28.79% 28.85% 21.57% 2 5.36% 3.51% 1.19% 3 0.81% - -""
c602b1fa5c5bef95971f1b1f2c1cb5b1
{ "intermediate": 0.4079662263393402, "beginner": 0.2864895761013031, "expert": 0.3055441081523895 }
42,727
1_ Translate the following legal text into colloquial Farsi 2_ Place the Persian and English text side by side in the table 3_ From the beginning to the end of the text, there should be an English sentence on the left side and a Persian sentence on the right side. 4- Using legal language for Persian translation ._ Place the Farsi and English text line by line from one point to the first point next to each other in such a way that one line of English text is followed by two empty lines, followed by the Persian translation and continue this process until the end of the text.6. GENERAL PRINCIPLES OF THE ENGLISH CRIMINAL LAW Criminal Liability 1. The Nature of Crime There is no statutory definition of crime, and it is even conceded that it "is not possible to discover a legal definition of crime which can be of value for English law". For practical purposes, a crime may be defined as a public wrong whose commission will result in criminal proceedings, which may, in turn result in the punishment of the wrongdoer. 2. Public Wrong It is the chief characteristic of crimes, that, unlike torts or breaches of contract, it is not left to the individual affected to bring an action in court though he may initiate such an action by reporting the commission of offences to the police. A criminal prosecution (as opposed to a civil action for damages) is therefore brought by the state (though private prosecutions are still possible in some cases). The corollary is that, whereas the plaintiff to a civil action may, if he so
ad69a0f9b3ec1253eac11e6003e98ce3
{ "intermediate": 0.2959313988685608, "beginner": 0.5091897249221802, "expert": 0.19487889111042023 }
42,728
Исправь код таким образом, чтобы при каждом инжекте файл patcher_log.txt перезаписывался заново, а не добавлял новые строки в файле: #include "pch.h" #include <Windows.h> #include <tlhelp32.h> #include <psapi.h> #include <fstream> #include <vector> #include <string> #include <memory> #include <thread> std::ofstream logFile("patcher_log.txt", std::ios::out | std::ios::app); bool PatchProcess(DWORD processID) { HANDLE hProcess = OpenProcess(PROCESS_VM_OPERATION | PROCESS_VM_READ | PROCESS_VM_WRITE, FALSE, processID); if (!hProcess) { logFile << "Failed to open the target process." << std::endl; return false; } auto processCloser = std::shared_ptr<void>( hProcess, [](HANDLE handle) { CloseHandle(handle); } ); BYTE signatureBytes[] = { 0x85, 0xC0, 0x74, 0x57, 0x5F, 0xB8, 0x01 }; BYTE patchByte = 0x00; MEMORY_BASIC_INFORMATION mbi{ 0 }; bool success = false; for (BYTE* addr = nullptr; VirtualQueryEx(hProcess, addr, &mbi, sizeof(mbi)) && addr < (BYTE*)0x7FFFFFFF; addr += mbi.RegionSize) { if (mbi.State == MEM_COMMIT && (mbi.Protect == PAGE_EXECUTE_READWRITE || mbi.Protect == PAGE_EXECUTE_READ)) { std::vector<BYTE> buffer(mbi.RegionSize); SIZE_T bytesRead; if (ReadProcessMemory(hProcess, mbi.BaseAddress, buffer.data(), mbi.RegionSize, &bytesRead)) { for (size_t j = 0; j < bytesRead - sizeof(signatureBytes); ++j) { if (memcmp(buffer.data() + j, signatureBytes, sizeof(signatureBytes)) == 0) { DWORD oldProtect; if (VirtualProtectEx(hProcess, addr + j + sizeof(signatureBytes) - 1, 1, PAGE_EXECUTE_READWRITE, &oldProtect)) { if (WriteProcessMemory(hProcess, addr + j + sizeof(signatureBytes) - 1, &patchByte, 1, nullptr)) { VirtualProtectEx(hProcess, addr + j + sizeof(signatureBytes) - 1, 1, oldProtect, &oldProtect); logFile << "Signature patched." << std::endl; success = true; return success; } } } } } } } return success; } void AttemptToPatch(DWORD currentPID) { logFile << "Attempting to patch current process ID : " << currentPID << " in a separate thread." << std::endl; while (true) { if (PatchProcess(currentPID)) { logFile << "Current process patched successfully." << std::endl; break; } else { logFile << "Failed to patch the current process.Retrying…" << std::endl; std::this_thread::sleep_for(std::chrono::seconds(5)); // Pause before retrying } } } DWORD WINAPI MonitorProcess(LPVOID lpParam) { DWORD currentPID = GetCurrentProcessId(); // Spin off a separate thread to attempt patching without blocking std::thread patcherThread(AttemptToPatch, currentPID); patcherThread.detach(); // Let the thread run independently return 0; } extern "C" BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: logFile << "DLL injected." << std::endl; DisableThreadLibraryCalls(hModule); CreateThread(nullptr, 0, MonitorProcess, nullptr, 0, nullptr); break; case DLL_THREAD_ATTACH: case DLL_THREAD_DETACH: case DLL_PROCESS_DETACH: break; } return TRUE; }
f3a3713dcea14f7824aecc01124970ae
{ "intermediate": 0.3312757611274719, "beginner": 0.5021449327468872, "expert": 0.16657935082912445 }
42,729
Hi How to attach any files to the incident record through inbound email action. In the instance there is a OOTB create incident inbound email action but there is no any attachment related code over there.
e6cce777240694e7c0a1b7cf0c25e0be
{ "intermediate": 0.4247939884662628, "beginner": 0.203782320022583, "expert": 0.3714236617088318 }
42,730
my latex doc compiles but wont produce pdf logs dont say anything
5dbccfd71601a52fc7b6192baffc289f
{ "intermediate": 0.36078882217407227, "beginner": 0.38611748814582825, "expert": 0.2530937194824219 }
42,731
i opened a .ipynb file in vs code. in the first box thing (i dont know the official word for it) there is this code: ""# NOTE: An OpenAI API key must be set here for application initialization, even if not in use. # If you're not utilizing OpenAI models, assign a placeholder string (e.g., "not_used"). import os os.environ["OPENAI_API_KEY"] ="sk-1aNKea1KYKNfi5kPebSkT3BlhkFJSM9VBu1Z0nNZlwGHXQxB""" when i press the play looking symbol, there is a message that pops up at the top of vs code asking me about a kernel? there is an option to click on 'exisiting Jupyter server' and when i click on that a message asks me to 'enter the url of the running Jupyter server" i have no idea what any of this means. please help!
929daf02b3a554bd0dfce0ee526f03b3
{ "intermediate": 0.7243923544883728, "beginner": 0.053186964243650436, "expert": 0.22242066264152527 }
42,732
comment faire pour que le conteneur de l’image (à la bordure inférieure arrondie) soit encore plus arrondie. de plus expliques moi comment faire pour croper l’image en la zoomant et la décalant vers le haut import 'package:flutter/material.dart'; void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: MyHomePage(), ); } } class MyHomePage extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( body: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ Expanded( child: Stack( fit: StackFit.expand, children: [ ClipPath( clipper: BottomRoundClipper(), child: Container( color: Color(0xFFD9D9D9), child: Image.asset( 'assets/main.png', fit: BoxFit.cover, ), ), ), Positioned( left: 0, right: 0, bottom: 70.0, // Ajustez la position verticale selon votre besoin child: Center( child: Text( 'Bienvenue sur All\'O', style: TextStyle( color: Colors.white, fontSize: 28.0, fontFamily: "NeueRegrade", fontWeight: FontWeight.bold, ), ), ), ), ], ), ), Padding( padding: const EdgeInsets.all(20.0), child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ Align( alignment: Alignment.center, child: SizedBox( width: 259, height: 55, child: ElevatedButton( onPressed: () { print('Button 1'); }, style: ButtonStyle( backgroundColor: MaterialStateProperty.all(Color(0xFFD4D7EC)), ), child: Text( 'Me connecter', style: TextStyle( color: Color(0xFF0F0D11), fontSize: 18.0, fontFamily: "NeueRegrade", fontWeight: FontWeight.w600, ), ), ), ), ), TextButton( onPressed: () { print('Button 2'); }, style: ButtonStyle( overlayColor: MaterialStateProperty.all(Colors.transparent), ), child: Text( 'Créer mon compte', style: TextStyle( color: Color(0xFF0F0D11), fontSize: 14.0, ), ), ), ], ), ), ], ), ); } } class BottomRoundClipper extends CustomClipper<Path> { @override Path getClip(Size size) { final path = Path(); path.lineTo(0, size.height - 60); path.quadraticBezierTo(size.width / 2, size.height , size.width, size.height - 60); path.lineTo(size.width, 0); path.close(); return path; } @override bool shouldReclip(covariant CustomClipper<Path> oldClipper) => false; }
c97df5bda23ae7765eb8b72c95995cdc
{ "intermediate": 0.3595365881919861, "beginner": 0.44524675607681274, "expert": 0.19521665573120117 }
42,733
Кажется, этому коду нужен рефакторинг, исправь проблемные места, если такие имеются, и отправь полный код исправленной программы: #include "pch.h" #include <Windows.h> #include <tlhelp32.h> #include <psapi.h> #include <fstream> #include <vector> #include <string> #include <memory> #include <thread> std::ofstream logFile("patcher_log.txt", std::ios::out); bool PatchProcess(DWORD processID) { HANDLE hProcess = OpenProcess(PROCESS_VM_OPERATION | PROCESS_VM_READ | PROCESS_VM_WRITE, FALSE, processID); if (!hProcess) { logFile << "Failed to open the target process." << std::endl; return false; } auto processCloser = std::shared_ptr<void>( hProcess, [](HANDLE handle) { CloseHandle(handle); } ); BYTE signatureBytes[] = { 0x85, 0xC0, 0x74, 0x57, 0x5F, 0xB8, 0x01 }; BYTE patchByte = 0x00; MEMORY_BASIC_INFORMATION mbi{ 0 }; bool success = false; for (BYTE* addr = nullptr; VirtualQueryEx(hProcess, addr, &mbi, sizeof(mbi)) && addr < (BYTE*)0x7FFFFFFF; addr += mbi.RegionSize) { if (mbi.State == MEM_COMMIT && (mbi.Protect == PAGE_EXECUTE_READWRITE || mbi.Protect == PAGE_EXECUTE_READ)) { std::vector<BYTE> buffer(mbi.RegionSize); SIZE_T bytesRead; if (ReadProcessMemory(hProcess, mbi.BaseAddress, buffer.data(), mbi.RegionSize, &bytesRead)) { for (size_t j = 0; j < bytesRead - sizeof(signatureBytes); ++j) { if (memcmp(buffer.data() + j, signatureBytes, sizeof(signatureBytes)) == 0) { DWORD oldProtect; if (VirtualProtectEx(hProcess, addr + j + sizeof(signatureBytes) - 1, 1, PAGE_EXECUTE_READWRITE, &oldProtect)) { if (WriteProcessMemory(hProcess, addr + j + sizeof(signatureBytes) - 1, &patchByte, 1, nullptr)) { VirtualProtectEx(hProcess, addr + j + sizeof(signatureBytes) - 1, 1, oldProtect, &oldProtect); logFile << "Signature patched." << std::endl; success = true; return success; } } } } } } } return success; } void AttemptToPatch(DWORD currentPID) { logFile << "Attempting to patch current process ID : " << currentPID << " in a separate thread." << std::endl; while (true) { if (PatchProcess(currentPID)) { logFile << "Current process patched successfully." << std::endl; break; } else { logFile << "Failed to patch the current process.Retrying…" << std::endl; std::this_thread::sleep_for(std::chrono::seconds(5)); // Pause before retrying } } } DWORD WINAPI MonitorProcess(LPVOID lpParam) { DWORD currentPID = GetCurrentProcessId(); // Spin off a separate thread to attempt patching without blocking std::thread patcherThread(AttemptToPatch, currentPID); patcherThread.detach(); // Let the thread run independently return 0; } extern "C" BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: logFile << "DLL injected." << std::endl; DisableThreadLibraryCalls(hModule); CreateThread(nullptr, 0, MonitorProcess, nullptr, 0, nullptr); break; case DLL_THREAD_ATTACH: case DLL_THREAD_DETACH: case DLL_PROCESS_DETACH: break; } return TRUE; }
de2a2a633062560c022e619b557353f1
{ "intermediate": 0.30990707874298096, "beginner": 0.5165427923202515, "expert": 0.17355014383792877 }
42,734
Write a python script to call this API request: POST /api/chat HTTP/2 Host: chatbot-ui-free.vercel.app User-Agent: Mozilla/5.0 (Windows NT 10.0; rv:109.0) Gecko/20100101 Firefox/118.0 Accept: */* Accept-Language: en-US,en;q=0.5 Accept-Encoding: gzip, deflate, br Referer: https://chatbot-ui-free.vercel.app/en x-auth-code: KJr4wuAIIkljB Content-Type: application/json Content-Length: 241 Origin: https://chatbot-ui-free.vercel.app DNT: 1 Connection: keep-alive Sec-Fetch-Dest: empty Sec-Fetch-Mode: cors Sec-Fetch-Site: same-origin TE: trailers With the following request: {"conversationId":"e5aa5449-6d08-49b8-af5d-059a904c2ece","model":{"id":"gpt-4-turbo-preview","name":"GPT-4-Turbo","maxLength":260000,"tokenLimit":126000,"context":"128K"},"messages":[{"role":"user","content":"user"}],"key":"","prompt":"sys"}
0c78ae3161983919acccc4fb04ba4b9e
{ "intermediate": 0.48737508058547974, "beginner": 0.16914884746074677, "expert": 0.3434761166572571 }
42,735
When I click on my incident caller details. I want see only User Id and email address. How to achieve this task.
e8509489d286ee01102288e4356a75b4
{ "intermediate": 0.4364626407623291, "beginner": 0.20230065286159515, "expert": 0.36123669147491455 }
42,736
I need to provide a button on top right corner to export list view of incident table in excel as same as OOTB export excel list menu in servicenow
a70e0aca29c7ed0e7dc1b5405c83ded2
{ "intermediate": 0.3787584900856018, "beginner": 0.20362979173660278, "expert": 0.4176117181777954 }
42,737
Проведи рефакторинг кода на C++ по лучшим best practices и поправь комментарии, кажется, их слишком много: #include "pch.h" #include <Windows.h> #include <tlhelp32.h> #include <psapi.h> #include <fstream> #include <vector> #include <string> #include <memory> #include <thread> // Класс для управления логированием в файл class Logger { public: // Конструктор открывает файл для записи Logger(const std::string& filename) : logFile(filename, std::ios::out) {} // Функция записи сообщения в лог void Log(const std::string& message) { if (logFile.is_open()) { logFile << message << std::endl; } } // Деструктор закрывает файл при уничтожении объекта Logger ~Logger() { if (logFile.is_open()) { logFile.close(); } } private: std::ofstream logFile; // Поток файла для записи }; Logger logger("patcher_log.txt"); // Создаем глобальный объект логгера // Основная функция для патча процесса bool PatchProcess(DWORD processID) { // Открываем процесс с правами на чтение, запись и выполнение операций в его памяти HANDLE hProcess = OpenProcess(PROCESS_VM_OPERATION | PROCESS_VM_READ | PROCESS_VM_WRITE, FALSE, processID); if (!hProcess) { logger.Log("Failed to open the target process."); return false; } // Обрабатываем закрытие процесса автоматически при выходе из функции auto processCloser = std::shared_ptr<void>(hProcess, CloseHandle); // Сигнатура для поиска в памяти процесса BYTE signatureBytes[] = { 0x85, 0xC0, 0x74, 0x57, 0x5F, 0xB8, 0x01 }; BYTE patchByte = 0x00; // Байт, на который меняем сигнатуру MEMORY_BASIC_INFORMATION mbi{}; bool success = false; // Просматриваем память процесса в поисках сигнатуры for (BYTE* addr = nullptr; VirtualQueryEx(hProcess, addr, &mbi, sizeof(mbi)) && addr < (BYTE*)0x7FFFFFFF; addr += mbi.RegionSize) { // Ищем сегменты памяти с коммитированными страницами и разрешением на выполнение/чтение if (mbi.State == MEM_COMMIT && (mbi.Protect == PAGE_EXECUTE_READWRITE || mbi.Protect == PAGE_EXECUTE_READ)) { std::vector<BYTE> buffer(mbi.RegionSize); SIZE_T bytesRead; // Читаем память из процесса в локальный буфер для поиска if (ReadProcessMemory(hProcess, mbi.BaseAddress, buffer.data(), mbi.RegionSize, &bytesRead)) { // Обходим буфер в поисках сигнатуры for (size_t j = 0; j < bytesRead - sizeof(signatureBytes); ++j) { if (memcmp(buffer.data() + j, signatureBytes, sizeof(signatureBytes)) == 0) { DWORD oldProtect; // Изменяем защиту страницы на запись, чтобы применить патч if (VirtualProtectEx(hProcess, addr + j + sizeof(signatureBytes) - 1, 1, PAGE_EXECUTE_READWRITE, &oldProtect)) { // Производим запись патча if (WriteProcessMemory(hProcess, addr + j + sizeof(signatureBytes) - 1, &patchByte, 1, nullptr)) { // Возвращаем оригинальную защиту страницы после записи VirtualProtectEx(hProcess, addr + j + sizeof(signatureBytes) - 1, 1, oldProtect, &oldProtect); logger.Log("Signature patched."); success = true; // Выходим из функции после успешного применения патча return success; } // Возвращаем оригинальную защиту страницы, если запись не удалась VirtualProtectEx(hProcess, addr + j + sizeof(signatureBytes) - 1, 1, oldProtect, &oldProtect); } } } } } } return success; } // Функция для попытки пропатчить текущий процесс в отдельном потоке void AttemptToPatch(DWORD currentPID) { logger.Log("Attempting to patch current process ID : " + std::to_string(currentPID) + " in a separate thread."); while (true) { if (PatchProcess(currentPID)) { logger.Log("Current process patched successfully."); break; } else { logger.Log("Failed to patch the current process.Retrying…"); // Ожидаем перед следующей попыткой std::this_thread::sleep_for(std::chrono::seconds(5)); } } } // Функция-монитор для создания потока патча DWORD WINAPI MonitorProcess(LPVOID lpParam) { DWORD currentPID = GetCurrentProcessId(); // Создаем отдельный поток для попыток патча std::thread patcherThread(AttemptToPatch, currentPID); patcherThread.detach(); // Позволяем потоку работать независимо return 0; } // Точка входа DLL extern "C" BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: logger.Log("DLL injected."); // Отключаем вызовы DLL для созданных и уничтоженных потоков DisableThreadLibraryCalls(hModule); // Создаем поток для мониторинга и возможности патча CreateThread(nullptr, 0, MonitorProcess, nullptr, 0, nullptr); break; case DLL_THREAD_ATTACH: case DLL_THREAD_DETACH: case DLL_PROCESS_DETACH: break; } return TRUE; }
198db66efd3b1c1cdd9e3d74a2d365b1
{ "intermediate": 0.3917011320590973, "beginner": 0.36292606592178345, "expert": 0.24537275731563568 }
42,738
You are a Python expert who can provide clear, concise, high-quality code. " import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns import cv2 import random import tensorflow as tf import tkinter as tk from tkinter import filedialog from PIL import ImageTk, Image from ipywidgets import interact, interactive, fixed, interact_manual import ipywidgets as widgets from IPython.display import display, clear_output from tensorflow.keras.preprocessing import image from tensorflow.keras.optimizers import Adam, SGD, RMSprop, AdamW, Adadelta, Adagrad, Adamax, Adafactor, Nadam, Ftrl from tensorflow.keras.preprocessing.image import ImageDataGenerator from tqdm import tqdm import os from sklearn.utils import shuffle from sklearn.preprocessing import LabelEncoder from sklearn.model_selection import train_test_split from tensorflow.keras.models import Sequential, Model, load_model from tensorflow.keras.layers import ( GlobalAveragePooling2D, Dropout, Dense, Conv2D, MaxPooling2D, Flatten, Dropout, BatchNormalization, Activation, concatenate, Conv2DTranspose, Input, Reshape, UpSampling2D, ) from tensorflow.keras.applications import ( EfficientNetV2B0, EfficientNetV2B1, EfficientNetV2B2, EfficientNetV2B3, EfficientNetV2L, EfficientNetV2M, EfficientNetV2S, ) from tensorflow.keras.applications import Xception from tensorflow.keras.applications import VGG16, VGG19 from tensorflow.keras.applications import ResNet50, ResNet101, ResNet152, ResNetRS50, ResNetRS101 from tensorflow.keras.applications import InceptionResNetV2, ConvNeXtXLarge, ConvNeXtBase, DenseNet121, MobileNetV2, NASNetLarge, NASNetMobile from tensorflow.keras.utils import to_categorical from tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau, TensorBoard, ModelCheckpoint from sklearn.metrics import classification_report, confusion_matrix import ipywidgets as widgets import io from PIL import Image from IPython.display import display, clear_output from warnings import filterwarnings from google.colab import drive drive.mount("/content/gdrive") def load_data(data_folders): X_data = [] # Combined data y_class_labels = [] # Combined classification labels y_seg_labels = [] # Combined segmentation labels for folderPath in data_folders: for label in labels: label_folder_path = os.path.join(folderPath, label) for filename in tqdm(os.listdir(label_folder_path)): if filename.endswith(".jpg"): img = cv2.imread(os.path.join(label_folder_path, filename)) img = cv2.resize(img, (image_size, image_size)) X_data.append(img) y_class_labels.append(label) seg_filename = filename.split(".")[0] + ".png" seg_img = cv2.imread(os.path.join(label_folder_path, seg_filename), 0) seg_img = cv2.resize(seg_img, (image_size, image_size)) seg_img = np.where(seg_img > 0, 1, 0) # Convert segmentation mask to binary y_seg_labels.append(seg_img) X_data = np.array(X_data) y_class_labels = np.array(y_class_labels) y_seg_labels = np.array(y_seg_labels) X_data, y_class_labels, y_seg_labels = shuffle(X_data, y_class_labels, y_seg_labels, random_state=101) return X_data, y_class_labels, y_seg_labels def split_data(X_data, y_class_labels, y_seg_labels, class_data_counts): X_train = [] y_train_class = [] y_train_seg = [] X_val = [] y_val_class = [] y_val_seg = [] X_test = [] y_test_class = [] y_test_seg = [] for label, count in class_data_counts.items(): label_indices = np.where(y_class_labels == label)[0] class_X_data = X_data[label_indices] class_y_class_labels = y_class_labels[label_indices] class_y_seg_labels = y_seg_labels[label_indices] train_count = count[0] val_count = count[1] test_count = count[2] class_X_train = class_X_data[:train_count] class_y_train_class = class_y_class_labels[:train_count] class_y_train_seg = class_y_seg_labels[:train_count] class_X_val = class_X_data[train_count: train_count + val_count] class_y_val_class = class_y_class_labels[train_count: train_count + val_count] class_y_val_seg = class_y_seg_labels[train_count: train_count + val_count] class_X_test = class_X_data[train_count + val_count: train_count + val_count + test_count] class_y_test_class = class_y_class_labels[train_count + val_count: train_count + val_count + test_count] class_y_test_seg = class_y_seg_labels[train_count + val_count: train_count + val_count + test_count] X_train.extend(class_X_train) y_train_class.extend(class_y_train_class) y_train_seg.extend(class_y_train_seg) X_val.extend(class_X_val) y_val_class.extend(class_y_val_class) y_val_seg.extend(class_y_val_seg) X_test.extend(class_X_test) y_test_class.extend(class_y_test_class) y_test_seg.extend(class_y_test_seg) # Convert class labels to categorical label_encoder = LabelEncoder() y_train_class_encoded = label_encoder.fit_transform(y_train_class) y_train_class_categorical = to_categorical(y_train_class_encoded) y_val_class_encoded = label_encoder.transform(y_val_class) y_val_class_categorical = to_categorical(y_val_class_encoded) y_test_class_encoded = label_encoder.transform(y_test_class) y_test_class_categorical = to_categorical(y_test_class_encoded) return ( np.array(X_train), np.array(y_train_class_categorical), np.array(y_train_seg), np.array(X_val), np.array(y_val_class_categorical), np.array(y_val_seg), np.array(X_test), np.array(y_test_class_categorical), np.array(y_test_seg), ) def count_labels(y_class_categorical, label_encoder): # Convert one-hot encoded labels back to label encoded y_class_labels = np.argmax(y_class_categorical, axis=1) # Convert label encoded labels back to original class names y_class_names = label_encoder.inverse_transform(y_class_labels) unique, counts = np.unique(y_class_names, return_counts=True) return dict(zip(unique, counts)) def build_model(input_shape, num_classes): num_filter = 32 # 16/32 best, 8: best classification but no segment # Encoder (Done) inputs = Input(input_shape) conv1 = Conv2D(num_filter * 1, 3, activation="linear", padding="same", strides=1)(inputs) bn1 = BatchNormalization()(conv1) relu1 = Activation("relu")(bn1) conv2 = Conv2D(num_filter * 1, 3, activation="linear", padding="same", strides=1)(relu1) bn2 = BatchNormalization()(conv2) relu2 = Activation("relu")(bn2) down1 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu2) conv3 = Conv2D(num_filter * 2, 3, activation="linear", padding="same", strides=1)(down1) bn3 = BatchNormalization()(conv3) relu3 = Activation("relu")(bn3) conv4 = Conv2D(num_filter * 2, 3, activation="linear", padding="same", strides=1)(relu3) bn4 = BatchNormalization()(conv4) relu4 = Activation("relu")(bn4) down2 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu4) conv5 = Conv2D(num_filter * 4, 3, activation="linear", padding="same", strides=1)(down2) bn5 = BatchNormalization()(conv5) relu5 = Activation("relu")(bn5) conv6 = Conv2D(num_filter * 4, 3, activation="linear", padding="same", strides=1)(relu5) bn6 = BatchNormalization()(conv6) relu6 = Activation("relu")(bn6) down3 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu6) conv7 = Conv2D(num_filter * 8, 3, activation="linear", padding="same", strides=1)(down3) bn7 = BatchNormalization()(conv7) relu7 = Activation("relu")(bn7) conv8 = Conv2D(num_filter * 8, 3, activation="linear", padding="same", strides=1)(relu7) bn8 = BatchNormalization()(conv8) relu8 = Activation("relu")(bn8) # Middle down4 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu8) conv9 = Conv2D(num_filter * 16, 3, activation="linear", padding="same", strides=1)(down4) bn9 = BatchNormalization()(conv9) relu9 = Activation("relu")(bn9) conv10 = Conv2D(num_filter * 16, 3, activation="linear", padding="same", strides=1)(relu9) bn10 = BatchNormalization()(conv10) relu10 = Activation("relu")(bn10) up1 = UpSampling2D(size=(2, 2), interpolation="bilinear")(relu10) # Decoder (Done) concat1 = concatenate([up1, relu8], axis=-1) # , axis=3 conv11 = Conv2D(num_filter * 8, 3, activation="linear", padding="same", strides=1)(concat1) bn11 = BatchNormalization()(conv11) relu11 = Activation("relu")(bn11) conv12 = Conv2D(num_filter * 8, 3, activation="linear", padding="same", strides=1)(relu11) bn12 = BatchNormalization()(conv12) relu12 = Activation("relu")(bn12) up2 = UpSampling2D(size=(2, 2), interpolation="bilinear")(relu12) concat2 = concatenate([up2, relu6], axis=-1) # , axis=3 conv13 = Conv2D(num_filter * 4, 3, activation="linear", padding="same", strides=1)(concat2) bn13 = BatchNormalization()(conv13) relu13 = Activation("relu")(bn13) conv14 = Conv2D(num_filter * 4, 3, activation="linear", padding="same", strides=1)(relu13) bn14 = BatchNormalization()(conv14) relu14 = Activation("relu")(bn14) up3 = UpSampling2D(size=(2, 2), interpolation="bilinear")(relu14) concat3 = concatenate([up3, relu4], axis=-1) # , axis=3 conv15 = Conv2D(num_filter * 2, 3, activation="linear", padding="same", strides=1)(concat3) bn15 = BatchNormalization()(conv15) relu15 = Activation("relu")(bn15) conv16 = Conv2D(num_filter * 2, 3, activation="linear", padding="same", strides=1)(relu15) bn16 = BatchNormalization()(conv16) relu16 = Activation("relu")(bn16) up4 = UpSampling2D(size=(2, 2), interpolation="bilinear")(relu16) concat4 = concatenate([up4, relu2], axis=-1) # , axis=3 conv17 = Conv2D(num_filter * 1, 3, activation="linear", padding="same", strides=1)(concat4) bn17 = BatchNormalization()(conv17) relu17 = Activation("relu")(bn17) conv18 = Conv2D(num_filter * 1, 3, activation="linear", padding="same", strides=1)(relu17) bn18 = BatchNormalization()(conv18) relu18 = Activation("relu")(bn18) # Segmentation branch segmentation_output = Conv2D(1, 1, activation="sigmoid", name="segmentation_output")(relu18) # original # Classification branch (Not done) gap1 = GlobalAveragePooling2D()(relu8) gap2 = GlobalAveragePooling2D()(relu10) gap3 = GlobalAveragePooling2D()(relu12) conv20 = Conv2D(16, 3, activation="linear", padding="same", strides=1)(segmentation_output) bn20 = BatchNormalization()(conv20) relu20 = Activation("relu")(bn20) down5 = MaxPooling2D(pool_size=(4, 4), strides=4)(relu20) conv21 = Conv2D(32, 3, activation="linear", padding="same", strides=1)(down5) bn21 = BatchNormalization()(conv21) relu21 = Activation("relu")(bn21) down6 = MaxPooling2D(pool_size=(4, 4), strides=4)(relu21) conv22 = Conv2D(64, 3, activation="linear", padding="same", strides=1)(down6) bn22 = BatchNormalization()(conv22) relu22 = Activation("relu")(bn22) down7 = MaxPooling2D(pool_size=(4, 4), strides=4)(relu22) flatten1 = Flatten()(down7) concat5 = concatenate([gap1, gap2, gap3, flatten1], axis=-1) # FC layers fc1 = Dense(1024, activation="relu")(concat5) dropout1 = Dropout(0.5)(fc1) fc2 = Dense(1024, activation="relu")(dropout1) dropout2 = Dropout(0.5)(fc2) classification_output = Dense(num_classes, activation="softmax", name="classification_output")(dropout2) # Define the model model = Model(inputs=inputs, outputs=[classification_output, segmentation_output]) return model def segmentation_loss(y_true, y_pred): y_true = tf.cast(y_true, tf.float32) y_pred = tf.cast(y_pred, tf.float32) bce_loss = tf.keras.losses.binary_crossentropy(y_true, y_pred) smooth = 1e-5 intersection = tf.reduce_sum(y_true * y_pred) union = tf.reduce_sum(y_true) + tf.reduce_sum(y_pred) dice_loss = 1.0 - 2.0 * (intersection + smooth) / (union + smooth) segmentation_loss = bce_loss + 1 * dice_loss return segmentation_loss def train_model(model, X_train, y_train_class, y_train_seg, X_val, y_val_class, y_val_seg, batch_size, epochs): checkpoint = ModelCheckpoint( "multitask_best_weights.h5", monitor="val_classification_output_accuracy", save_best_only=True, mode="max", verbose=1,) reduce_lr = ReduceLROnPlateau( monitor="val_classification_output_accuracy", factor=0.3, patience=2, min_delta=0.001, mode="auto", verbose=1,) tensorboard = TensorBoard(log_dir="logs") model.compile( optimizer=Adam(lr=0.001), loss={"classification_output": "categorical_crossentropy", "segmentation_output": segmentation_loss}, metrics={"classification_output": "accuracy", "segmentation_output": "accuracy"}, loss_weights={"classification_output": 1, "segmentation_output": 1},) history = model.fit( X_train, {"classification_output": y_train_class, "segmentation_output": y_train_seg}, validation_data=(X_val, {"classification_output": y_val_class, "segmentation_output": y_val_seg}), epochs=epochs, verbose=1, batch_size=batch_size, callbacks=[checkpoint, reduce_lr, tensorboard],) return history def evaluate_model(model, X_test, y_test_class, y_test_seg): with tf.keras.utils.custom_object_scope({"segmentation_loss": segmentation_loss}): # Load the best model weights best_model = load_model("multitask_best_weights.h5") # Evaluate the model on test data test_loss, test_class_loss, test_seg_loss, test_class_acc, test_seg_acc = best_model.evaluate( X_test, {"classification_output": y_test_class, "segmentation_output": y_test_seg}) print("Test Classification Loss:", test_class_loss) print("Test Segmentation Loss:", test_seg_loss) print("Test Classification Accuracy:", test_class_acc) print("Test Segmentation Accuracy:", test_seg_acc) # Evaluate the model on validation data val_loss, val_class_loss, val_seg_loss, val_class_acc, val_seg_acc = best_model.evaluate( X_val, {'classification_output': y_val_class, 'segmentation_output': y_val_seg}) print("Validation Classification Loss:", val_class_loss) print("Validation Segmentation Loss:", val_seg_loss) print("Validation Classification Accuracy:", val_class_acc) print("Validation Segmentation Accuracy:", val_seg_acc) # Evaluate the model on training data train_loss, train_class_loss, train_seg_loss, train_class_acc, train_seg_acc = best_model.evaluate(X_train, {'classification_output': y_train_class, 'segmentation_output': y_train_seg}) print("Train Classification Loss:", train_class_loss) print("Train Segmentation Loss:", train_seg_loss) print("Train Classification Accuracy:", train_class_acc) print("Train Segmentation Accuracy:", train_seg_acc) # Return test classification accuracy return test_class_acc def plot_performance(history): # Plot classification accuracy classification_train_accuracy = history.history["classification_output_accuracy"] classification_val_accuracy = history.history["val_classification_output_accuracy"] plt.figure(figsize=(7, 3)) plt.plot(classification_train_accuracy, label="Training Accuracy") plt.plot(classification_val_accuracy, label="Validation Accuracy") plt.title("Classification Accuracy") plt.xlabel("Epochs") plt.ylabel("Accuracy") plt.legend() plt.show() # Plot classification loss classification_train_loss = history.history["classification_output_loss"] classification_val_loss = history.history["val_classification_output_loss"] plt.figure(figsize=(7, 3)) plt.plot(classification_train_loss, "b", label="Training Loss") plt.plot(classification_val_loss, "r", label="Validation Loss") plt.title("Classification Loss") plt.xlabel("Epochs") plt.ylabel("Loss") plt.legend() plt.show() # Plot segmentation accuracy segmentation_train_accuracy = history.history["segmentation_output_accuracy"] segmentation_val_accuracy = history.history["val_segmentation_output_accuracy"] plt.figure(figsize=(7, 3)) plt.plot(segmentation_train_accuracy, label="Training Accuracy") plt.plot(segmentation_val_accuracy, label="Validation Accuracy") plt.title("Segmentation Accuracy") plt.xlabel("Epochs") plt.ylabel("Accuracy") plt.legend() plt.show() # Plot segmentation loss segmentation_train_loss = history.history["segmentation_output_loss"] segmentation_val_loss = history.history["val_segmentation_output_loss"] plt.figure(figsize=(7, 3)) plt.plot(segmentation_train_loss, "b", label="Training Loss") plt.plot(segmentation_val_loss, "r", label="Validation Loss") plt.title("Segmentation Loss") plt.xlabel("Epochs") plt.ylabel("Loss") plt.legend() plt.show() # Set image size image_size = 224 # Define labels labels = ["bridge", "excess", "good"] # Set data folders data_folders = [ "/content/gdrive/MyDrive/Deep learning/FYP_2/4 Dataset Ratio 60 20 20/jit012/jit0/f_dip/train", "/content/gdrive/MyDrive/Deep learning/FYP_2/4 Dataset Ratio 60 20 20/jit012/jit0/f_dip/val", "/content/gdrive/MyDrive/Deep learning/FYP_2/4 Dataset Ratio 60 20 20/jit012/jit0/f_dip/test",] # Load data X_data, y_class_labels, y_seg_labels = load_data(data_folders) # Define train:val:test ratio for each class (ratio x4 = exact) class_data_counts = { "bridge": [40, 80, 80], "excess": [40, 80, 80], "good": [40, 80, 80], } # Split data X_train, y_train_class, y_train_seg, X_val, y_val_class, y_val_seg, X_test, y_test_class, y_test_seg = split_data( X_data, y_class_labels, y_seg_labels, class_data_counts) ''' print("Number of train images:", len(X_train)) print("Number of train binary masks:", len(y_train_seg)) print("Number of validation images:", len(X_val)) print("Number of validation binary masks:", len(y_val_seg)) print("Number of test images:", len(X_test)) print("Number of test binary masks:", len(y_test_seg)) ''' # Initialize the label encoder label_encoder = LabelEncoder() label_encoder.fit(y_class_labels) # Count the number of images of each class in the train, validation, and test sets train_counts = count_labels(y_train_class, label_encoder) val_counts = count_labels(y_val_class, label_encoder) test_counts = count_labels(y_test_class, label_encoder) print("Train counts: ", train_counts," Total in train set:", sum(train_counts.values())) print("Validation counts:", val_counts, " Total in validation set:", sum(val_counts.values())) print("Test counts: ", test_counts," Total in test set:", sum(test_counts.values())) # Build model input_shape = (image_size, image_size, 3) num_classes = len(labels) model = build_model(input_shape, num_classes) model.summary() # Train model n times test_class_acc_list = [] for i in range(5): print(f"\nTrain {i+1}:\n") model = build_model(input_shape, num_classes) batch_size = 16 epochs = 50 history = train_model(model, X_train, y_train_class, y_train_seg, X_val, y_val_class, y_val_seg, batch_size, epochs) # Evaluate model on test data test_class_acc = evaluate_model(model, X_test, y_test_class, y_test_seg) plot_performance(history) test_class_acc_list.append(test_class_acc) # Calculate average test classification accuracy average_test_class_acc = sum(test_class_acc_list) / len(test_class_acc_list) print("Test Classification Accuracy List:", test_class_acc_list) print("Average Test Classification Accuracy:", average_test_class_acc) " The above is the Python code with Keras to do multi-task learning with binary segmentation and classification using one mult-task learning model. Modify the code to change the model to resnet50 (from keras library), so no need to perform segmentation, only perform classification. Do not modify the other part of my code.
8f3560992581a0845d952ac2ece5bd5b
{ "intermediate": 0.3006076216697693, "beginner": 0.3237382769584656, "expert": 0.3756541907787323 }
42,739
I need to provide a button on top right corner to export list view template of incident table in excel in servicenow
e47efb8dcb17df9e3a0fab38f66aa3d2
{ "intermediate": 0.3767140507698059, "beginner": 0.2307366579771042, "expert": 0.3925492465496063 }
42,740
You are a Python expert who can provide clear, concise, high-quality code. " import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns import cv2 import random import tensorflow as tf import tkinter as tk from tkinter import filedialog from PIL import ImageTk, Image from ipywidgets import interact, interactive, fixed, interact_manual import ipywidgets as widgets from IPython.display import display, clear_output from tensorflow.keras.preprocessing import image from tensorflow.keras.optimizers import Adam, SGD, RMSprop, AdamW, Adadelta, Adagrad, Adamax, Adafactor, Nadam, Ftrl from tensorflow.keras.preprocessing.image import ImageDataGenerator from tqdm import tqdm import os from sklearn.utils import shuffle from sklearn.preprocessing import LabelEncoder from sklearn.model_selection import train_test_split from tensorflow.keras.models import Sequential, Model, load_model from tensorflow.keras.layers import ( GlobalAveragePooling2D, Dropout, Dense, Conv2D, MaxPooling2D, Flatten, Dropout, BatchNormalization, Activation, concatenate, Conv2DTranspose, Input, Reshape, UpSampling2D, ) from tensorflow.keras.applications import ( EfficientNetV2B0, EfficientNetV2B1, EfficientNetV2B2, EfficientNetV2B3, EfficientNetV2L, EfficientNetV2M, EfficientNetV2S, ) from tensorflow.keras.applications import Xception from tensorflow.keras.applications import VGG16, VGG19 from tensorflow.keras.applications import ResNet50, ResNet101, ResNet152, ResNetRS50, ResNetRS101 from tensorflow.keras.applications import InceptionResNetV2, ConvNeXtXLarge, ConvNeXtBase, DenseNet121, MobileNetV2, NASNetLarge, NASNetMobile from tensorflow.keras.utils import to_categorical from tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau, TensorBoard, ModelCheckpoint from sklearn.metrics import classification_report, confusion_matrix import ipywidgets as widgets import io from PIL import Image from IPython.display import display, clear_output from warnings import filterwarnings from google.colab import drive drive.mount("/content/gdrive") def load_data(data_folders): X_data = [] # Combined data y_class_labels = [] # Combined classification labels y_seg_labels = [] # Combined segmentation labels for folderPath in data_folders: for label in labels: label_folder_path = os.path.join(folderPath, label) for filename in tqdm(os.listdir(label_folder_path)): if filename.endswith(".jpg"): img = cv2.imread(os.path.join(label_folder_path, filename)) img = cv2.resize(img, (image_size, image_size)) X_data.append(img) y_class_labels.append(label) seg_filename = filename.split(".")[0] + ".png" seg_img = cv2.imread(os.path.join(label_folder_path, seg_filename), 0) seg_img = cv2.resize(seg_img, (image_size, image_size)) seg_img = np.where(seg_img > 0, 1, 0) # Convert segmentation mask to binary y_seg_labels.append(seg_img) X_data = np.array(X_data) y_class_labels = np.array(y_class_labels) y_seg_labels = np.array(y_seg_labels) X_data, y_class_labels, y_seg_labels = shuffle(X_data, y_class_labels, y_seg_labels, random_state=101) return X_data, y_class_labels, y_seg_labels def split_data(X_data, y_class_labels, y_seg_labels, class_data_counts): X_train = [] y_train_class = [] y_train_seg = [] X_val = [] y_val_class = [] y_val_seg = [] X_test = [] y_test_class = [] y_test_seg = [] for label, count in class_data_counts.items(): label_indices = np.where(y_class_labels == label)[0] class_X_data = X_data[label_indices] class_y_class_labels = y_class_labels[label_indices] class_y_seg_labels = y_seg_labels[label_indices] train_count = count[0] val_count = count[1] test_count = count[2] class_X_train = class_X_data[:train_count] class_y_train_class = class_y_class_labels[:train_count] class_y_train_seg = class_y_seg_labels[:train_count] class_X_val = class_X_data[train_count: train_count + val_count] class_y_val_class = class_y_class_labels[train_count: train_count + val_count] class_y_val_seg = class_y_seg_labels[train_count: train_count + val_count] class_X_test = class_X_data[train_count + val_count: train_count + val_count + test_count] class_y_test_class = class_y_class_labels[train_count + val_count: train_count + val_count + test_count] class_y_test_seg = class_y_seg_labels[train_count + val_count: train_count + val_count + test_count] X_train.extend(class_X_train) y_train_class.extend(class_y_train_class) y_train_seg.extend(class_y_train_seg) X_val.extend(class_X_val) y_val_class.extend(class_y_val_class) y_val_seg.extend(class_y_val_seg) X_test.extend(class_X_test) y_test_class.extend(class_y_test_class) y_test_seg.extend(class_y_test_seg) # Convert class labels to categorical label_encoder = LabelEncoder() y_train_class_encoded = label_encoder.fit_transform(y_train_class) y_train_class_categorical = to_categorical(y_train_class_encoded) y_val_class_encoded = label_encoder.transform(y_val_class) y_val_class_categorical = to_categorical(y_val_class_encoded) y_test_class_encoded = label_encoder.transform(y_test_class) y_test_class_categorical = to_categorical(y_test_class_encoded) return ( np.array(X_train), np.array(y_train_class_categorical), np.array(y_train_seg), np.array(X_val), np.array(y_val_class_categorical), np.array(y_val_seg), np.array(X_test), np.array(y_test_class_categorical), np.array(y_test_seg), ) def count_labels(y_class_categorical, label_encoder): # Convert one-hot encoded labels back to label encoded y_class_labels = np.argmax(y_class_categorical, axis=1) # Convert label encoded labels back to original class names y_class_names = label_encoder.inverse_transform(y_class_labels) unique, counts = np.unique(y_class_names, return_counts=True) return dict(zip(unique, counts)) def build_model(input_shape, num_classes): num_filter = 32 # 16/32 best, 8: best classification but no segment # Encoder (Done) inputs = Input(input_shape) conv1 = Conv2D(num_filter * 1, 3, activation="linear", padding="same", strides=1)(inputs) bn1 = BatchNormalization()(conv1) relu1 = Activation("relu")(bn1) conv2 = Conv2D(num_filter * 1, 3, activation="linear", padding="same", strides=1)(relu1) bn2 = BatchNormalization()(conv2) relu2 = Activation("relu")(bn2) down1 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu2) conv3 = Conv2D(num_filter * 2, 3, activation="linear", padding="same", strides=1)(down1) bn3 = BatchNormalization()(conv3) relu3 = Activation("relu")(bn3) conv4 = Conv2D(num_filter * 2, 3, activation="linear", padding="same", strides=1)(relu3) bn4 = BatchNormalization()(conv4) relu4 = Activation("relu")(bn4) down2 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu4) conv5 = Conv2D(num_filter * 4, 3, activation="linear", padding="same", strides=1)(down2) bn5 = BatchNormalization()(conv5) relu5 = Activation("relu")(bn5) conv6 = Conv2D(num_filter * 4, 3, activation="linear", padding="same", strides=1)(relu5) bn6 = BatchNormalization()(conv6) relu6 = Activation("relu")(bn6) down3 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu6) conv7 = Conv2D(num_filter * 8, 3, activation="linear", padding="same", strides=1)(down3) bn7 = BatchNormalization()(conv7) relu7 = Activation("relu")(bn7) conv8 = Conv2D(num_filter * 8, 3, activation="linear", padding="same", strides=1)(relu7) bn8 = BatchNormalization()(conv8) relu8 = Activation("relu")(bn8) # Middle down4 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu8) conv9 = Conv2D(num_filter * 16, 3, activation="linear", padding="same", strides=1)(down4) bn9 = BatchNormalization()(conv9) relu9 = Activation("relu")(bn9) conv10 = Conv2D(num_filter * 16, 3, activation="linear", padding="same", strides=1)(relu9) bn10 = BatchNormalization()(conv10) relu10 = Activation("relu")(bn10) up1 = UpSampling2D(size=(2, 2), interpolation="bilinear")(relu10) # Decoder (Done) concat1 = concatenate([up1, relu8], axis=-1) # , axis=3 conv11 = Conv2D(num_filter * 8, 3, activation="linear", padding="same", strides=1)(concat1) bn11 = BatchNormalization()(conv11) relu11 = Activation("relu")(bn11) conv12 = Conv2D(num_filter * 8, 3, activation="linear", padding="same", strides=1)(relu11) bn12 = BatchNormalization()(conv12) relu12 = Activation("relu")(bn12) up2 = UpSampling2D(size=(2, 2), interpolation="bilinear")(relu12) concat2 = concatenate([up2, relu6], axis=-1) # , axis=3 conv13 = Conv2D(num_filter * 4, 3, activation="linear", padding="same", strides=1)(concat2) bn13 = BatchNormalization()(conv13) relu13 = Activation("relu")(bn13) conv14 = Conv2D(num_filter * 4, 3, activation="linear", padding="same", strides=1)(relu13) bn14 = BatchNormalization()(conv14) relu14 = Activation("relu")(bn14) up3 = UpSampling2D(size=(2, 2), interpolation="bilinear")(relu14) concat3 = concatenate([up3, relu4], axis=-1) # , axis=3 conv15 = Conv2D(num_filter * 2, 3, activation="linear", padding="same", strides=1)(concat3) bn15 = BatchNormalization()(conv15) relu15 = Activation("relu")(bn15) conv16 = Conv2D(num_filter * 2, 3, activation="linear", padding="same", strides=1)(relu15) bn16 = BatchNormalization()(conv16) relu16 = Activation("relu")(bn16) up4 = UpSampling2D(size=(2, 2), interpolation="bilinear")(relu16) concat4 = concatenate([up4, relu2], axis=-1) # , axis=3 conv17 = Conv2D(num_filter * 1, 3, activation="linear", padding="same", strides=1)(concat4) bn17 = BatchNormalization()(conv17) relu17 = Activation("relu")(bn17) conv18 = Conv2D(num_filter * 1, 3, activation="linear", padding="same", strides=1)(relu17) bn18 = BatchNormalization()(conv18) relu18 = Activation("relu")(bn18) # Segmentation branch segmentation_output = Conv2D(1, 1, activation="sigmoid", name="segmentation_output")(relu18) # original # Classification branch (Not done) gap1 = GlobalAveragePooling2D()(relu8) gap2 = GlobalAveragePooling2D()(relu10) gap3 = GlobalAveragePooling2D()(relu12) conv20 = Conv2D(16, 3, activation="linear", padding="same", strides=1)(segmentation_output) bn20 = BatchNormalization()(conv20) relu20 = Activation("relu")(bn20) down5 = MaxPooling2D(pool_size=(4, 4), strides=4)(relu20) conv21 = Conv2D(32, 3, activation="linear", padding="same", strides=1)(down5) bn21 = BatchNormalization()(conv21) relu21 = Activation("relu")(bn21) down6 = MaxPooling2D(pool_size=(4, 4), strides=4)(relu21) conv22 = Conv2D(64, 3, activation="linear", padding="same", strides=1)(down6) bn22 = BatchNormalization()(conv22) relu22 = Activation("relu")(bn22) down7 = MaxPooling2D(pool_size=(4, 4), strides=4)(relu22) flatten1 = Flatten()(down7) concat5 = concatenate([gap1, gap2, gap3, flatten1], axis=-1) # FC layers fc1 = Dense(1024, activation="relu")(concat5) dropout1 = Dropout(0.5)(fc1) fc2 = Dense(1024, activation="relu")(dropout1) dropout2 = Dropout(0.5)(fc2) classification_output = Dense(num_classes, activation="softmax", name="classification_output")(dropout2) # Define the model model = Model(inputs=inputs, outputs=[classification_output, segmentation_output]) return model def segmentation_loss(y_true, y_pred): y_true = tf.cast(y_true, tf.float32) y_pred = tf.cast(y_pred, tf.float32) bce_loss = tf.keras.losses.binary_crossentropy(y_true, y_pred) smooth = 1e-5 intersection = tf.reduce_sum(y_true * y_pred) union = tf.reduce_sum(y_true) + tf.reduce_sum(y_pred) dice_loss = 1.0 - 2.0 * (intersection + smooth) / (union + smooth) segmentation_loss = bce_loss + 1 * dice_loss return segmentation_loss def train_model(model, X_train, y_train_class, y_train_seg, X_val, y_val_class, y_val_seg, batch_size, epochs): checkpoint = ModelCheckpoint( "multitask_best_weights.h5", monitor="val_classification_output_accuracy", save_best_only=True, mode="max", verbose=1,) reduce_lr = ReduceLROnPlateau( monitor="val_classification_output_accuracy", factor=0.3, patience=2, min_delta=0.001, mode="auto", verbose=1,) tensorboard = TensorBoard(log_dir="logs") model.compile( optimizer=Adam(lr=0.001), loss={"classification_output": "categorical_crossentropy", "segmentation_output": segmentation_loss}, metrics={"classification_output": "accuracy", "segmentation_output": "accuracy"}, loss_weights={"classification_output": 1, "segmentation_output": 1},) history = model.fit( X_train, {"classification_output": y_train_class, "segmentation_output": y_train_seg}, validation_data=(X_val, {"classification_output": y_val_class, "segmentation_output": y_val_seg}), epochs=epochs, verbose=1, batch_size=batch_size, callbacks=[checkpoint, reduce_lr, tensorboard],) return history def evaluate_model(model, X_test, y_test_class, y_test_seg): with tf.keras.utils.custom_object_scope({"segmentation_loss": segmentation_loss}): # Load the best model weights best_model = load_model("multitask_best_weights.h5") # Evaluate the model on test data test_loss, test_class_loss, test_seg_loss, test_class_acc, test_seg_acc = best_model.evaluate( X_test, {"classification_output": y_test_class, "segmentation_output": y_test_seg}) print("Test Classification Loss:", test_class_loss) print("Test Segmentation Loss:", test_seg_loss) print("Test Classification Accuracy:", test_class_acc) print("Test Segmentation Accuracy:", test_seg_acc) # Evaluate the model on validation data val_loss, val_class_loss, val_seg_loss, val_class_acc, val_seg_acc = best_model.evaluate( X_val, {'classification_output': y_val_class, 'segmentation_output': y_val_seg}) print("Validation Classification Loss:", val_class_loss) print("Validation Segmentation Loss:", val_seg_loss) print("Validation Classification Accuracy:", val_class_acc) print("Validation Segmentation Accuracy:", val_seg_acc) # Evaluate the model on training data train_loss, train_class_loss, train_seg_loss, train_class_acc, train_seg_acc = best_model.evaluate(X_train, {'classification_output': y_train_class, 'segmentation_output': y_train_seg}) print("Train Classification Loss:", train_class_loss) print("Train Segmentation Loss:", train_seg_loss) print("Train Classification Accuracy:", train_class_acc) print("Train Segmentation Accuracy:", train_seg_acc) # Return test classification accuracy return test_class_acc def plot_performance(history): # Plot classification accuracy classification_train_accuracy = history.history["classification_output_accuracy"] classification_val_accuracy = history.history["val_classification_output_accuracy"] plt.figure(figsize=(7, 3)) plt.plot(classification_train_accuracy, label="Training Accuracy") plt.plot(classification_val_accuracy, label="Validation Accuracy") plt.title("Classification Accuracy") plt.xlabel("Epochs") plt.ylabel("Accuracy") plt.legend() plt.show() # Plot classification loss classification_train_loss = history.history["classification_output_loss"] classification_val_loss = history.history["val_classification_output_loss"] plt.figure(figsize=(7, 3)) plt.plot(classification_train_loss, "b", label="Training Loss") plt.plot(classification_val_loss, "r", label="Validation Loss") plt.title("Classification Loss") plt.xlabel("Epochs") plt.ylabel("Loss") plt.legend() plt.show() # Plot segmentation accuracy segmentation_train_accuracy = history.history["segmentation_output_accuracy"] segmentation_val_accuracy = history.history["val_segmentation_output_accuracy"] plt.figure(figsize=(7, 3)) plt.plot(segmentation_train_accuracy, label="Training Accuracy") plt.plot(segmentation_val_accuracy, label="Validation Accuracy") plt.title("Segmentation Accuracy") plt.xlabel("Epochs") plt.ylabel("Accuracy") plt.legend() plt.show() # Plot segmentation loss segmentation_train_loss = history.history["segmentation_output_loss"] segmentation_val_loss = history.history["val_segmentation_output_loss"] plt.figure(figsize=(7, 3)) plt.plot(segmentation_train_loss, "b", label="Training Loss") plt.plot(segmentation_val_loss, "r", label="Validation Loss") plt.title("Segmentation Loss") plt.xlabel("Epochs") plt.ylabel("Loss") plt.legend() plt.show() # Set image size image_size = 224 # Define labels labels = ["bridge", "excess", "good"] # Set data folders data_folders = [ "/content/gdrive/MyDrive/Deep learning/FYP_2/4 Dataset Ratio 60 20 20/jit012/jit0/f_dip/train", "/content/gdrive/MyDrive/Deep learning/FYP_2/4 Dataset Ratio 60 20 20/jit012/jit0/f_dip/val", "/content/gdrive/MyDrive/Deep learning/FYP_2/4 Dataset Ratio 60 20 20/jit012/jit0/f_dip/test",] # Load data X_data, y_class_labels, y_seg_labels = load_data(data_folders) # Define train:val:test ratio for each class (ratio x4 = exact) class_data_counts = { "bridge": [40, 80, 80], "excess": [40, 80, 80], "good": [40, 80, 80], } # Split data X_train, y_train_class, y_train_seg, X_val, y_val_class, y_val_seg, X_test, y_test_class, y_test_seg = split_data( X_data, y_class_labels, y_seg_labels, class_data_counts) ''' print("Number of train images:", len(X_train)) print("Number of train binary masks:", len(y_train_seg)) print("Number of validation images:", len(X_val)) print("Number of validation binary masks:", len(y_val_seg)) print("Number of test images:", len(X_test)) print("Number of test binary masks:", len(y_test_seg)) ''' # Initialize the label encoder label_encoder = LabelEncoder() label_encoder.fit(y_class_labels) # Count the number of images of each class in the train, validation, and test sets train_counts = count_labels(y_train_class, label_encoder) val_counts = count_labels(y_val_class, label_encoder) test_counts = count_labels(y_test_class, label_encoder) print("Train counts: ", train_counts," Total in train set:", sum(train_counts.values())) print("Validation counts:", val_counts, " Total in validation set:", sum(val_counts.values())) print("Test counts: ", test_counts," Total in test set:", sum(test_counts.values())) # Build model input_shape = (image_size, image_size, 3) num_classes = len(labels) model = build_model(input_shape, num_classes) model.summary() # Train model n times test_class_acc_list = [] for i in range(5): print(f"\nTrain {i+1}:\n") model = build_model(input_shape, num_classes) batch_size = 16 epochs = 50 history = train_model(model, X_train, y_train_class, y_train_seg, X_val, y_val_class, y_val_seg, batch_size, epochs) # Evaluate model on test data test_class_acc = evaluate_model(model, X_test, y_test_class, y_test_seg) plot_performance(history) test_class_acc_list.append(test_class_acc) # Calculate average test classification accuracy average_test_class_acc = sum(test_class_acc_list) / len(test_class_acc_list) print("Test Classification Accuracy List:", test_class_acc_list) print("Average Test Classification Accuracy:", average_test_class_acc) " The above is the Python code with Keras to do multi-task learning with binary segmentation and classification using one mult-task learning model. Modify the code to change the model to resnet50 (from keras library), so no need to perform segmentation, only perform classification. Do not modify the other part of my code such as original functions.
153dd3c34128661d306b5eeae034f109
{ "intermediate": 0.3006076216697693, "beginner": 0.3237382769584656, "expert": 0.3756541907787323 }
42,741
Hi everyone, Im trying to create a UI Action that will redirect the user from the "Problem" to the Catalog, and when the user opens a "Incident" or a "Ritm" the "Parent" field should be the number of the problem is was created from, but Im not being abble to make this work ...
274bcbbc0e255f68a84e8b88addcc649
{ "intermediate": 0.5023295283317566, "beginner": 0.206486776471138, "expert": 0.2911836504936218 }
42,742
You are a Python expert who can provide clear, concise, high-quality code. " import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns import cv2 import random import tensorflow as tf import tkinter as tk from tkinter import filedialog from PIL import ImageTk, Image from ipywidgets import interact, interactive, fixed, interact_manual import ipywidgets as widgets from IPython.display import display, clear_output from tensorflow.keras.preprocessing import image from tensorflow.keras.optimizers import Adam, SGD, RMSprop, AdamW, Adadelta, Adagrad, Adamax, Adafactor, Nadam, Ftrl from tensorflow.keras.preprocessing.image import ImageDataGenerator from tqdm import tqdm import os from sklearn.utils import shuffle from sklearn.preprocessing import LabelEncoder from sklearn.model_selection import train_test_split from tensorflow.keras.models import Sequential, Model, load_model from tensorflow.keras.layers import ( GlobalAveragePooling2D, Dropout, Dense, Conv2D, MaxPooling2D, Flatten, Dropout, BatchNormalization, Activation, concatenate, Conv2DTranspose, Input, Reshape, UpSampling2D, ) from tensorflow.keras.applications import ( EfficientNetV2B0, EfficientNetV2B1, EfficientNetV2B2, EfficientNetV2B3, EfficientNetV2L, EfficientNetV2M, EfficientNetV2S, ) from tensorflow.keras.applications import Xception from tensorflow.keras.applications import VGG16, VGG19 from tensorflow.keras.applications import ResNet50, ResNet101, ResNet152, ResNetRS50, ResNetRS101 from tensorflow.keras.applications import InceptionResNetV2, ConvNeXtXLarge, ConvNeXtBase, DenseNet121, MobileNetV2, NASNetLarge, NASNetMobile from tensorflow.keras.utils import to_categorical from tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau, TensorBoard, ModelCheckpoint from sklearn.metrics import classification_report, confusion_matrix import ipywidgets as widgets import io from PIL import Image from IPython.display import display, clear_output from warnings import filterwarnings from google.colab import drive drive.mount("/content/gdrive") def load_data(data_folders): X_data = [] # Combined data y_class_labels = [] # Combined classification labels y_seg_labels = [] # Combined segmentation labels for folderPath in data_folders: for label in labels: label_folder_path = os.path.join(folderPath, label) for filename in tqdm(os.listdir(label_folder_path)): if filename.endswith(".jpg"): img = cv2.imread(os.path.join(label_folder_path, filename)) img = cv2.resize(img, (image_size, image_size)) X_data.append(img) y_class_labels.append(label) seg_filename = filename.split(".")[0] + ".png" seg_img = cv2.imread(os.path.join(label_folder_path, seg_filename), 0) seg_img = cv2.resize(seg_img, (image_size, image_size)) seg_img = np.where(seg_img > 0, 1, 0) # Convert segmentation mask to binary y_seg_labels.append(seg_img) X_data = np.array(X_data) y_class_labels = np.array(y_class_labels) y_seg_labels = np.array(y_seg_labels) X_data, y_class_labels, y_seg_labels = shuffle(X_data, y_class_labels, y_seg_labels, random_state=101) return X_data, y_class_labels, y_seg_labels def split_data(X_data, y_class_labels, y_seg_labels, class_data_counts): X_train = [] y_train_class = [] y_train_seg = [] X_val = [] y_val_class = [] y_val_seg = [] X_test = [] y_test_class = [] y_test_seg = [] for label, count in class_data_counts.items(): label_indices = np.where(y_class_labels == label)[0] class_X_data = X_data[label_indices] class_y_class_labels = y_class_labels[label_indices] class_y_seg_labels = y_seg_labels[label_indices] train_count = count[0] val_count = count[1] test_count = count[2] class_X_train = class_X_data[:train_count] class_y_train_class = class_y_class_labels[:train_count] class_y_train_seg = class_y_seg_labels[:train_count] class_X_val = class_X_data[train_count: train_count + val_count] class_y_val_class = class_y_class_labels[train_count: train_count + val_count] class_y_val_seg = class_y_seg_labels[train_count: train_count + val_count] class_X_test = class_X_data[train_count + val_count: train_count + val_count + test_count] class_y_test_class = class_y_class_labels[train_count + val_count: train_count + val_count + test_count] class_y_test_seg = class_y_seg_labels[train_count + val_count: train_count + val_count + test_count] X_train.extend(class_X_train) y_train_class.extend(class_y_train_class) y_train_seg.extend(class_y_train_seg) X_val.extend(class_X_val) y_val_class.extend(class_y_val_class) y_val_seg.extend(class_y_val_seg) X_test.extend(class_X_test) y_test_class.extend(class_y_test_class) y_test_seg.extend(class_y_test_seg) # Convert class labels to categorical label_encoder = LabelEncoder() y_train_class_encoded = label_encoder.fit_transform(y_train_class) y_train_class_categorical = to_categorical(y_train_class_encoded) y_val_class_encoded = label_encoder.transform(y_val_class) y_val_class_categorical = to_categorical(y_val_class_encoded) y_test_class_encoded = label_encoder.transform(y_test_class) y_test_class_categorical = to_categorical(y_test_class_encoded) return ( np.array(X_train), np.array(y_train_class_categorical), np.array(y_train_seg), np.array(X_val), np.array(y_val_class_categorical), np.array(y_val_seg), np.array(X_test), np.array(y_test_class_categorical), np.array(y_test_seg), ) def count_labels(y_class_categorical, label_encoder): # Convert one-hot encoded labels back to label encoded y_class_labels = np.argmax(y_class_categorical, axis=1) # Convert label encoded labels back to original class names y_class_names = label_encoder.inverse_transform(y_class_labels) unique, counts = np.unique(y_class_names, return_counts=True) return dict(zip(unique, counts)) def build_model(input_shape, num_classes): num_filter = 32 # 16/32 best, 8: best classification but no segment # Encoder (Done) inputs = Input(input_shape) conv1 = Conv2D(num_filter * 1, 3, activation="linear", padding="same", strides=1)(inputs) bn1 = BatchNormalization()(conv1) relu1 = Activation("relu")(bn1) conv2 = Conv2D(num_filter * 1, 3, activation="linear", padding="same", strides=1)(relu1) bn2 = BatchNormalization()(conv2) relu2 = Activation("relu")(bn2) down1 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu2) conv3 = Conv2D(num_filter * 2, 3, activation="linear", padding="same", strides=1)(down1) bn3 = BatchNormalization()(conv3) relu3 = Activation("relu")(bn3) conv4 = Conv2D(num_filter * 2, 3, activation="linear", padding="same", strides=1)(relu3) bn4 = BatchNormalization()(conv4) relu4 = Activation("relu")(bn4) down2 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu4) conv5 = Conv2D(num_filter * 4, 3, activation="linear", padding="same", strides=1)(down2) bn5 = BatchNormalization()(conv5) relu5 = Activation("relu")(bn5) conv6 = Conv2D(num_filter * 4, 3, activation="linear", padding="same", strides=1)(relu5) bn6 = BatchNormalization()(conv6) relu6 = Activation("relu")(bn6) down3 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu6) conv7 = Conv2D(num_filter * 8, 3, activation="linear", padding="same", strides=1)(down3) bn7 = BatchNormalization()(conv7) relu7 = Activation("relu")(bn7) conv8 = Conv2D(num_filter * 8, 3, activation="linear", padding="same", strides=1)(relu7) bn8 = BatchNormalization()(conv8) relu8 = Activation("relu")(bn8) # Middle down4 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu8) conv9 = Conv2D(num_filter * 16, 3, activation="linear", padding="same", strides=1)(down4) bn9 = BatchNormalization()(conv9) relu9 = Activation("relu")(bn9) conv10 = Conv2D(num_filter * 16, 3, activation="linear", padding="same", strides=1)(relu9) bn10 = BatchNormalization()(conv10) relu10 = Activation("relu")(bn10) up1 = UpSampling2D(size=(2, 2), interpolation="bilinear")(relu10) # Decoder (Done) concat1 = concatenate([up1, relu8], axis=-1) # , axis=3 conv11 = Conv2D(num_filter * 8, 3, activation="linear", padding="same", strides=1)(concat1) bn11 = BatchNormalization()(conv11) relu11 = Activation("relu")(bn11) conv12 = Conv2D(num_filter * 8, 3, activation="linear", padding="same", strides=1)(relu11) bn12 = BatchNormalization()(conv12) relu12 = Activation("relu")(bn12) up2 = UpSampling2D(size=(2, 2), interpolation="bilinear")(relu12) concat2 = concatenate([up2, relu6], axis=-1) # , axis=3 conv13 = Conv2D(num_filter * 4, 3, activation="linear", padding="same", strides=1)(concat2) bn13 = BatchNormalization()(conv13) relu13 = Activation("relu")(bn13) conv14 = Conv2D(num_filter * 4, 3, activation="linear", padding="same", strides=1)(relu13) bn14 = BatchNormalization()(conv14) relu14 = Activation("relu")(bn14) up3 = UpSampling2D(size=(2, 2), interpolation="bilinear")(relu14) concat3 = concatenate([up3, relu4], axis=-1) # , axis=3 conv15 = Conv2D(num_filter * 2, 3, activation="linear", padding="same", strides=1)(concat3) bn15 = BatchNormalization()(conv15) relu15 = Activation("relu")(bn15) conv16 = Conv2D(num_filter * 2, 3, activation="linear", padding="same", strides=1)(relu15) bn16 = BatchNormalization()(conv16) relu16 = Activation("relu")(bn16) up4 = UpSampling2D(size=(2, 2), interpolation="bilinear")(relu16) concat4 = concatenate([up4, relu2], axis=-1) # , axis=3 conv17 = Conv2D(num_filter * 1, 3, activation="linear", padding="same", strides=1)(concat4) bn17 = BatchNormalization()(conv17) relu17 = Activation("relu")(bn17) conv18 = Conv2D(num_filter * 1, 3, activation="linear", padding="same", strides=1)(relu17) bn18 = BatchNormalization()(conv18) relu18 = Activation("relu")(bn18) # Segmentation branch segmentation_output = Conv2D(1, 1, activation="sigmoid", name="segmentation_output")(relu18) # original # Classification branch (Not done) gap1 = GlobalAveragePooling2D()(relu8) gap2 = GlobalAveragePooling2D()(relu10) gap3 = GlobalAveragePooling2D()(relu12) conv20 = Conv2D(16, 3, activation="linear", padding="same", strides=1)(segmentation_output) bn20 = BatchNormalization()(conv20) relu20 = Activation("relu")(bn20) down5 = MaxPooling2D(pool_size=(4, 4), strides=4)(relu20) conv21 = Conv2D(32, 3, activation="linear", padding="same", strides=1)(down5) bn21 = BatchNormalization()(conv21) relu21 = Activation("relu")(bn21) down6 = MaxPooling2D(pool_size=(4, 4), strides=4)(relu21) conv22 = Conv2D(64, 3, activation="linear", padding="same", strides=1)(down6) bn22 = BatchNormalization()(conv22) relu22 = Activation("relu")(bn22) down7 = MaxPooling2D(pool_size=(4, 4), strides=4)(relu22) flatten1 = Flatten()(down7) concat5 = concatenate([gap1, gap2, gap3, flatten1], axis=-1) # FC layers fc1 = Dense(1024, activation="relu")(concat5) dropout1 = Dropout(0.5)(fc1) fc2 = Dense(1024, activation="relu")(dropout1) dropout2 = Dropout(0.5)(fc2) classification_output = Dense(num_classes, activation="softmax", name="classification_output")(dropout2) # Define the model model = Model(inputs=inputs, outputs=[classification_output, segmentation_output]) return model def segmentation_loss(y_true, y_pred): y_true = tf.cast(y_true, tf.float32) y_pred = tf.cast(y_pred, tf.float32) bce_loss = tf.keras.losses.binary_crossentropy(y_true, y_pred) smooth = 1e-5 intersection = tf.reduce_sum(y_true * y_pred) union = tf.reduce_sum(y_true) + tf.reduce_sum(y_pred) dice_loss = 1.0 - 2.0 * (intersection + smooth) / (union + smooth) segmentation_loss = bce_loss + 1 * dice_loss return segmentation_loss def train_model(model, X_train, y_train_class, y_train_seg, X_val, y_val_class, y_val_seg, batch_size, epochs): checkpoint = ModelCheckpoint( "multitask_best_weights.h5", monitor="val_classification_output_accuracy", save_best_only=True, mode="max", verbose=1,) reduce_lr = ReduceLROnPlateau( monitor="val_classification_output_accuracy", factor=0.3, patience=2, min_delta=0.001, mode="auto", verbose=1,) tensorboard = TensorBoard(log_dir="logs") model.compile( optimizer=Adam(lr=0.001), loss={"classification_output": "categorical_crossentropy", "segmentation_output": segmentation_loss}, metrics={"classification_output": "accuracy", "segmentation_output": "accuracy"}, loss_weights={"classification_output": 1, "segmentation_output": 1},) history = model.fit( X_train, {"classification_output": y_train_class, "segmentation_output": y_train_seg}, validation_data=(X_val, {"classification_output": y_val_class, "segmentation_output": y_val_seg}), epochs=epochs, verbose=1, batch_size=batch_size, callbacks=[checkpoint, reduce_lr, tensorboard],) return history def evaluate_model(model, X_test, y_test_class, y_test_seg): with tf.keras.utils.custom_object_scope({"segmentation_loss": segmentation_loss}): # Load the best model weights best_model = load_model("multitask_best_weights.h5") # Evaluate the model on test data test_loss, test_class_loss, test_seg_loss, test_class_acc, test_seg_acc = best_model.evaluate( X_test, {"classification_output": y_test_class, "segmentation_output": y_test_seg}) print("Test Classification Loss:", test_class_loss) print("Test Segmentation Loss:", test_seg_loss) print("Test Classification Accuracy:", test_class_acc) print("Test Segmentation Accuracy:", test_seg_acc) # Evaluate the model on validation data val_loss, val_class_loss, val_seg_loss, val_class_acc, val_seg_acc = best_model.evaluate( X_val, {'classification_output': y_val_class, 'segmentation_output': y_val_seg}) print("Validation Classification Loss:", val_class_loss) print("Validation Segmentation Loss:", val_seg_loss) print("Validation Classification Accuracy:", val_class_acc) print("Validation Segmentation Accuracy:", val_seg_acc) # Evaluate the model on training data train_loss, train_class_loss, train_seg_loss, train_class_acc, train_seg_acc = best_model.evaluate(X_train, {'classification_output': y_train_class, 'segmentation_output': y_train_seg}) print("Train Classification Loss:", train_class_loss) print("Train Segmentation Loss:", train_seg_loss) print("Train Classification Accuracy:", train_class_acc) print("Train Segmentation Accuracy:", train_seg_acc) # Return test classification accuracy return test_class_acc def plot_performance(history): # Plot classification accuracy classification_train_accuracy = history.history["classification_output_accuracy"] classification_val_accuracy = history.history["val_classification_output_accuracy"] plt.figure(figsize=(7, 3)) plt.plot(classification_train_accuracy, label="Training Accuracy") plt.plot(classification_val_accuracy, label="Validation Accuracy") plt.title("Classification Accuracy") plt.xlabel("Epochs") plt.ylabel("Accuracy") plt.legend() plt.show() # Plot classification loss classification_train_loss = history.history["classification_output_loss"] classification_val_loss = history.history["val_classification_output_loss"] plt.figure(figsize=(7, 3)) plt.plot(classification_train_loss, "b", label="Training Loss") plt.plot(classification_val_loss, "r", label="Validation Loss") plt.title("Classification Loss") plt.xlabel("Epochs") plt.ylabel("Loss") plt.legend() plt.show() # Plot segmentation accuracy segmentation_train_accuracy = history.history["segmentation_output_accuracy"] segmentation_val_accuracy = history.history["val_segmentation_output_accuracy"] plt.figure(figsize=(7, 3)) plt.plot(segmentation_train_accuracy, label="Training Accuracy") plt.plot(segmentation_val_accuracy, label="Validation Accuracy") plt.title("Segmentation Accuracy") plt.xlabel("Epochs") plt.ylabel("Accuracy") plt.legend() plt.show() # Plot segmentation loss segmentation_train_loss = history.history["segmentation_output_loss"] segmentation_val_loss = history.history["val_segmentation_output_loss"] plt.figure(figsize=(7, 3)) plt.plot(segmentation_train_loss, "b", label="Training Loss") plt.plot(segmentation_val_loss, "r", label="Validation Loss") plt.title("Segmentation Loss") plt.xlabel("Epochs") plt.ylabel("Loss") plt.legend() plt.show() # Set image size image_size = 224 # Define labels labels = ["bridge", "excess", "good"] # Set data folders data_folders = [ "/content/gdrive/MyDrive/Deep learning/FYP_2/4 Dataset Ratio 60 20 20/jit012/jit0/f_dip/train", "/content/gdrive/MyDrive/Deep learning/FYP_2/4 Dataset Ratio 60 20 20/jit012/jit0/f_dip/val", "/content/gdrive/MyDrive/Deep learning/FYP_2/4 Dataset Ratio 60 20 20/jit012/jit0/f_dip/test",] # Load data X_data, y_class_labels, y_seg_labels = load_data(data_folders) # Define train:val:test ratio for each class (ratio x4 = exact) class_data_counts = { "bridge": [40, 80, 80], "excess": [40, 80, 80], "good": [40, 80, 80], } # Split data X_train, y_train_class, y_train_seg, X_val, y_val_class, y_val_seg, X_test, y_test_class, y_test_seg = split_data( X_data, y_class_labels, y_seg_labels, class_data_counts) ''' print("Number of train images:", len(X_train)) print("Number of train binary masks:", len(y_train_seg)) print("Number of validation images:", len(X_val)) print("Number of validation binary masks:", len(y_val_seg)) print("Number of test images:", len(X_test)) print("Number of test binary masks:", len(y_test_seg)) ''' # Initialize the label encoder label_encoder = LabelEncoder() label_encoder.fit(y_class_labels) # Count the number of images of each class in the train, validation, and test sets train_counts = count_labels(y_train_class, label_encoder) val_counts = count_labels(y_val_class, label_encoder) test_counts = count_labels(y_test_class, label_encoder) print("Train counts: ", train_counts," Total in train set:", sum(train_counts.values())) print("Validation counts:", val_counts, " Total in validation set:", sum(val_counts.values())) print("Test counts: ", test_counts," Total in test set:", sum(test_counts.values())) # Build model input_shape = (image_size, image_size, 3) num_classes = len(labels) model = build_model(input_shape, num_classes) model.summary() # Train model n times test_class_acc_list = [] for i in range(5): print(f"\nTrain {i+1}:\n") model = build_model(input_shape, num_classes) batch_size = 16 epochs = 50 history = train_model(model, X_train, y_train_class, y_train_seg, X_val, y_val_class, y_val_seg, batch_size, epochs) # Evaluate model on test data test_class_acc = evaluate_model(model, X_test, y_test_class, y_test_seg) plot_performance(history) test_class_acc_list.append(test_class_acc) # Calculate average test classification accuracy average_test_class_acc = sum(test_class_acc_list) / len(test_class_acc_list) print("Test Classification Accuracy List:", test_class_acc_list) print("Average Test Classification Accuracy:", average_test_class_acc) " The above is the Python code with Keras to do multi-task learning with binary segmentation and classification using one mult-task learning model. I train the model 5 times and take the average accuracy. Modify the code to change the model to resnet50 (from keras library), so no need to perform segmentation, only perform classification. Do not modify the other part of my code. Show full code.
49121602341054faf144026d1c730ba0
{ "intermediate": 0.3006076216697693, "beginner": 0.3237382769584656, "expert": 0.3756541907787323 }
42,743
You are a Python expert who can provide clear, concise, high-quality code. " import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns import cv2 import random import tensorflow as tf import tkinter as tk from tkinter import filedialog from PIL import ImageTk, Image from ipywidgets import interact, interactive, fixed, interact_manual import ipywidgets as widgets from IPython.display import display, clear_output from tensorflow.keras.preprocessing import image from tensorflow.keras.optimizers import Adam, SGD, RMSprop, AdamW, Adadelta, Adagrad, Adamax, Adafactor, Nadam, Ftrl from tensorflow.keras.preprocessing.image import ImageDataGenerator from tqdm import tqdm import os from sklearn.utils import shuffle from sklearn.preprocessing import LabelEncoder from sklearn.model_selection import train_test_split from tensorflow.keras.models import Sequential, Model, load_model from tensorflow.keras.layers import ( GlobalAveragePooling2D, Dropout, Dense, Conv2D, MaxPooling2D, Flatten, Dropout, BatchNormalization, Activation, concatenate, Conv2DTranspose, Input, Reshape, UpSampling2D, ) from tensorflow.keras.applications import ( EfficientNetV2B0, EfficientNetV2B1, EfficientNetV2B2, EfficientNetV2B3, EfficientNetV2L, EfficientNetV2M, EfficientNetV2S, ) from tensorflow.keras.applications import Xception from tensorflow.keras.applications import VGG16, VGG19 from tensorflow.keras.applications import ResNet50, ResNet101, ResNet152, ResNetRS50, ResNetRS101 from tensorflow.keras.applications import InceptionResNetV2, ConvNeXtXLarge, ConvNeXtBase, DenseNet121, MobileNetV2, NASNetLarge, NASNetMobile from tensorflow.keras.utils import to_categorical from tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau, TensorBoard, ModelCheckpoint from sklearn.metrics import classification_report, confusion_matrix import ipywidgets as widgets import io from PIL import Image from IPython.display import display, clear_output from warnings import filterwarnings from google.colab import drive drive.mount("/content/gdrive") def load_data(data_folders): X_data = [] # Combined data y_class_labels = [] # Combined classification labels y_seg_labels = [] # Combined segmentation labels for folderPath in data_folders: for label in labels: label_folder_path = os.path.join(folderPath, label) for filename in tqdm(os.listdir(label_folder_path)): if filename.endswith(".jpg"): img = cv2.imread(os.path.join(label_folder_path, filename)) img = cv2.resize(img, (image_size, image_size)) X_data.append(img) y_class_labels.append(label) seg_filename = filename.split(".")[0] + ".png" seg_img = cv2.imread(os.path.join(label_folder_path, seg_filename), 0) seg_img = cv2.resize(seg_img, (image_size, image_size)) seg_img = np.where(seg_img > 0, 1, 0) # Convert segmentation mask to binary y_seg_labels.append(seg_img) X_data = np.array(X_data) y_class_labels = np.array(y_class_labels) y_seg_labels = np.array(y_seg_labels) X_data, y_class_labels, y_seg_labels = shuffle(X_data, y_class_labels, y_seg_labels, random_state=101) return X_data, y_class_labels, y_seg_labels def split_data(X_data, y_class_labels, y_seg_labels, class_data_counts): X_train = [] y_train_class = [] y_train_seg = [] X_val = [] y_val_class = [] y_val_seg = [] X_test = [] y_test_class = [] y_test_seg = [] for label, count in class_data_counts.items(): label_indices = np.where(y_class_labels == label)[0] class_X_data = X_data[label_indices] class_y_class_labels = y_class_labels[label_indices] class_y_seg_labels = y_seg_labels[label_indices] train_count = count[0] val_count = count[1] test_count = count[2] class_X_train = class_X_data[:train_count] class_y_train_class = class_y_class_labels[:train_count] class_y_train_seg = class_y_seg_labels[:train_count] class_X_val = class_X_data[train_count: train_count + val_count] class_y_val_class = class_y_class_labels[train_count: train_count + val_count] class_y_val_seg = class_y_seg_labels[train_count: train_count + val_count] class_X_test = class_X_data[train_count + val_count: train_count + val_count + test_count] class_y_test_class = class_y_class_labels[train_count + val_count: train_count + val_count + test_count] class_y_test_seg = class_y_seg_labels[train_count + val_count: train_count + val_count + test_count] X_train.extend(class_X_train) y_train_class.extend(class_y_train_class) y_train_seg.extend(class_y_train_seg) X_val.extend(class_X_val) y_val_class.extend(class_y_val_class) y_val_seg.extend(class_y_val_seg) X_test.extend(class_X_test) y_test_class.extend(class_y_test_class) y_test_seg.extend(class_y_test_seg) # Convert class labels to categorical label_encoder = LabelEncoder() y_train_class_encoded = label_encoder.fit_transform(y_train_class) y_train_class_categorical = to_categorical(y_train_class_encoded) y_val_class_encoded = label_encoder.transform(y_val_class) y_val_class_categorical = to_categorical(y_val_class_encoded) y_test_class_encoded = label_encoder.transform(y_test_class) y_test_class_categorical = to_categorical(y_test_class_encoded) return ( np.array(X_train), np.array(y_train_class_categorical), np.array(y_train_seg), np.array(X_val), np.array(y_val_class_categorical), np.array(y_val_seg), np.array(X_test), np.array(y_test_class_categorical), np.array(y_test_seg), ) def count_labels(y_class_categorical, label_encoder): # Convert one-hot encoded labels back to label encoded y_class_labels = np.argmax(y_class_categorical, axis=1) # Convert label encoded labels back to original class names y_class_names = label_encoder.inverse_transform(y_class_labels) unique, counts = np.unique(y_class_names, return_counts=True) return dict(zip(unique, counts)) def build_model(input_shape, num_classes): num_filter = 32 # 16/32 best, 8: best classification but no segment # Encoder (Done) inputs = Input(input_shape) conv1 = Conv2D(num_filter * 1, 3, activation="linear", padding="same", strides=1)(inputs) bn1 = BatchNormalization()(conv1) relu1 = Activation("relu")(bn1) conv2 = Conv2D(num_filter * 1, 3, activation="linear", padding="same", strides=1)(relu1) bn2 = BatchNormalization()(conv2) relu2 = Activation("relu")(bn2) down1 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu2) conv3 = Conv2D(num_filter * 2, 3, activation="linear", padding="same", strides=1)(down1) bn3 = BatchNormalization()(conv3) relu3 = Activation("relu")(bn3) conv4 = Conv2D(num_filter * 2, 3, activation="linear", padding="same", strides=1)(relu3) bn4 = BatchNormalization()(conv4) relu4 = Activation("relu")(bn4) down2 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu4) conv5 = Conv2D(num_filter * 4, 3, activation="linear", padding="same", strides=1)(down2) bn5 = BatchNormalization()(conv5) relu5 = Activation("relu")(bn5) conv6 = Conv2D(num_filter * 4, 3, activation="linear", padding="same", strides=1)(relu5) bn6 = BatchNormalization()(conv6) relu6 = Activation("relu")(bn6) down3 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu6) conv7 = Conv2D(num_filter * 8, 3, activation="linear", padding="same", strides=1)(down3) bn7 = BatchNormalization()(conv7) relu7 = Activation("relu")(bn7) conv8 = Conv2D(num_filter * 8, 3, activation="linear", padding="same", strides=1)(relu7) bn8 = BatchNormalization()(conv8) relu8 = Activation("relu")(bn8) # Middle down4 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu8) conv9 = Conv2D(num_filter * 16, 3, activation="linear", padding="same", strides=1)(down4) bn9 = BatchNormalization()(conv9) relu9 = Activation("relu")(bn9) conv10 = Conv2D(num_filter * 16, 3, activation="linear", padding="same", strides=1)(relu9) bn10 = BatchNormalization()(conv10) relu10 = Activation("relu")(bn10) up1 = UpSampling2D(size=(2, 2), interpolation="bilinear")(relu10) # Decoder (Done) concat1 = concatenate([up1, relu8], axis=-1) # , axis=3 conv11 = Conv2D(num_filter * 8, 3, activation="linear", padding="same", strides=1)(concat1) bn11 = BatchNormalization()(conv11) relu11 = Activation("relu")(bn11) conv12 = Conv2D(num_filter * 8, 3, activation="linear", padding="same", strides=1)(relu11) bn12 = BatchNormalization()(conv12) relu12 = Activation("relu")(bn12) up2 = UpSampling2D(size=(2, 2), interpolation="bilinear")(relu12) concat2 = concatenate([up2, relu6], axis=-1) # , axis=3 conv13 = Conv2D(num_filter * 4, 3, activation="linear", padding="same", strides=1)(concat2) bn13 = BatchNormalization()(conv13) relu13 = Activation("relu")(bn13) conv14 = Conv2D(num_filter * 4, 3, activation="linear", padding="same", strides=1)(relu13) bn14 = BatchNormalization()(conv14) relu14 = Activation("relu")(bn14) up3 = UpSampling2D(size=(2, 2), interpolation="bilinear")(relu14) concat3 = concatenate([up3, relu4], axis=-1) # , axis=3 conv15 = Conv2D(num_filter * 2, 3, activation="linear", padding="same", strides=1)(concat3) bn15 = BatchNormalization()(conv15) relu15 = Activation("relu")(bn15) conv16 = Conv2D(num_filter * 2, 3, activation="linear", padding="same", strides=1)(relu15) bn16 = BatchNormalization()(conv16) relu16 = Activation("relu")(bn16) up4 = UpSampling2D(size=(2, 2), interpolation="bilinear")(relu16) concat4 = concatenate([up4, relu2], axis=-1) # , axis=3 conv17 = Conv2D(num_filter * 1, 3, activation="linear", padding="same", strides=1)(concat4) bn17 = BatchNormalization()(conv17) relu17 = Activation("relu")(bn17) conv18 = Conv2D(num_filter * 1, 3, activation="linear", padding="same", strides=1)(relu17) bn18 = BatchNormalization()(conv18) relu18 = Activation("relu")(bn18) # Segmentation branch segmentation_output = Conv2D(1, 1, activation="sigmoid", name="segmentation_output")(relu18) # original # Classification branch (Not done) gap1 = GlobalAveragePooling2D()(relu8) gap2 = GlobalAveragePooling2D()(relu10) gap3 = GlobalAveragePooling2D()(relu12) conv20 = Conv2D(16, 3, activation="linear", padding="same", strides=1)(segmentation_output) bn20 = BatchNormalization()(conv20) relu20 = Activation("relu")(bn20) down5 = MaxPooling2D(pool_size=(4, 4), strides=4)(relu20) conv21 = Conv2D(32, 3, activation="linear", padding="same", strides=1)(down5) bn21 = BatchNormalization()(conv21) relu21 = Activation("relu")(bn21) down6 = MaxPooling2D(pool_size=(4, 4), strides=4)(relu21) conv22 = Conv2D(64, 3, activation="linear", padding="same", strides=1)(down6) bn22 = BatchNormalization()(conv22) relu22 = Activation("relu")(bn22) down7 = MaxPooling2D(pool_size=(4, 4), strides=4)(relu22) flatten1 = Flatten()(down7) concat5 = concatenate([gap1, gap2, gap3, flatten1], axis=-1) # FC layers fc1 = Dense(1024, activation="relu")(concat5) dropout1 = Dropout(0.5)(fc1) fc2 = Dense(1024, activation="relu")(dropout1) dropout2 = Dropout(0.5)(fc2) classification_output = Dense(num_classes, activation="softmax", name="classification_output")(dropout2) # Define the model model = Model(inputs=inputs, outputs=[classification_output, segmentation_output]) return model def segmentation_loss(y_true, y_pred): y_true = tf.cast(y_true, tf.float32) y_pred = tf.cast(y_pred, tf.float32) bce_loss = tf.keras.losses.binary_crossentropy(y_true, y_pred) smooth = 1e-5 intersection = tf.reduce_sum(y_true * y_pred) union = tf.reduce_sum(y_true) + tf.reduce_sum(y_pred) dice_loss = 1.0 - 2.0 * (intersection + smooth) / (union + smooth) segmentation_loss = bce_loss + 1 * dice_loss return segmentation_loss def train_model(model, X_train, y_train_class, y_train_seg, X_val, y_val_class, y_val_seg, batch_size, epochs): checkpoint = ModelCheckpoint( "multitask_best_weights.h5", monitor="val_classification_output_accuracy", save_best_only=True, mode="max", verbose=1,) reduce_lr = ReduceLROnPlateau( monitor="val_classification_output_accuracy", factor=0.3, patience=2, min_delta=0.001, mode="auto", verbose=1,) tensorboard = TensorBoard(log_dir="logs") model.compile( optimizer=Adam(lr=0.001), loss={"classification_output": "categorical_crossentropy", "segmentation_output": segmentation_loss}, metrics={"classification_output": "accuracy", "segmentation_output": "accuracy"}, loss_weights={"classification_output": 1, "segmentation_output": 1},) history = model.fit( X_train, {"classification_output": y_train_class, "segmentation_output": y_train_seg}, validation_data=(X_val, {"classification_output": y_val_class, "segmentation_output": y_val_seg}), epochs=epochs, verbose=1, batch_size=batch_size, callbacks=[checkpoint, reduce_lr, tensorboard],) return history def evaluate_model(model, X_test, y_test_class, y_test_seg): with tf.keras.utils.custom_object_scope({"segmentation_loss": segmentation_loss}): # Load the best model weights best_model = load_model("multitask_best_weights.h5") # Evaluate the model on test data test_loss, test_class_loss, test_seg_loss, test_class_acc, test_seg_acc = best_model.evaluate( X_test, {"classification_output": y_test_class, "segmentation_output": y_test_seg}) print("Test Classification Loss:", test_class_loss) print("Test Segmentation Loss:", test_seg_loss) print("Test Classification Accuracy:", test_class_acc) print("Test Segmentation Accuracy:", test_seg_acc) # Evaluate the model on validation data val_loss, val_class_loss, val_seg_loss, val_class_acc, val_seg_acc = best_model.evaluate( X_val, {'classification_output': y_val_class, 'segmentation_output': y_val_seg}) print("Validation Classification Loss:", val_class_loss) print("Validation Segmentation Loss:", val_seg_loss) print("Validation Classification Accuracy:", val_class_acc) print("Validation Segmentation Accuracy:", val_seg_acc) # Evaluate the model on training data train_loss, train_class_loss, train_seg_loss, train_class_acc, train_seg_acc = best_model.evaluate(X_train, {'classification_output': y_train_class, 'segmentation_output': y_train_seg}) print("Train Classification Loss:", train_class_loss) print("Train Segmentation Loss:", train_seg_loss) print("Train Classification Accuracy:", train_class_acc) print("Train Segmentation Accuracy:", train_seg_acc) # Return test classification accuracy return test_class_acc def plot_performance(history): # Plot classification accuracy classification_train_accuracy = history.history["classification_output_accuracy"] classification_val_accuracy = history.history["val_classification_output_accuracy"] plt.figure(figsize=(7, 3)) plt.plot(classification_train_accuracy, label="Training Accuracy") plt.plot(classification_val_accuracy, label="Validation Accuracy") plt.title("Classification Accuracy") plt.xlabel("Epochs") plt.ylabel("Accuracy") plt.legend() plt.show() # Plot classification loss classification_train_loss = history.history["classification_output_loss"] classification_val_loss = history.history["val_classification_output_loss"] plt.figure(figsize=(7, 3)) plt.plot(classification_train_loss, "b", label="Training Loss") plt.plot(classification_val_loss, "r", label="Validation Loss") plt.title("Classification Loss") plt.xlabel("Epochs") plt.ylabel("Loss") plt.legend() plt.show() # Plot segmentation accuracy segmentation_train_accuracy = history.history["segmentation_output_accuracy"] segmentation_val_accuracy = history.history["val_segmentation_output_accuracy"] plt.figure(figsize=(7, 3)) plt.plot(segmentation_train_accuracy, label="Training Accuracy") plt.plot(segmentation_val_accuracy, label="Validation Accuracy") plt.title("Segmentation Accuracy") plt.xlabel("Epochs") plt.ylabel("Accuracy") plt.legend() plt.show() # Plot segmentation loss segmentation_train_loss = history.history["segmentation_output_loss"] segmentation_val_loss = history.history["val_segmentation_output_loss"] plt.figure(figsize=(7, 3)) plt.plot(segmentation_train_loss, "b", label="Training Loss") plt.plot(segmentation_val_loss, "r", label="Validation Loss") plt.title("Segmentation Loss") plt.xlabel("Epochs") plt.ylabel("Loss") plt.legend() plt.show() # Set image size image_size = 224 # Define labels labels = ["bridge", "excess", "good"] # Set data folders data_folders = [ "/content/gdrive/MyDrive/Deep learning/FYP_2/4 Dataset Ratio 60 20 20/jit012/jit0/f_dip/train", "/content/gdrive/MyDrive/Deep learning/FYP_2/4 Dataset Ratio 60 20 20/jit012/jit0/f_dip/val", "/content/gdrive/MyDrive/Deep learning/FYP_2/4 Dataset Ratio 60 20 20/jit012/jit0/f_dip/test",] # Load data X_data, y_class_labels, y_seg_labels = load_data(data_folders) # Define train:val:test ratio for each class (ratio x4 = exact) class_data_counts = { "bridge": [40, 80, 80], "excess": [40, 80, 80], "good": [40, 80, 80], } # Split data X_train, y_train_class, y_train_seg, X_val, y_val_class, y_val_seg, X_test, y_test_class, y_test_seg = split_data( X_data, y_class_labels, y_seg_labels, class_data_counts) ''' print("Number of train images:", len(X_train)) print("Number of train binary masks:", len(y_train_seg)) print("Number of validation images:", len(X_val)) print("Number of validation binary masks:", len(y_val_seg)) print("Number of test images:", len(X_test)) print("Number of test binary masks:", len(y_test_seg)) ''' # Initialize the label encoder label_encoder = LabelEncoder() label_encoder.fit(y_class_labels) # Count the number of images of each class in the train, validation, and test sets train_counts = count_labels(y_train_class, label_encoder) val_counts = count_labels(y_val_class, label_encoder) test_counts = count_labels(y_test_class, label_encoder) print("Train counts: ", train_counts," Total in train set:", sum(train_counts.values())) print("Validation counts:", val_counts, " Total in validation set:", sum(val_counts.values())) print("Test counts: ", test_counts," Total in test set:", sum(test_counts.values())) # Build model input_shape = (image_size, image_size, 3) num_classes = len(labels) model = build_model(input_shape, num_classes) model.summary() # Train model n times test_class_acc_list = [] for i in range(5): print(f"\nTrain {i+1}:\n") model = build_model(input_shape, num_classes) batch_size = 16 epochs = 50 history = train_model(model, X_train, y_train_class, y_train_seg, X_val, y_val_class, y_val_seg, batch_size, epochs) # Evaluate model on test data test_class_acc = evaluate_model(model, X_test, y_test_class, y_test_seg) plot_performance(history) test_class_acc_list.append(test_class_acc) # Calculate average test classification accuracy average_test_class_acc = sum(test_class_acc_list) / len(test_class_acc_list) print("Test Classification Accuracy List:", test_class_acc_list) print("Average Test Classification Accuracy:", average_test_class_acc) " The above is the Python code with Keras to do multi-task learning with binary segmentation and classification using one mult-task learning model. Modify the code to change the model to resnet50 (from keras library), so no need to perform segmentation, only perform classification. Do not modify the other part of my code. Show full code.
c8342bb619cb64baa938efe314a5c759
{ "intermediate": 0.3006076216697693, "beginner": 0.3237382769584656, "expert": 0.3756541907787323 }
42,744
Hello
d935e5b374ac2b5c95b06b289c2a1942
{ "intermediate": 0.3123404085636139, "beginner": 0.2729349136352539, "expert": 0.4147246778011322 }
42,745
make a list of pun with the word "solana" and animal names
9678e6ff53df9f7e5f60893ce1ee3aa8
{ "intermediate": 0.35919418931007385, "beginner": 0.33154961466789246, "expert": 0.3092562258243561 }
42,746
You are a Python expert who can provide clear, concise, high-quality code. " import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns import cv2 import random import tensorflow as tf import tkinter as tk from tkinter import filedialog from PIL import ImageTk, Image from ipywidgets import interact, interactive, fixed, interact_manual import ipywidgets as widgets from IPython.display import display, clear_output from tensorflow.keras.preprocessing import image from tensorflow.keras.optimizers import Adam, SGD, RMSprop, AdamW, Adadelta, Adagrad, Adamax, Adafactor, Nadam, Ftrl from tensorflow.keras.preprocessing.image import ImageDataGenerator from tqdm import tqdm import os from sklearn.utils import shuffle from sklearn.preprocessing import LabelEncoder from sklearn.model_selection import train_test_split from tensorflow.keras.models import Sequential, Model, load_model from tensorflow.keras.layers import ( GlobalAveragePooling2D, Dropout, Dense, Conv2D, MaxPooling2D, Flatten, Dropout, BatchNormalization, Activation, concatenate, Conv2DTranspose, Input, Reshape, UpSampling2D, ) from tensorflow.keras.applications import ( EfficientNetV2B0, EfficientNetV2B1, EfficientNetV2B2, EfficientNetV2B3, EfficientNetV2L, EfficientNetV2M, EfficientNetV2S, ) from tensorflow.keras.applications import Xception from tensorflow.keras.applications import VGG16, VGG19 from tensorflow.keras.applications import ResNet50, ResNet101, ResNet152, ResNetRS50, ResNetRS101 from tensorflow.keras.applications import InceptionResNetV2, ConvNeXtXLarge, ConvNeXtBase, DenseNet121, MobileNetV2, NASNetLarge, NASNetMobile from tensorflow.keras.utils import to_categorical from tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau, TensorBoard, ModelCheckpoint from sklearn.metrics import classification_report, confusion_matrix import ipywidgets as widgets import io from PIL import Image from IPython.display import display, clear_output from warnings import filterwarnings from google.colab import drive drive.mount("/content/gdrive") def load_data(data_folders): X_data = [] # Combined data y_class_labels = [] # Combined classification labels y_seg_labels = [] # Combined segmentation labels for folderPath in data_folders: for label in labels: label_folder_path = os.path.join(folderPath, label) for filename in tqdm(os.listdir(label_folder_path)): if filename.endswith(".jpg"): img = cv2.imread(os.path.join(label_folder_path, filename)) img = cv2.resize(img, (image_size, image_size)) X_data.append(img) y_class_labels.append(label) seg_filename = filename.split(".")[0] + ".png" seg_img = cv2.imread(os.path.join(label_folder_path, seg_filename), 0) seg_img = cv2.resize(seg_img, (image_size, image_size)) seg_img = np.where(seg_img > 0, 1, 0) # Convert segmentation mask to binary y_seg_labels.append(seg_img) X_data = np.array(X_data) y_class_labels = np.array(y_class_labels) y_seg_labels = np.array(y_seg_labels) X_data, y_class_labels, y_seg_labels = shuffle(X_data, y_class_labels, y_seg_labels, random_state=101) return X_data, y_class_labels, y_seg_labels def split_data(X_data, y_class_labels, y_seg_labels, class_data_counts): X_train = [] y_train_class = [] y_train_seg = [] X_val = [] y_val_class = [] y_val_seg = [] X_test = [] y_test_class = [] y_test_seg = [] for label, count in class_data_counts.items(): label_indices = np.where(y_class_labels == label)[0] class_X_data = X_data[label_indices] class_y_class_labels = y_class_labels[label_indices] class_y_seg_labels = y_seg_labels[label_indices] train_count = count[0] val_count = count[1] test_count = count[2] class_X_train = class_X_data[:train_count] class_y_train_class = class_y_class_labels[:train_count] class_y_train_seg = class_y_seg_labels[:train_count] class_X_val = class_X_data[train_count: train_count + val_count] class_y_val_class = class_y_class_labels[train_count: train_count + val_count] class_y_val_seg = class_y_seg_labels[train_count: train_count + val_count] class_X_test = class_X_data[train_count + val_count: train_count + val_count + test_count] class_y_test_class = class_y_class_labels[train_count + val_count: train_count + val_count + test_count] class_y_test_seg = class_y_seg_labels[train_count + val_count: train_count + val_count + test_count] X_train.extend(class_X_train) y_train_class.extend(class_y_train_class) y_train_seg.extend(class_y_train_seg) X_val.extend(class_X_val) y_val_class.extend(class_y_val_class) y_val_seg.extend(class_y_val_seg) X_test.extend(class_X_test) y_test_class.extend(class_y_test_class) y_test_seg.extend(class_y_test_seg) # Convert class labels to categorical label_encoder = LabelEncoder() y_train_class_encoded = label_encoder.fit_transform(y_train_class) y_train_class_categorical = to_categorical(y_train_class_encoded) y_val_class_encoded = label_encoder.transform(y_val_class) y_val_class_categorical = to_categorical(y_val_class_encoded) y_test_class_encoded = label_encoder.transform(y_test_class) y_test_class_categorical = to_categorical(y_test_class_encoded) return ( np.array(X_train), np.array(y_train_class_categorical), np.array(y_train_seg), np.array(X_val), np.array(y_val_class_categorical), np.array(y_val_seg), np.array(X_test), np.array(y_test_class_categorical), np.array(y_test_seg), ) def count_labels(y_class_categorical, label_encoder): # Convert one-hot encoded labels back to label encoded y_class_labels = np.argmax(y_class_categorical, axis=1) # Convert label encoded labels back to original class names y_class_names = label_encoder.inverse_transform(y_class_labels) unique, counts = np.unique(y_class_names, return_counts=True) return dict(zip(unique, counts)) def build_model(input_shape, num_classes): num_filter = 32 # 16/32 best, 8: best classification but no segment # Encoder (Done) inputs = Input(input_shape) conv1 = Conv2D(num_filter * 1, 3, activation="linear", padding="same", strides=1)(inputs) bn1 = BatchNormalization()(conv1) relu1 = Activation("relu")(bn1) conv2 = Conv2D(num_filter * 1, 3, activation="linear", padding="same", strides=1)(relu1) bn2 = BatchNormalization()(conv2) relu2 = Activation("relu")(bn2) down1 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu2) conv3 = Conv2D(num_filter * 2, 3, activation="linear", padding="same", strides=1)(down1) bn3 = BatchNormalization()(conv3) relu3 = Activation("relu")(bn3) conv4 = Conv2D(num_filter * 2, 3, activation="linear", padding="same", strides=1)(relu3) bn4 = BatchNormalization()(conv4) relu4 = Activation("relu")(bn4) down2 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu4) conv5 = Conv2D(num_filter * 4, 3, activation="linear", padding="same", strides=1)(down2) bn5 = BatchNormalization()(conv5) relu5 = Activation("relu")(bn5) conv6 = Conv2D(num_filter * 4, 3, activation="linear", padding="same", strides=1)(relu5) bn6 = BatchNormalization()(conv6) relu6 = Activation("relu")(bn6) down3 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu6) conv7 = Conv2D(num_filter * 8, 3, activation="linear", padding="same", strides=1)(down3) bn7 = BatchNormalization()(conv7) relu7 = Activation("relu")(bn7) conv8 = Conv2D(num_filter * 8, 3, activation="linear", padding="same", strides=1)(relu7) bn8 = BatchNormalization()(conv8) relu8 = Activation("relu")(bn8) # Middle down4 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu8) conv9 = Conv2D(num_filter * 16, 3, activation="linear", padding="same", strides=1)(down4) bn9 = BatchNormalization()(conv9) relu9 = Activation("relu")(bn9) conv10 = Conv2D(num_filter * 16, 3, activation="linear", padding="same", strides=1)(relu9) bn10 = BatchNormalization()(conv10) relu10 = Activation("relu")(bn10) up1 = UpSampling2D(size=(2, 2), interpolation="bilinear")(relu10) # Decoder (Done) concat1 = concatenate([up1, relu8], axis=-1) # , axis=3 conv11 = Conv2D(num_filter * 8, 3, activation="linear", padding="same", strides=1)(concat1) bn11 = BatchNormalization()(conv11) relu11 = Activation("relu")(bn11) conv12 = Conv2D(num_filter * 8, 3, activation="linear", padding="same", strides=1)(relu11) bn12 = BatchNormalization()(conv12) relu12 = Activation("relu")(bn12) up2 = UpSampling2D(size=(2, 2), interpolation="bilinear")(relu12) concat2 = concatenate([up2, relu6], axis=-1) # , axis=3 conv13 = Conv2D(num_filter * 4, 3, activation="linear", padding="same", strides=1)(concat2) bn13 = BatchNormalization()(conv13) relu13 = Activation("relu")(bn13) conv14 = Conv2D(num_filter * 4, 3, activation="linear", padding="same", strides=1)(relu13) bn14 = BatchNormalization()(conv14) relu14 = Activation("relu")(bn14) up3 = UpSampling2D(size=(2, 2), interpolation="bilinear")(relu14) concat3 = concatenate([up3, relu4], axis=-1) # , axis=3 conv15 = Conv2D(num_filter * 2, 3, activation="linear", padding="same", strides=1)(concat3) bn15 = BatchNormalization()(conv15) relu15 = Activation("relu")(bn15) conv16 = Conv2D(num_filter * 2, 3, activation="linear", padding="same", strides=1)(relu15) bn16 = BatchNormalization()(conv16) relu16 = Activation("relu")(bn16) up4 = UpSampling2D(size=(2, 2), interpolation="bilinear")(relu16) concat4 = concatenate([up4, relu2], axis=-1) # , axis=3 conv17 = Conv2D(num_filter * 1, 3, activation="linear", padding="same", strides=1)(concat4) bn17 = BatchNormalization()(conv17) relu17 = Activation("relu")(bn17) conv18 = Conv2D(num_filter * 1, 3, activation="linear", padding="same", strides=1)(relu17) bn18 = BatchNormalization()(conv18) relu18 = Activation("relu")(bn18) # Segmentation branch segmentation_output = Conv2D(1, 1, activation="sigmoid", name="segmentation_output")(relu18) # original # Classification branch (Not done) gap1 = GlobalAveragePooling2D()(relu8) gap2 = GlobalAveragePooling2D()(relu10) gap3 = GlobalAveragePooling2D()(relu12) conv20 = Conv2D(16, 3, activation="linear", padding="same", strides=1)(segmentation_output) bn20 = BatchNormalization()(conv20) relu20 = Activation("relu")(bn20) down5 = MaxPooling2D(pool_size=(4, 4), strides=4)(relu20) conv21 = Conv2D(32, 3, activation="linear", padding="same", strides=1)(down5) bn21 = BatchNormalization()(conv21) relu21 = Activation("relu")(bn21) down6 = MaxPooling2D(pool_size=(4, 4), strides=4)(relu21) conv22 = Conv2D(64, 3, activation="linear", padding="same", strides=1)(down6) bn22 = BatchNormalization()(conv22) relu22 = Activation("relu")(bn22) down7 = MaxPooling2D(pool_size=(4, 4), strides=4)(relu22) flatten1 = Flatten()(down7) concat5 = concatenate([gap1, gap2, gap3, flatten1], axis=-1) # FC layers fc1 = Dense(1024, activation="relu")(concat5) dropout1 = Dropout(0.5)(fc1) fc2 = Dense(1024, activation="relu")(dropout1) dropout2 = Dropout(0.5)(fc2) classification_output = Dense(num_classes, activation="softmax", name="classification_output")(dropout2) # Define the model model = Model(inputs=inputs, outputs=[classification_output, segmentation_output]) return model def segmentation_loss(y_true, y_pred): y_true = tf.cast(y_true, tf.float32) y_pred = tf.cast(y_pred, tf.float32) bce_loss = tf.keras.losses.binary_crossentropy(y_true, y_pred) smooth = 1e-5 intersection = tf.reduce_sum(y_true * y_pred) union = tf.reduce_sum(y_true) + tf.reduce_sum(y_pred) dice_loss = 1.0 - 2.0 * (intersection + smooth) / (union + smooth) segmentation_loss = bce_loss + 1 * dice_loss return segmentation_loss def train_model(model, X_train, y_train_class, y_train_seg, X_val, y_val_class, y_val_seg, batch_size, epochs): checkpoint = ModelCheckpoint( "multitask_best_weights.h5", monitor="val_classification_output_accuracy", save_best_only=True, mode="max", verbose=1,) reduce_lr = ReduceLROnPlateau( monitor="val_classification_output_accuracy", factor=0.3, patience=2, min_delta=0.001, mode="auto", verbose=1,) tensorboard = TensorBoard(log_dir="logs") model.compile( optimizer=Adam(lr=0.001), loss={"classification_output": "categorical_crossentropy", "segmentation_output": segmentation_loss}, metrics={"classification_output": "accuracy", "segmentation_output": "accuracy"}, loss_weights={"classification_output": 1, "segmentation_output": 1},) history = model.fit( X_train, {"classification_output": y_train_class, "segmentation_output": y_train_seg}, validation_data=(X_val, {"classification_output": y_val_class, "segmentation_output": y_val_seg}), epochs=epochs, verbose=1, batch_size=batch_size, callbacks=[checkpoint, reduce_lr, tensorboard],) return history def evaluate_model(model, X_test, y_test_class, y_test_seg): with tf.keras.utils.custom_object_scope({"segmentation_loss": segmentation_loss}): # Load the best model weights best_model = load_model("multitask_best_weights.h5") # Evaluate the model on test data test_loss, test_class_loss, test_seg_loss, test_class_acc, test_seg_acc = best_model.evaluate( X_test, {"classification_output": y_test_class, "segmentation_output": y_test_seg}) print("Test Classification Loss:", test_class_loss) print("Test Segmentation Loss:", test_seg_loss) print("Test Classification Accuracy:", test_class_acc) print("Test Segmentation Accuracy:", test_seg_acc) # Evaluate the model on validation data val_loss, val_class_loss, val_seg_loss, val_class_acc, val_seg_acc = best_model.evaluate( X_val, {'classification_output': y_val_class, 'segmentation_output': y_val_seg}) print("Validation Classification Loss:", val_class_loss) print("Validation Segmentation Loss:", val_seg_loss) print("Validation Classification Accuracy:", val_class_acc) print("Validation Segmentation Accuracy:", val_seg_acc) # Evaluate the model on training data train_loss, train_class_loss, train_seg_loss, train_class_acc, train_seg_acc = best_model.evaluate(X_train, {'classification_output': y_train_class, 'segmentation_output': y_train_seg}) print("Train Classification Loss:", train_class_loss) print("Train Segmentation Loss:", train_seg_loss) print("Train Classification Accuracy:", train_class_acc) print("Train Segmentation Accuracy:", train_seg_acc) # Return test classification accuracy return test_class_acc def plot_performance(history): # Plot classification accuracy classification_train_accuracy = history.history["classification_output_accuracy"] classification_val_accuracy = history.history["val_classification_output_accuracy"] plt.figure(figsize=(7, 3)) plt.plot(classification_train_accuracy, label="Training Accuracy") plt.plot(classification_val_accuracy, label="Validation Accuracy") plt.title("Classification Accuracy") plt.xlabel("Epochs") plt.ylabel("Accuracy") plt.legend() plt.show() # Plot classification loss classification_train_loss = history.history["classification_output_loss"] classification_val_loss = history.history["val_classification_output_loss"] plt.figure(figsize=(7, 3)) plt.plot(classification_train_loss, "b", label="Training Loss") plt.plot(classification_val_loss, "r", label="Validation Loss") plt.title("Classification Loss") plt.xlabel("Epochs") plt.ylabel("Loss") plt.legend() plt.show() # Plot segmentation accuracy segmentation_train_accuracy = history.history["segmentation_output_accuracy"] segmentation_val_accuracy = history.history["val_segmentation_output_accuracy"] plt.figure(figsize=(7, 3)) plt.plot(segmentation_train_accuracy, label="Training Accuracy") plt.plot(segmentation_val_accuracy, label="Validation Accuracy") plt.title("Segmentation Accuracy") plt.xlabel("Epochs") plt.ylabel("Accuracy") plt.legend() plt.show() # Plot segmentation loss segmentation_train_loss = history.history["segmentation_output_loss"] segmentation_val_loss = history.history["val_segmentation_output_loss"] plt.figure(figsize=(7, 3)) plt.plot(segmentation_train_loss, "b", label="Training Loss") plt.plot(segmentation_val_loss, "r", label="Validation Loss") plt.title("Segmentation Loss") plt.xlabel("Epochs") plt.ylabel("Loss") plt.legend() plt.show() # Set image size image_size = 224 # Define labels labels = ["bridge", "excess", "good"] # Set data folders data_folders = [ "/content/gdrive/MyDrive/Deep learning/FYP_2/4 Dataset Ratio 60 20 20/jit012/jit0/f_dip/train", "/content/gdrive/MyDrive/Deep learning/FYP_2/4 Dataset Ratio 60 20 20/jit012/jit0/f_dip/val", "/content/gdrive/MyDrive/Deep learning/FYP_2/4 Dataset Ratio 60 20 20/jit012/jit0/f_dip/test",] # Load data X_data, y_class_labels, y_seg_labels = load_data(data_folders) # Define train:val:test ratio for each class (ratio x4 = exact) class_data_counts = { "bridge": [40, 80, 80], "excess": [40, 80, 80], "good": [40, 80, 80], } # Split data X_train, y_train_class, y_train_seg, X_val, y_val_class, y_val_seg, X_test, y_test_class, y_test_seg = split_data( X_data, y_class_labels, y_seg_labels, class_data_counts) ''' print("Number of train images:", len(X_train)) print("Number of train binary masks:", len(y_train_seg)) print("Number of validation images:", len(X_val)) print("Number of validation binary masks:", len(y_val_seg)) print("Number of test images:", len(X_test)) print("Number of test binary masks:", len(y_test_seg)) ''' # Initialize the label encoder label_encoder = LabelEncoder() label_encoder.fit(y_class_labels) # Count the number of images of each class in the train, validation, and test sets train_counts = count_labels(y_train_class, label_encoder) val_counts = count_labels(y_val_class, label_encoder) test_counts = count_labels(y_test_class, label_encoder) print("Train counts: ", train_counts," Total in train set:", sum(train_counts.values())) print("Validation counts:", val_counts, " Total in validation set:", sum(val_counts.values())) print("Test counts: ", test_counts," Total in test set:", sum(test_counts.values())) # Build model input_shape = (image_size, image_size, 3) num_classes = len(labels) model = build_model(input_shape, num_classes) model.summary() # Train model n times test_class_acc_list = [] for i in range(5): print(f"\nTrain {i+1}:\n") model = build_model(input_shape, num_classes) batch_size = 16 epochs = 50 history = train_model(model, X_train, y_train_class, y_train_seg, X_val, y_val_class, y_val_seg, batch_size, epochs) # Evaluate model on test data test_class_acc = evaluate_model(model, X_test, y_test_class, y_test_seg) plot_performance(history) test_class_acc_list.append(test_class_acc) # Calculate average test classification accuracy average_test_class_acc = sum(test_class_acc_list) / len(test_class_acc_list) print("Test Classification Accuracy List:", test_class_acc_list) print("Average Test Classification Accuracy:", average_test_class_acc) " The above is the Python code with Keras to do multi-task learning with binary segmentation and classification using one mult-task learning model. I train the model 5 times and take the average accuracy. Modify the code to change the model to resnet50 (from keras library), so no need to perform segmentation, only perform classification. Do not modify the other part of my code. Show full code.
09a55fa5b635d33ecdfee6a7d7e45bcf
{ "intermediate": 0.3006076216697693, "beginner": 0.3237382769584656, "expert": 0.3756541907787323 }
42,747
We have a Sop reminder that triggering every monday. I need that whenever the reminder triggers that attachment will also go with it in servicenow
44cc02dad97ec8a2b0814bad7bad3cac
{ "intermediate": 0.3587626814842224, "beginner": 0.30641186237335205, "expert": 0.33482545614242554 }
42,748
You are a Python expert who can provide clear, concise, high-quality code. " import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns import cv2 import random import tensorflow as tf import tkinter as tk from tkinter import filedialog from PIL import ImageTk, Image from ipywidgets import interact, interactive, fixed, interact_manual import ipywidgets as widgets from IPython.display import display, clear_output from tensorflow.keras.preprocessing import image from tensorflow.keras.optimizers import Adam, SGD, RMSprop, AdamW, Adadelta, Adagrad, Adamax, Adafactor, Nadam, Ftrl from tensorflow.keras.preprocessing.image import ImageDataGenerator from tqdm import tqdm import os from sklearn.utils import shuffle from sklearn.preprocessing import LabelEncoder from sklearn.model_selection import train_test_split from tensorflow.keras.models import Sequential, Model, load_model from tensorflow.keras.layers import ( GlobalAveragePooling2D, Dropout, Dense, Conv2D, MaxPooling2D, Flatten, Dropout, BatchNormalization, Activation, concatenate, Conv2DTranspose, Input, Reshape, UpSampling2D, ) from tensorflow.keras.applications import ( EfficientNetV2B0, EfficientNetV2B1, EfficientNetV2B2, EfficientNetV2B3, EfficientNetV2L, EfficientNetV2M, EfficientNetV2S, ) from tensorflow.keras.applications import Xception from tensorflow.keras.applications import VGG16, VGG19 from tensorflow.keras.applications import ResNet50, ResNet101, ResNet152, ResNetRS50, ResNetRS101 from tensorflow.keras.applications import InceptionResNetV2, ConvNeXtXLarge, ConvNeXtBase, DenseNet121, MobileNetV2, NASNetLarge, NASNetMobile from tensorflow.keras.utils import to_categorical from tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau, TensorBoard, ModelCheckpoint from sklearn.metrics import classification_report, confusion_matrix import ipywidgets as widgets import io from PIL import Image from IPython.display import display, clear_output from warnings import filterwarnings from google.colab import drive drive.mount("/content/gdrive") def load_data(data_folders): X_data = [] # Combined data y_class_labels = [] # Combined classification labels y_seg_labels = [] # Combined segmentation labels for folderPath in data_folders: for label in labels: label_folder_path = os.path.join(folderPath, label) for filename in tqdm(os.listdir(label_folder_path)): if filename.endswith(".jpg"): img = cv2.imread(os.path.join(label_folder_path, filename)) img = cv2.resize(img, (image_size, image_size)) X_data.append(img) y_class_labels.append(label) seg_filename = filename.split(".")[0] + ".png" seg_img = cv2.imread(os.path.join(label_folder_path, seg_filename), 0) seg_img = cv2.resize(seg_img, (image_size, image_size)) seg_img = np.where(seg_img > 0, 1, 0) # Convert segmentation mask to binary y_seg_labels.append(seg_img) X_data = np.array(X_data) y_class_labels = np.array(y_class_labels) y_seg_labels = np.array(y_seg_labels) X_data, y_class_labels, y_seg_labels = shuffle(X_data, y_class_labels, y_seg_labels, random_state=101) return X_data, y_class_labels, y_seg_labels def split_data(X_data, y_class_labels, y_seg_labels, class_data_counts): X_train = [] y_train_class = [] y_train_seg = [] X_val = [] y_val_class = [] y_val_seg = [] X_test = [] y_test_class = [] y_test_seg = [] for label, count in class_data_counts.items(): label_indices = np.where(y_class_labels == label)[0] class_X_data = X_data[label_indices] class_y_class_labels = y_class_labels[label_indices] class_y_seg_labels = y_seg_labels[label_indices] train_count = count[0] val_count = count[1] test_count = count[2] class_X_train = class_X_data[:train_count] class_y_train_class = class_y_class_labels[:train_count] class_y_train_seg = class_y_seg_labels[:train_count] class_X_val = class_X_data[train_count: train_count + val_count] class_y_val_class = class_y_class_labels[train_count: train_count + val_count] class_y_val_seg = class_y_seg_labels[train_count: train_count + val_count] class_X_test = class_X_data[train_count + val_count: train_count + val_count + test_count] class_y_test_class = class_y_class_labels[train_count + val_count: train_count + val_count + test_count] class_y_test_seg = class_y_seg_labels[train_count + val_count: train_count + val_count + test_count] X_train.extend(class_X_train) y_train_class.extend(class_y_train_class) y_train_seg.extend(class_y_train_seg) X_val.extend(class_X_val) y_val_class.extend(class_y_val_class) y_val_seg.extend(class_y_val_seg) X_test.extend(class_X_test) y_test_class.extend(class_y_test_class) y_test_seg.extend(class_y_test_seg) # Convert class labels to categorical label_encoder = LabelEncoder() y_train_class_encoded = label_encoder.fit_transform(y_train_class) y_train_class_categorical = to_categorical(y_train_class_encoded) y_val_class_encoded = label_encoder.transform(y_val_class) y_val_class_categorical = to_categorical(y_val_class_encoded) y_test_class_encoded = label_encoder.transform(y_test_class) y_test_class_categorical = to_categorical(y_test_class_encoded) return ( np.array(X_train), np.array(y_train_class_categorical), np.array(y_train_seg), np.array(X_val), np.array(y_val_class_categorical), np.array(y_val_seg), np.array(X_test), np.array(y_test_class_categorical), np.array(y_test_seg), ) def count_labels(y_class_categorical, label_encoder): # Convert one-hot encoded labels back to label encoded y_class_labels = np.argmax(y_class_categorical, axis=1) # Convert label encoded labels back to original class names y_class_names = label_encoder.inverse_transform(y_class_labels) unique, counts = np.unique(y_class_names, return_counts=True) return dict(zip(unique, counts)) def build_model(input_shape, num_classes): num_filter = 32 # 16/32 best, 8: best classification but no segment # Encoder (Done) inputs = Input(input_shape) conv1 = Conv2D(num_filter * 1, 3, activation="linear", padding="same", strides=1)(inputs) bn1 = BatchNormalization()(conv1) relu1 = Activation("relu")(bn1) conv2 = Conv2D(num_filter * 1, 3, activation="linear", padding="same", strides=1)(relu1) bn2 = BatchNormalization()(conv2) relu2 = Activation("relu")(bn2) down1 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu2) conv3 = Conv2D(num_filter * 2, 3, activation="linear", padding="same", strides=1)(down1) bn3 = BatchNormalization()(conv3) relu3 = Activation("relu")(bn3) conv4 = Conv2D(num_filter * 2, 3, activation="linear", padding="same", strides=1)(relu3) bn4 = BatchNormalization()(conv4) relu4 = Activation("relu")(bn4) down2 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu4) conv5 = Conv2D(num_filter * 4, 3, activation="linear", padding="same", strides=1)(down2) bn5 = BatchNormalization()(conv5) relu5 = Activation("relu")(bn5) conv6 = Conv2D(num_filter * 4, 3, activation="linear", padding="same", strides=1)(relu5) bn6 = BatchNormalization()(conv6) relu6 = Activation("relu")(bn6) down3 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu6) conv7 = Conv2D(num_filter * 8, 3, activation="linear", padding="same", strides=1)(down3) bn7 = BatchNormalization()(conv7) relu7 = Activation("relu")(bn7) conv8 = Conv2D(num_filter * 8, 3, activation="linear", padding="same", strides=1)(relu7) bn8 = BatchNormalization()(conv8) relu8 = Activation("relu")(bn8) # Middle down4 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu8) conv9 = Conv2D(num_filter * 16, 3, activation="linear", padding="same", strides=1)(down4) bn9 = BatchNormalization()(conv9) relu9 = Activation("relu")(bn9) conv10 = Conv2D(num_filter * 16, 3, activation="linear", padding="same", strides=1)(relu9) bn10 = BatchNormalization()(conv10) relu10 = Activation("relu")(bn10) up1 = UpSampling2D(size=(2, 2), interpolation="bilinear")(relu10) # Decoder (Done) concat1 = concatenate([up1, relu8], axis=-1) # , axis=3 conv11 = Conv2D(num_filter * 8, 3, activation="linear", padding="same", strides=1)(concat1) bn11 = BatchNormalization()(conv11) relu11 = Activation("relu")(bn11) conv12 = Conv2D(num_filter * 8, 3, activation="linear", padding="same", strides=1)(relu11) bn12 = BatchNormalization()(conv12) relu12 = Activation("relu")(bn12) up2 = UpSampling2D(size=(2, 2), interpolation="bilinear")(relu12) concat2 = concatenate([up2, relu6], axis=-1) # , axis=3 conv13 = Conv2D(num_filter * 4, 3, activation="linear", padding="same", strides=1)(concat2) bn13 = BatchNormalization()(conv13) relu13 = Activation("relu")(bn13) conv14 = Conv2D(num_filter * 4, 3, activation="linear", padding="same", strides=1)(relu13) bn14 = BatchNormalization()(conv14) relu14 = Activation("relu")(bn14) up3 = UpSampling2D(size=(2, 2), interpolation="bilinear")(relu14) concat3 = concatenate([up3, relu4], axis=-1) # , axis=3 conv15 = Conv2D(num_filter * 2, 3, activation="linear", padding="same", strides=1)(concat3) bn15 = BatchNormalization()(conv15) relu15 = Activation("relu")(bn15) conv16 = Conv2D(num_filter * 2, 3, activation="linear", padding="same", strides=1)(relu15) bn16 = BatchNormalization()(conv16) relu16 = Activation("relu")(bn16) up4 = UpSampling2D(size=(2, 2), interpolation="bilinear")(relu16) concat4 = concatenate([up4, relu2], axis=-1) # , axis=3 conv17 = Conv2D(num_filter * 1, 3, activation="linear", padding="same", strides=1)(concat4) bn17 = BatchNormalization()(conv17) relu17 = Activation("relu")(bn17) conv18 = Conv2D(num_filter * 1, 3, activation="linear", padding="same", strides=1)(relu17) bn18 = BatchNormalization()(conv18) relu18 = Activation("relu")(bn18) # Segmentation branch segmentation_output = Conv2D(1, 1, activation="sigmoid", name="segmentation_output")(relu18) # original # Classification branch (Not done) gap1 = GlobalAveragePooling2D()(relu8) gap2 = GlobalAveragePooling2D()(relu10) gap3 = GlobalAveragePooling2D()(relu12) conv20 = Conv2D(16, 3, activation="linear", padding="same", strides=1)(segmentation_output) bn20 = BatchNormalization()(conv20) relu20 = Activation("relu")(bn20) down5 = MaxPooling2D(pool_size=(4, 4), strides=4)(relu20) conv21 = Conv2D(32, 3, activation="linear", padding="same", strides=1)(down5) bn21 = BatchNormalization()(conv21) relu21 = Activation("relu")(bn21) down6 = MaxPooling2D(pool_size=(4, 4), strides=4)(relu21) conv22 = Conv2D(64, 3, activation="linear", padding="same", strides=1)(down6) bn22 = BatchNormalization()(conv22) relu22 = Activation("relu")(bn22) down7 = MaxPooling2D(pool_size=(4, 4), strides=4)(relu22) flatten1 = Flatten()(down7) concat5 = concatenate([gap1, gap2, gap3, flatten1], axis=-1) # FC layers fc1 = Dense(1024, activation="relu")(concat5) dropout1 = Dropout(0.5)(fc1) fc2 = Dense(1024, activation="relu")(dropout1) dropout2 = Dropout(0.5)(fc2) classification_output = Dense(num_classes, activation="softmax", name="classification_output")(dropout2) # Define the model model = Model(inputs=inputs, outputs=[classification_output, segmentation_output]) return model def segmentation_loss(y_true, y_pred): y_true = tf.cast(y_true, tf.float32) y_pred = tf.cast(y_pred, tf.float32) bce_loss = tf.keras.losses.binary_crossentropy(y_true, y_pred) smooth = 1e-5 intersection = tf.reduce_sum(y_true * y_pred) union = tf.reduce_sum(y_true) + tf.reduce_sum(y_pred) dice_loss = 1.0 - 2.0 * (intersection + smooth) / (union + smooth) segmentation_loss = bce_loss + 1 * dice_loss return segmentation_loss def train_model(model, X_train, y_train_class, y_train_seg, X_val, y_val_class, y_val_seg, batch_size, epochs): checkpoint = ModelCheckpoint( "multitask_best_weights.h5", monitor="val_classification_output_accuracy", save_best_only=True, mode="max", verbose=1,) reduce_lr = ReduceLROnPlateau( monitor="val_classification_output_accuracy", factor=0.3, patience=2, min_delta=0.001, mode="auto", verbose=1,) tensorboard = TensorBoard(log_dir="logs") model.compile( optimizer=Adam(lr=0.001), loss={"classification_output": "categorical_crossentropy", "segmentation_output": segmentation_loss}, metrics={"classification_output": "accuracy", "segmentation_output": "accuracy"}, loss_weights={"classification_output": 1, "segmentation_output": 1},) history = model.fit( X_train, {"classification_output": y_train_class, "segmentation_output": y_train_seg}, validation_data=(X_val, {"classification_output": y_val_class, "segmentation_output": y_val_seg}), epochs=epochs, verbose=1, batch_size=batch_size, callbacks=[checkpoint, reduce_lr, tensorboard],) return history def evaluate_model(model, X_test, y_test_class, y_test_seg): with tf.keras.utils.custom_object_scope({"segmentation_loss": segmentation_loss}): # Load the best model weights best_model = load_model("multitask_best_weights.h5") # Evaluate the model on test data test_loss, test_class_loss, test_seg_loss, test_class_acc, test_seg_acc = best_model.evaluate( X_test, {"classification_output": y_test_class, "segmentation_output": y_test_seg}) print("Test Classification Loss:", test_class_loss) print("Test Segmentation Loss:", test_seg_loss) print("Test Classification Accuracy:", test_class_acc) print("Test Segmentation Accuracy:", test_seg_acc) # Evaluate the model on validation data val_loss, val_class_loss, val_seg_loss, val_class_acc, val_seg_acc = best_model.evaluate( X_val, {'classification_output': y_val_class, 'segmentation_output': y_val_seg}) print("Validation Classification Loss:", val_class_loss) print("Validation Segmentation Loss:", val_seg_loss) print("Validation Classification Accuracy:", val_class_acc) print("Validation Segmentation Accuracy:", val_seg_acc) # Evaluate the model on training data train_loss, train_class_loss, train_seg_loss, train_class_acc, train_seg_acc = best_model.evaluate(X_train, {'classification_output': y_train_class, 'segmentation_output': y_train_seg}) print("Train Classification Loss:", train_class_loss) print("Train Segmentation Loss:", train_seg_loss) print("Train Classification Accuracy:", train_class_acc) print("Train Segmentation Accuracy:", train_seg_acc) # Return test classification accuracy return test_class_acc def plot_performance(history): # Plot classification accuracy classification_train_accuracy = history.history["classification_output_accuracy"] classification_val_accuracy = history.history["val_classification_output_accuracy"] plt.figure(figsize=(7, 3)) plt.plot(classification_train_accuracy, label="Training Accuracy") plt.plot(classification_val_accuracy, label="Validation Accuracy") plt.title("Classification Accuracy") plt.xlabel("Epochs") plt.ylabel("Accuracy") plt.legend() plt.show() # Plot classification loss classification_train_loss = history.history["classification_output_loss"] classification_val_loss = history.history["val_classification_output_loss"] plt.figure(figsize=(7, 3)) plt.plot(classification_train_loss, "b", label="Training Loss") plt.plot(classification_val_loss, "r", label="Validation Loss") plt.title("Classification Loss") plt.xlabel("Epochs") plt.ylabel("Loss") plt.legend() plt.show() # Plot segmentation accuracy segmentation_train_accuracy = history.history["segmentation_output_accuracy"] segmentation_val_accuracy = history.history["val_segmentation_output_accuracy"] plt.figure(figsize=(7, 3)) plt.plot(segmentation_train_accuracy, label="Training Accuracy") plt.plot(segmentation_val_accuracy, label="Validation Accuracy") plt.title("Segmentation Accuracy") plt.xlabel("Epochs") plt.ylabel("Accuracy") plt.legend() plt.show() # Plot segmentation loss segmentation_train_loss = history.history["segmentation_output_loss"] segmentation_val_loss = history.history["val_segmentation_output_loss"] plt.figure(figsize=(7, 3)) plt.plot(segmentation_train_loss, "b", label="Training Loss") plt.plot(segmentation_val_loss, "r", label="Validation Loss") plt.title("Segmentation Loss") plt.xlabel("Epochs") plt.ylabel("Loss") plt.legend() plt.show() # Set image size image_size = 224 # Define labels labels = ["bridge", "excess", "good"] # Set data folders data_folders = [ "/content/gdrive/MyDrive/Deep learning/FYP_2/4 Dataset Ratio 60 20 20/jit012/jit0/f_dip/train", "/content/gdrive/MyDrive/Deep learning/FYP_2/4 Dataset Ratio 60 20 20/jit012/jit0/f_dip/val", "/content/gdrive/MyDrive/Deep learning/FYP_2/4 Dataset Ratio 60 20 20/jit012/jit0/f_dip/test",] # Load data X_data, y_class_labels, y_seg_labels = load_data(data_folders) # Define train:val:test ratio for each class (ratio x4 = exact) class_data_counts = { "bridge": [40, 80, 80], "excess": [40, 80, 80], "good": [40, 80, 80], } # Split data X_train, y_train_class, y_train_seg, X_val, y_val_class, y_val_seg, X_test, y_test_class, y_test_seg = split_data( X_data, y_class_labels, y_seg_labels, class_data_counts) ''' print("Number of train images:", len(X_train)) print("Number of train binary masks:", len(y_train_seg)) print("Number of validation images:", len(X_val)) print("Number of validation binary masks:", len(y_val_seg)) print("Number of test images:", len(X_test)) print("Number of test binary masks:", len(y_test_seg)) ''' # Initialize the label encoder label_encoder = LabelEncoder() label_encoder.fit(y_class_labels) # Count the number of images of each class in the train, validation, and test sets train_counts = count_labels(y_train_class, label_encoder) val_counts = count_labels(y_val_class, label_encoder) test_counts = count_labels(y_test_class, label_encoder) print("Train counts: ", train_counts," Total in train set:", sum(train_counts.values())) print("Validation counts:", val_counts, " Total in validation set:", sum(val_counts.values())) print("Test counts: ", test_counts," Total in test set:", sum(test_counts.values())) # Build model input_shape = (image_size, image_size, 3) num_classes = len(labels) model = build_model(input_shape, num_classes) model.summary() # Train model n times test_class_acc_list = [] for i in range(5): print(f"\nTrain {i+1}:\n") model = build_model(input_shape, num_classes) batch_size = 16 epochs = 50 history = train_model(model, X_train, y_train_class, y_train_seg, X_val, y_val_class, y_val_seg, batch_size, epochs) # Evaluate model on test data test_class_acc = evaluate_model(model, X_test, y_test_class, y_test_seg) plot_performance(history) test_class_acc_list.append(test_class_acc) # Calculate average test classification accuracy average_test_class_acc = sum(test_class_acc_list) / len(test_class_acc_list) print("Test Classification Accuracy List:", test_class_acc_list) print("Average Test Classification Accuracy:", average_test_class_acc) " The above is the Python code with Keras to do multi-task learning with binary segmentation and classification using one mult-task learning model. I train the model 5 times and take the average accuracy. Modify the code to change the model to resnet50 (from keras library), so no need to perform segmentation, only perform classification. Do not modify the other part of my code. Show full code.
4df943f7aa35397e445c73588dcbf9b9
{ "intermediate": 0.3006076216697693, "beginner": 0.3237382769584656, "expert": 0.3756541907787323 }
42,749
please explain these steps like i am a layperson: ""RAPTOR: Recursive Abstractive Processing for Tree-Organized Retrieval RAPTOR introduces a novel approach to retrieval-augmented language models by constructing a recursive tree structure from documents. This allows for more efficient and context-aware information retrieval across large texts, addressing common limitations in traditional language models. For detailed methodologies and implementations, refer to the original paper: RAPTOR: Recursive Abstractive Processing for Tree-Organized Retrieval Paper page PWC Installation Before using RAPTOR, ensure Python 3.8+ is installed. Clone the RAPTOR repository and install necessary dependencies: git clone https://github.com/parthsarthi03/raptor.git cd raptor pip install -r requirements.txt Basic Usage To get started with RAPTOR, follow these steps: Setting Up RAPTOR First, set your OpenAI API key and initialize the RAPTOR configuration: import os os.environ["OPENAI_API_KEY"] = "your-openai-api-key" from raptor import RetrievalAugmentation # Initialize with default configuration. For advanced configurations, check the documentation. [WIP] RA = RetrievalAugmentation() Adding Documents to the Tree Add your text documents to RAPTOR for indexing: with open('sample.txt', 'r') as file: text = file.read() RA.add_documents(text) Answering Questions You can now use RAPTOR to answer questions based on the indexed documents: question = "How did Cinderella reach her happy ending?" answer = RA.answer_question(question=question) print("Answer: ", answer) Saving and Loading the Tree Save the constructed tree to a specified path: SAVE_PATH = "demo/cinderella" RA.save(SAVE_PATH) Load the saved tree back into RAPTOR: RA = RetrievalAugmentation(tree=SAVE_PATH) answer = RA.answer_question(question=question)""
b4cb1501ca5a820dbc0dc28aaaaf69c4
{ "intermediate": 0.7287807464599609, "beginner": 0.12660636007785797, "expert": 0.1446128636598587 }
42,750
Привожу код на C++, в PatchProcess слишком много вложенных условий, что явно не подходит под best practices, можешь исправить это? #include "pch.h" #include <Windows.h> #include <tlhelp32.h> #include <psapi.h> #include <fstream> #include <vector> #include <string> #include <memory> #include <thread> class Logger { public: explicit Logger(const std::string& filename) : logFile(filename) {} void Log(const std::string& message) { if (logFile.is_open()) { logFile << message << "\n"; } } private: std::ofstream logFile; }; Logger logger("patcher_log.txt"); bool PatchProcess(DWORD processID, Logger& logger) { // Открытие дескриптора процесса с необходимыми правами доступа HANDLE hProcess = OpenProcess(PROCESS_VM_OPERATION | PROCESS_VM_READ | PROCESS_VM_WRITE, FALSE, processID); if (!hProcess) { logger.Log("Failed to open the target process."); return false; } // Используем std::unique_ptr для автоматического закрытия дескриптора std::unique_ptr<void, decltype(&CloseHandle)> processCloser(hProcess, CloseHandle); // Массив байт для поиска в памяти процесса BYTE signatureBytes[] = { 0x85, 0xC0, 0x74, 0x57, 0x5F, 0xB8, 0x01 }; BYTE patchByte = 0x00; // Байт, используемый для патча MEMORY_BASIC_INFORMATION mbi{}; // Переменная успешности операции bool success = false; // Циклический просмотр памяти процесса for (BYTE* addr = nullptr; VirtualQueryEx(hProcess, addr, &mbi, sizeof(mbi)) && addr < (BYTE*)0x7FFFFFFF; addr += mbi.RegionSize) { // Поиск сегментов памяти с разрешенным выполнением и чтением if (mbi.State == MEM_COMMIT && (mbi.Protect == PAGE_EXECUTE_READWRITE || mbi.Protect == PAGE_EXECUTE_READ)) { // Буфер для хранения данных сегмента памяти std::vector<BYTE> buffer(mbi.RegionSize); SIZE_T bytesRead; // Чтение памяти из процесса if (ReadProcessMemory(hProcess, mbi.BaseAddress, buffer.data(), mbi.RegionSize, &bytesRead)) { // Поиск сигнатуры в буфере for (size_t j = 0; j < bytesRead - sizeof(signatureBytes); ++j) { if (memcmp(buffer.data() + j, signatureBytes, sizeof(signatureBytes)) == 0) { DWORD oldProtect; // Изменение защиты страницы на запись перед патчем if (VirtualProtectEx(hProcess, addr + j + sizeof(signatureBytes) - 1, 1, PAGE_EXECUTE_READWRITE, &oldProtect)) { // Попытка записать патч и проверка успеха if (WriteProcessMemory(hProcess, addr + j + sizeof(signatureBytes) - 1, &patchByte, 1, nullptr)) { // Возвращаем оригинальные настройки защиты страницы VirtualProtectEx(hProcess, addr + j + sizeof(signatureBytes) - 1, 1, oldProtect, &oldProtect); logger.Log("Signature patched."); success = true; // Отмечаем успех return success; } else { // Возврат защиты страницы в случае неудачи записи VirtualProtectEx(hProcess, addr + j + sizeof(signatureBytes) - 1, 1, oldProtect, &oldProtect); logger.Log("Failed to apply patch."); } } } } } } } return success; } void AttemptToPatch(DWORD currentPID, Logger& logger) { logger.Log("Attempting to patch current process ID : " + std::to_string(currentPID) + " in a separate thread."); while (!PatchProcess(currentPID, logger)) { logger.Log("Failed to patch the current process.Retrying…"); std::this_thread::sleep_for(std::chrono::seconds(5)); } logger.Log("Current process patched successfully."); } DWORD WINAPI MonitorProcess(LPVOID lpParam) { Logger* logger = static_cast<Logger*>(lpParam); DWORD currentPID = GetCurrentProcessId(); std::thread patcherThread(AttemptToPatch, currentPID, std::ref(*logger)); patcherThread.detach(); return 0; } BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: DisableThreadLibraryCalls(hModule); CreateThread(nullptr, 0, MonitorProcess, static_cast<LPVOID>(&logger), 0, nullptr); break; case DLL_THREAD_ATTACH: case DLL_THREAD_DETACH: case DLL_PROCESS_DETACH: break; } return TRUE; }
703e26848309996259a3efc2e1ad077a
{ "intermediate": 0.3632993996143341, "beginner": 0.5369626879692078, "expert": 0.09973789751529694 }
42,751
You are a Python expert who can provide clear, concise, high-quality code. " import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns import cv2 import random import tensorflow as tf import tkinter as tk from tkinter import filedialog from PIL import ImageTk, Image from ipywidgets import interact, interactive, fixed, interact_manual import ipywidgets as widgets from IPython.display import display, clear_output from tensorflow.keras.preprocessing import image from tensorflow.keras.optimizers import Adam, SGD, RMSprop, AdamW, Adadelta, Adagrad, Adamax, Adafactor, Nadam, Ftrl from tensorflow.keras.preprocessing.image import ImageDataGenerator from tqdm import tqdm import os from sklearn.utils import shuffle from sklearn.preprocessing import LabelEncoder from sklearn.model_selection import train_test_split from tensorflow.keras.models import Sequential, Model, load_model from tensorflow.keras.layers import ( GlobalAveragePooling2D, Dropout, Dense, Conv2D, MaxPooling2D, Flatten, Dropout, BatchNormalization, Activation, concatenate, Conv2DTranspose, Input, Reshape, UpSampling2D, ) from tensorflow.keras.applications import ( EfficientNetV2B0, EfficientNetV2B1, EfficientNetV2B2, EfficientNetV2B3, EfficientNetV2L, EfficientNetV2M, EfficientNetV2S, ) from tensorflow.keras.applications import Xception from tensorflow.keras.applications import VGG16, VGG19 from tensorflow.keras.applications import ResNet50, ResNet101, ResNet152, ResNetRS50, ResNetRS101 from tensorflow.keras.applications import InceptionResNetV2, ConvNeXtXLarge, ConvNeXtBase, DenseNet121, MobileNetV2, NASNetLarge, NASNetMobile from tensorflow.keras.utils import to_categorical from tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau, TensorBoard, ModelCheckpoint from sklearn.metrics import classification_report, confusion_matrix import ipywidgets as widgets import io from PIL import Image from IPython.display import display, clear_output from warnings import filterwarnings from google.colab import drive drive.mount("/content/gdrive") def load_data(data_folders): X_data = [] # Combined data y_class_labels = [] # Combined classification labels y_seg_labels = [] # Combined segmentation labels for folderPath in data_folders: for label in labels: label_folder_path = os.path.join(folderPath, label) for filename in tqdm(os.listdir(label_folder_path)): if filename.endswith(".jpg"): img = cv2.imread(os.path.join(label_folder_path, filename)) img = cv2.resize(img, (image_size, image_size)) X_data.append(img) y_class_labels.append(label) seg_filename = filename.split(".")[0] + ".png" seg_img = cv2.imread(os.path.join(label_folder_path, seg_filename), 0) seg_img = cv2.resize(seg_img, (image_size, image_size)) seg_img = np.where(seg_img > 0, 1, 0) # Convert segmentation mask to binary y_seg_labels.append(seg_img) X_data = np.array(X_data) y_class_labels = np.array(y_class_labels) y_seg_labels = np.array(y_seg_labels) X_data, y_class_labels, y_seg_labels = shuffle(X_data, y_class_labels, y_seg_labels, random_state=101) return X_data, y_class_labels, y_seg_labels def split_data(X_data, y_class_labels, y_seg_labels, class_data_counts): X_train = [] y_train_class = [] y_train_seg = [] X_val = [] y_val_class = [] y_val_seg = [] X_test = [] y_test_class = [] y_test_seg = [] for label, count in class_data_counts.items(): label_indices = np.where(y_class_labels == label)[0] class_X_data = X_data[label_indices] class_y_class_labels = y_class_labels[label_indices] class_y_seg_labels = y_seg_labels[label_indices] train_count = count[0] val_count = count[1] test_count = count[2] class_X_train = class_X_data[:train_count] class_y_train_class = class_y_class_labels[:train_count] class_y_train_seg = class_y_seg_labels[:train_count] class_X_val = class_X_data[train_count: train_count + val_count] class_y_val_class = class_y_class_labels[train_count: train_count + val_count] class_y_val_seg = class_y_seg_labels[train_count: train_count + val_count] class_X_test = class_X_data[train_count + val_count: train_count + val_count + test_count] class_y_test_class = class_y_class_labels[train_count + val_count: train_count + val_count + test_count] class_y_test_seg = class_y_seg_labels[train_count + val_count: train_count + val_count + test_count] X_train.extend(class_X_train) y_train_class.extend(class_y_train_class) y_train_seg.extend(class_y_train_seg) X_val.extend(class_X_val) y_val_class.extend(class_y_val_class) y_val_seg.extend(class_y_val_seg) X_test.extend(class_X_test) y_test_class.extend(class_y_test_class) y_test_seg.extend(class_y_test_seg) # Convert class labels to categorical label_encoder = LabelEncoder() y_train_class_encoded = label_encoder.fit_transform(y_train_class) y_train_class_categorical = to_categorical(y_train_class_encoded) y_val_class_encoded = label_encoder.transform(y_val_class) y_val_class_categorical = to_categorical(y_val_class_encoded) y_test_class_encoded = label_encoder.transform(y_test_class) y_test_class_categorical = to_categorical(y_test_class_encoded) return ( np.array(X_train), np.array(y_train_class_categorical), np.array(y_train_seg), np.array(X_val), np.array(y_val_class_categorical), np.array(y_val_seg), np.array(X_test), np.array(y_test_class_categorical), np.array(y_test_seg), ) def count_labels(y_class_categorical, label_encoder): # Convert one-hot encoded labels back to label encoded y_class_labels = np.argmax(y_class_categorical, axis=1) # Convert label encoded labels back to original class names y_class_names = label_encoder.inverse_transform(y_class_labels) unique, counts = np.unique(y_class_names, return_counts=True) return dict(zip(unique, counts)) def build_model(input_shape, num_classes): num_filter = 32 # 16/32 best, 8: best classification but no segment # Encoder (Done) inputs = Input(input_shape) conv1 = Conv2D(num_filter * 1, 3, activation="linear", padding="same", strides=1)(inputs) bn1 = BatchNormalization()(conv1) relu1 = Activation("relu")(bn1) conv2 = Conv2D(num_filter * 1, 3, activation="linear", padding="same", strides=1)(relu1) bn2 = BatchNormalization()(conv2) relu2 = Activation("relu")(bn2) down1 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu2) conv3 = Conv2D(num_filter * 2, 3, activation="linear", padding="same", strides=1)(down1) bn3 = BatchNormalization()(conv3) relu3 = Activation("relu")(bn3) conv4 = Conv2D(num_filter * 2, 3, activation="linear", padding="same", strides=1)(relu3) bn4 = BatchNormalization()(conv4) relu4 = Activation("relu")(bn4) down2 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu4) conv5 = Conv2D(num_filter * 4, 3, activation="linear", padding="same", strides=1)(down2) bn5 = BatchNormalization()(conv5) relu5 = Activation("relu")(bn5) conv6 = Conv2D(num_filter * 4, 3, activation="linear", padding="same", strides=1)(relu5) bn6 = BatchNormalization()(conv6) relu6 = Activation("relu")(bn6) down3 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu6) conv7 = Conv2D(num_filter * 8, 3, activation="linear", padding="same", strides=1)(down3) bn7 = BatchNormalization()(conv7) relu7 = Activation("relu")(bn7) conv8 = Conv2D(num_filter * 8, 3, activation="linear", padding="same", strides=1)(relu7) bn8 = BatchNormalization()(conv8) relu8 = Activation("relu")(bn8) # Middle down4 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu8) conv9 = Conv2D(num_filter * 16, 3, activation="linear", padding="same", strides=1)(down4) bn9 = BatchNormalization()(conv9) relu9 = Activation("relu")(bn9) conv10 = Conv2D(num_filter * 16, 3, activation="linear", padding="same", strides=1)(relu9) bn10 = BatchNormalization()(conv10) relu10 = Activation("relu")(bn10) up1 = UpSampling2D(size=(2, 2), interpolation="bilinear")(relu10) # Decoder (Done) concat1 = concatenate([up1, relu8], axis=-1) # , axis=3 conv11 = Conv2D(num_filter * 8, 3, activation="linear", padding="same", strides=1)(concat1) bn11 = BatchNormalization()(conv11) relu11 = Activation("relu")(bn11) conv12 = Conv2D(num_filter * 8, 3, activation="linear", padding="same", strides=1)(relu11) bn12 = BatchNormalization()(conv12) relu12 = Activation("relu")(bn12) up2 = UpSampling2D(size=(2, 2), interpolation="bilinear")(relu12) concat2 = concatenate([up2, relu6], axis=-1) # , axis=3 conv13 = Conv2D(num_filter * 4, 3, activation="linear", padding="same", strides=1)(concat2) bn13 = BatchNormalization()(conv13) relu13 = Activation("relu")(bn13) conv14 = Conv2D(num_filter * 4, 3, activation="linear", padding="same", strides=1)(relu13) bn14 = BatchNormalization()(conv14) relu14 = Activation("relu")(bn14) up3 = UpSampling2D(size=(2, 2), interpolation="bilinear")(relu14) concat3 = concatenate([up3, relu4], axis=-1) # , axis=3 conv15 = Conv2D(num_filter * 2, 3, activation="linear", padding="same", strides=1)(concat3) bn15 = BatchNormalization()(conv15) relu15 = Activation("relu")(bn15) conv16 = Conv2D(num_filter * 2, 3, activation="linear", padding="same", strides=1)(relu15) bn16 = BatchNormalization()(conv16) relu16 = Activation("relu")(bn16) up4 = UpSampling2D(size=(2, 2), interpolation="bilinear")(relu16) concat4 = concatenate([up4, relu2], axis=-1) # , axis=3 conv17 = Conv2D(num_filter * 1, 3, activation="linear", padding="same", strides=1)(concat4) bn17 = BatchNormalization()(conv17) relu17 = Activation("relu")(bn17) conv18 = Conv2D(num_filter * 1, 3, activation="linear", padding="same", strides=1)(relu17) bn18 = BatchNormalization()(conv18) relu18 = Activation("relu")(bn18) # Segmentation branch segmentation_output = Conv2D(1, 1, activation="sigmoid", name="segmentation_output")(relu18) # original # Classification branch (Not done) gap1 = GlobalAveragePooling2D()(relu8) gap2 = GlobalAveragePooling2D()(relu10) gap3 = GlobalAveragePooling2D()(relu12) conv20 = Conv2D(16, 3, activation="linear", padding="same", strides=1)(segmentation_output) bn20 = BatchNormalization()(conv20) relu20 = Activation("relu")(bn20) down5 = MaxPooling2D(pool_size=(4, 4), strides=4)(relu20) conv21 = Conv2D(32, 3, activation="linear", padding="same", strides=1)(down5) bn21 = BatchNormalization()(conv21) relu21 = Activation("relu")(bn21) down6 = MaxPooling2D(pool_size=(4, 4), strides=4)(relu21) conv22 = Conv2D(64, 3, activation="linear", padding="same", strides=1)(down6) bn22 = BatchNormalization()(conv22) relu22 = Activation("relu")(bn22) down7 = MaxPooling2D(pool_size=(4, 4), strides=4)(relu22) flatten1 = Flatten()(down7) concat5 = concatenate([gap1, gap2, gap3, flatten1], axis=-1) # FC layers fc1 = Dense(1024, activation="relu")(concat5) dropout1 = Dropout(0.5)(fc1) fc2 = Dense(1024, activation="relu")(dropout1) dropout2 = Dropout(0.5)(fc2) classification_output = Dense(num_classes, activation="softmax", name="classification_output")(dropout2) # Define the model model = Model(inputs=inputs, outputs=[classification_output, segmentation_output]) return model def segmentation_loss(y_true, y_pred): y_true = tf.cast(y_true, tf.float32) y_pred = tf.cast(y_pred, tf.float32) bce_loss = tf.keras.losses.binary_crossentropy(y_true, y_pred) smooth = 1e-5 intersection = tf.reduce_sum(y_true * y_pred) union = tf.reduce_sum(y_true) + tf.reduce_sum(y_pred) dice_loss = 1.0 - 2.0 * (intersection + smooth) / (union + smooth) segmentation_loss = bce_loss + 1 * dice_loss return segmentation_loss def train_model(model, X_train, y_train_class, y_train_seg, X_val, y_val_class, y_val_seg, batch_size, epochs): checkpoint = ModelCheckpoint( "multitask_best_weights.h5", monitor="val_classification_output_accuracy", save_best_only=True, mode="max", verbose=1,) reduce_lr = ReduceLROnPlateau( monitor="val_classification_output_accuracy", factor=0.3, patience=2, min_delta=0.001, mode="auto", verbose=1,) tensorboard = TensorBoard(log_dir="logs") model.compile( optimizer=Adam(lr=0.001), loss={"classification_output": "categorical_crossentropy", "segmentation_output": segmentation_loss}, metrics={"classification_output": "accuracy", "segmentation_output": "accuracy"}, loss_weights={"classification_output": 1, "segmentation_output": 1},) history = model.fit( X_train, {"classification_output": y_train_class, "segmentation_output": y_train_seg}, validation_data=(X_val, {"classification_output": y_val_class, "segmentation_output": y_val_seg}), epochs=epochs, verbose=1, batch_size=batch_size, callbacks=[checkpoint, reduce_lr, tensorboard],) return history def evaluate_model(model, X_test, y_test_class, y_test_seg): with tf.keras.utils.custom_object_scope({"segmentation_loss": segmentation_loss}): # Load the best model weights best_model = load_model("multitask_best_weights.h5") # Evaluate the model on test data test_loss, test_class_loss, test_seg_loss, test_class_acc, test_seg_acc = best_model.evaluate( X_test, {"classification_output": y_test_class, "segmentation_output": y_test_seg}) print("Test Classification Loss:", test_class_loss) print("Test Segmentation Loss:", test_seg_loss) print("Test Classification Accuracy:", test_class_acc) print("Test Segmentation Accuracy:", test_seg_acc) # Evaluate the model on validation data val_loss, val_class_loss, val_seg_loss, val_class_acc, val_seg_acc = best_model.evaluate( X_val, {'classification_output': y_val_class, 'segmentation_output': y_val_seg}) print("Validation Classification Loss:", val_class_loss) print("Validation Segmentation Loss:", val_seg_loss) print("Validation Classification Accuracy:", val_class_acc) print("Validation Segmentation Accuracy:", val_seg_acc) # Evaluate the model on training data train_loss, train_class_loss, train_seg_loss, train_class_acc, train_seg_acc = best_model.evaluate(X_train, {'classification_output': y_train_class, 'segmentation_output': y_train_seg}) print("Train Classification Loss:", train_class_loss) print("Train Segmentation Loss:", train_seg_loss) print("Train Classification Accuracy:", train_class_acc) print("Train Segmentation Accuracy:", train_seg_acc) # Return test classification accuracy return test_class_acc def plot_performance(history): # Plot classification accuracy classification_train_accuracy = history.history["classification_output_accuracy"] classification_val_accuracy = history.history["val_classification_output_accuracy"] plt.figure(figsize=(7, 3)) plt.plot(classification_train_accuracy, label="Training Accuracy") plt.plot(classification_val_accuracy, label="Validation Accuracy") plt.title("Classification Accuracy") plt.xlabel("Epochs") plt.ylabel("Accuracy") plt.legend() plt.show() # Plot classification loss classification_train_loss = history.history["classification_output_loss"] classification_val_loss = history.history["val_classification_output_loss"] plt.figure(figsize=(7, 3)) plt.plot(classification_train_loss, "b", label="Training Loss") plt.plot(classification_val_loss, "r", label="Validation Loss") plt.title("Classification Loss") plt.xlabel("Epochs") plt.ylabel("Loss") plt.legend() plt.show() # Plot segmentation accuracy segmentation_train_accuracy = history.history["segmentation_output_accuracy"] segmentation_val_accuracy = history.history["val_segmentation_output_accuracy"] plt.figure(figsize=(7, 3)) plt.plot(segmentation_train_accuracy, label="Training Accuracy") plt.plot(segmentation_val_accuracy, label="Validation Accuracy") plt.title("Segmentation Accuracy") plt.xlabel("Epochs") plt.ylabel("Accuracy") plt.legend() plt.show() # Plot segmentation loss segmentation_train_loss = history.history["segmentation_output_loss"] segmentation_val_loss = history.history["val_segmentation_output_loss"] plt.figure(figsize=(7, 3)) plt.plot(segmentation_train_loss, "b", label="Training Loss") plt.plot(segmentation_val_loss, "r", label="Validation Loss") plt.title("Segmentation Loss") plt.xlabel("Epochs") plt.ylabel("Loss") plt.legend() plt.show() # Set image size image_size = 224 # Define labels labels = ["bridge", "excess", "good"] # Set data folders data_folders = [ "/content/gdrive/MyDrive/Deep learning/FYP_2/4 Dataset Ratio 60 20 20/jit012/jit0/f_dip/train", "/content/gdrive/MyDrive/Deep learning/FYP_2/4 Dataset Ratio 60 20 20/jit012/jit0/f_dip/val", "/content/gdrive/MyDrive/Deep learning/FYP_2/4 Dataset Ratio 60 20 20/jit012/jit0/f_dip/test",] # Load data X_data, y_class_labels, y_seg_labels = load_data(data_folders) # Define train:val:test ratio for each class (ratio x4 = exact) class_data_counts = { "bridge": [40, 80, 80], "excess": [40, 80, 80], "good": [40, 80, 80], } # Split data X_train, y_train_class, y_train_seg, X_val, y_val_class, y_val_seg, X_test, y_test_class, y_test_seg = split_data( X_data, y_class_labels, y_seg_labels, class_data_counts) ''' print("Number of train images:", len(X_train)) print("Number of train binary masks:", len(y_train_seg)) print("Number of validation images:", len(X_val)) print("Number of validation binary masks:", len(y_val_seg)) print("Number of test images:", len(X_test)) print("Number of test binary masks:", len(y_test_seg)) ''' # Initialize the label encoder label_encoder = LabelEncoder() label_encoder.fit(y_class_labels) # Count the number of images of each class in the train, validation, and test sets train_counts = count_labels(y_train_class, label_encoder) val_counts = count_labels(y_val_class, label_encoder) test_counts = count_labels(y_test_class, label_encoder) print("Train counts: ", train_counts," Total in train set:", sum(train_counts.values())) print("Validation counts:", val_counts, " Total in validation set:", sum(val_counts.values())) print("Test counts: ", test_counts," Total in test set:", sum(test_counts.values())) # Build model input_shape = (image_size, image_size, 3) num_classes = len(labels) model = build_model(input_shape, num_classes) model.summary() # Train model n times test_class_acc_list = [] for i in range(5): print(f"\nTrain {i+1}:\n") model = build_model(input_shape, num_classes) batch_size = 16 epochs = 50 history = train_model(model, X_train, y_train_class, y_train_seg, X_val, y_val_class, y_val_seg, batch_size, epochs) # Evaluate model on test data test_class_acc = evaluate_model(model, X_test, y_test_class, y_test_seg) plot_performance(history) test_class_acc_list.append(test_class_acc) # Calculate average test classification accuracy average_test_class_acc = sum(test_class_acc_list) / len(test_class_acc_list) print("Test Classification Accuracy List:", test_class_acc_list) print("Average Test Classification Accuracy:", average_test_class_acc) " The above is the Python code with Keras to do multi-task learning with binary segmentation and classification using one mult-task learning model. I train the model 5 times and take the average accuracy. Modify the code to change the model to resnet50 (from keras library), so no need to perform segmentation, only perform classification. Do not modify the other part of my code. Show full code.
a915281280ff0f5211a09bf368203d15
{ "intermediate": 0.3006076216697693, "beginner": 0.3237382769584656, "expert": 0.3756541907787323 }
42,752
You are a Python expert who can provide clear, concise, high-quality code. " import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns import cv2 import random import tensorflow as tf import tkinter as tk from tkinter import filedialog from PIL import ImageTk, Image from ipywidgets import interact, interactive, fixed, interact_manual import ipywidgets as widgets from IPython.display import display, clear_output from tensorflow.keras.preprocessing import image from tensorflow.keras.optimizers import Adam, SGD, RMSprop, AdamW, Adadelta, Adagrad, Adamax, Adafactor, Nadam, Ftrl from tensorflow.keras.preprocessing.image import ImageDataGenerator from tqdm import tqdm import os from sklearn.utils import shuffle from sklearn.preprocessing import LabelEncoder from sklearn.model_selection import train_test_split from tensorflow.keras.models import Sequential, Model, load_model from tensorflow.keras.layers import ( GlobalAveragePooling2D, Dropout, Dense, Conv2D, MaxPooling2D, Flatten, Dropout, BatchNormalization, Activation, concatenate, Conv2DTranspose, Input, Reshape, UpSampling2D, ) from tensorflow.keras.applications import ( EfficientNetV2B0, EfficientNetV2B1, EfficientNetV2B2, EfficientNetV2B3, EfficientNetV2L, EfficientNetV2M, EfficientNetV2S, ) from tensorflow.keras.applications import Xception from tensorflow.keras.applications import VGG16, VGG19 from tensorflow.keras.applications import ResNet50, ResNet101, ResNet152, ResNetRS50, ResNetRS101 from tensorflow.keras.applications import InceptionResNetV2, ConvNeXtXLarge, ConvNeXtBase, DenseNet121, MobileNetV2, NASNetLarge, NASNetMobile from tensorflow.keras.utils import to_categorical from tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau, TensorBoard, ModelCheckpoint from sklearn.metrics import classification_report, confusion_matrix import ipywidgets as widgets import io from PIL import Image from IPython.display import display, clear_output from warnings import filterwarnings from google.colab import drive drive.mount("/content/gdrive") def load_data(data_folders): X_data = [] # Combined data y_class_labels = [] # Combined classification labels y_seg_labels = [] # Combined segmentation labels for folderPath in data_folders: for label in labels: label_folder_path = os.path.join(folderPath, label) for filename in tqdm(os.listdir(label_folder_path)): if filename.endswith(".jpg"): img = cv2.imread(os.path.join(label_folder_path, filename)) img = cv2.resize(img, (image_size, image_size)) X_data.append(img) y_class_labels.append(label) seg_filename = filename.split(".")[0] + ".png" seg_img = cv2.imread(os.path.join(label_folder_path, seg_filename), 0) seg_img = cv2.resize(seg_img, (image_size, image_size)) seg_img = np.where(seg_img > 0, 1, 0) # Convert segmentation mask to binary y_seg_labels.append(seg_img) X_data = np.array(X_data) y_class_labels = np.array(y_class_labels) y_seg_labels = np.array(y_seg_labels) X_data, y_class_labels, y_seg_labels = shuffle(X_data, y_class_labels, y_seg_labels, random_state=101) return X_data, y_class_labels, y_seg_labels def split_data(X_data, y_class_labels, y_seg_labels, class_data_counts): X_train = [] y_train_class = [] y_train_seg = [] X_val = [] y_val_class = [] y_val_seg = [] X_test = [] y_test_class = [] y_test_seg = [] for label, count in class_data_counts.items(): label_indices = np.where(y_class_labels == label)[0] class_X_data = X_data[label_indices] class_y_class_labels = y_class_labels[label_indices] class_y_seg_labels = y_seg_labels[label_indices] train_count = count[0] val_count = count[1] test_count = count[2] class_X_train = class_X_data[:train_count] class_y_train_class = class_y_class_labels[:train_count] class_y_train_seg = class_y_seg_labels[:train_count] class_X_val = class_X_data[train_count: train_count + val_count] class_y_val_class = class_y_class_labels[train_count: train_count + val_count] class_y_val_seg = class_y_seg_labels[train_count: train_count + val_count] class_X_test = class_X_data[train_count + val_count: train_count + val_count + test_count] class_y_test_class = class_y_class_labels[train_count + val_count: train_count + val_count + test_count] class_y_test_seg = class_y_seg_labels[train_count + val_count: train_count + val_count + test_count] X_train.extend(class_X_train) y_train_class.extend(class_y_train_class) y_train_seg.extend(class_y_train_seg) X_val.extend(class_X_val) y_val_class.extend(class_y_val_class) y_val_seg.extend(class_y_val_seg) X_test.extend(class_X_test) y_test_class.extend(class_y_test_class) y_test_seg.extend(class_y_test_seg) # Convert class labels to categorical label_encoder = LabelEncoder() y_train_class_encoded = label_encoder.fit_transform(y_train_class) y_train_class_categorical = to_categorical(y_train_class_encoded) y_val_class_encoded = label_encoder.transform(y_val_class) y_val_class_categorical = to_categorical(y_val_class_encoded) y_test_class_encoded = label_encoder.transform(y_test_class) y_test_class_categorical = to_categorical(y_test_class_encoded) return ( np.array(X_train), np.array(y_train_class_categorical), np.array(y_train_seg), np.array(X_val), np.array(y_val_class_categorical), np.array(y_val_seg), np.array(X_test), np.array(y_test_class_categorical), np.array(y_test_seg), ) def count_labels(y_class_categorical, label_encoder): # Convert one-hot encoded labels back to label encoded y_class_labels = np.argmax(y_class_categorical, axis=1) # Convert label encoded labels back to original class names y_class_names = label_encoder.inverse_transform(y_class_labels) unique, counts = np.unique(y_class_names, return_counts=True) return dict(zip(unique, counts)) def build_model(input_shape, num_classes): num_filter = 32 # 16/32 best, 8: best classification but no segment # Encoder (Done) inputs = Input(input_shape) conv1 = Conv2D(num_filter * 1, 3, activation="linear", padding="same", strides=1)(inputs) bn1 = BatchNormalization()(conv1) relu1 = Activation("relu")(bn1) conv2 = Conv2D(num_filter * 1, 3, activation="linear", padding="same", strides=1)(relu1) bn2 = BatchNormalization()(conv2) relu2 = Activation("relu")(bn2) down1 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu2) conv3 = Conv2D(num_filter * 2, 3, activation="linear", padding="same", strides=1)(down1) bn3 = BatchNormalization()(conv3) relu3 = Activation("relu")(bn3) conv4 = Conv2D(num_filter * 2, 3, activation="linear", padding="same", strides=1)(relu3) bn4 = BatchNormalization()(conv4) relu4 = Activation("relu")(bn4) down2 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu4) conv5 = Conv2D(num_filter * 4, 3, activation="linear", padding="same", strides=1)(down2) bn5 = BatchNormalization()(conv5) relu5 = Activation("relu")(bn5) conv6 = Conv2D(num_filter * 4, 3, activation="linear", padding="same", strides=1)(relu5) bn6 = BatchNormalization()(conv6) relu6 = Activation("relu")(bn6) down3 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu6) conv7 = Conv2D(num_filter * 8, 3, activation="linear", padding="same", strides=1)(down3) bn7 = BatchNormalization()(conv7) relu7 = Activation("relu")(bn7) conv8 = Conv2D(num_filter * 8, 3, activation="linear", padding="same", strides=1)(relu7) bn8 = BatchNormalization()(conv8) relu8 = Activation("relu")(bn8) # Middle down4 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu8) conv9 = Conv2D(num_filter * 16, 3, activation="linear", padding="same", strides=1)(down4) bn9 = BatchNormalization()(conv9) relu9 = Activation("relu")(bn9) conv10 = Conv2D(num_filter * 16, 3, activation="linear", padding="same", strides=1)(relu9) bn10 = BatchNormalization()(conv10) relu10 = Activation("relu")(bn10) up1 = UpSampling2D(size=(2, 2), interpolation="bilinear")(relu10) # Decoder (Done) concat1 = concatenate([up1, relu8], axis=-1) # , axis=3 conv11 = Conv2D(num_filter * 8, 3, activation="linear", padding="same", strides=1)(concat1) bn11 = BatchNormalization()(conv11) relu11 = Activation("relu")(bn11) conv12 = Conv2D(num_filter * 8, 3, activation="linear", padding="same", strides=1)(relu11) bn12 = BatchNormalization()(conv12) relu12 = Activation("relu")(bn12) up2 = UpSampling2D(size=(2, 2), interpolation="bilinear")(relu12) concat2 = concatenate([up2, relu6], axis=-1) # , axis=3 conv13 = Conv2D(num_filter * 4, 3, activation="linear", padding="same", strides=1)(concat2) bn13 = BatchNormalization()(conv13) relu13 = Activation("relu")(bn13) conv14 = Conv2D(num_filter * 4, 3, activation="linear", padding="same", strides=1)(relu13) bn14 = BatchNormalization()(conv14) relu14 = Activation("relu")(bn14) up3 = UpSampling2D(size=(2, 2), interpolation="bilinear")(relu14) concat3 = concatenate([up3, relu4], axis=-1) # , axis=3 conv15 = Conv2D(num_filter * 2, 3, activation="linear", padding="same", strides=1)(concat3) bn15 = BatchNormalization()(conv15) relu15 = Activation("relu")(bn15) conv16 = Conv2D(num_filter * 2, 3, activation="linear", padding="same", strides=1)(relu15) bn16 = BatchNormalization()(conv16) relu16 = Activation("relu")(bn16) up4 = UpSampling2D(size=(2, 2), interpolation="bilinear")(relu16) concat4 = concatenate([up4, relu2], axis=-1) # , axis=3 conv17 = Conv2D(num_filter * 1, 3, activation="linear", padding="same", strides=1)(concat4) bn17 = BatchNormalization()(conv17) relu17 = Activation("relu")(bn17) conv18 = Conv2D(num_filter * 1, 3, activation="linear", padding="same", strides=1)(relu17) bn18 = BatchNormalization()(conv18) relu18 = Activation("relu")(bn18) # Segmentation branch segmentation_output = Conv2D(1, 1, activation="sigmoid", name="segmentation_output")(relu18) # original # Classification branch (Not done) gap1 = GlobalAveragePooling2D()(relu8) gap2 = GlobalAveragePooling2D()(relu10) gap3 = GlobalAveragePooling2D()(relu12) conv20 = Conv2D(16, 3, activation="linear", padding="same", strides=1)(segmentation_output) bn20 = BatchNormalization()(conv20) relu20 = Activation("relu")(bn20) down5 = MaxPooling2D(pool_size=(4, 4), strides=4)(relu20) conv21 = Conv2D(32, 3, activation="linear", padding="same", strides=1)(down5) bn21 = BatchNormalization()(conv21) relu21 = Activation("relu")(bn21) down6 = MaxPooling2D(pool_size=(4, 4), strides=4)(relu21) conv22 = Conv2D(64, 3, activation="linear", padding="same", strides=1)(down6) bn22 = BatchNormalization()(conv22) relu22 = Activation("relu")(bn22) down7 = MaxPooling2D(pool_size=(4, 4), strides=4)(relu22) flatten1 = Flatten()(down7) concat5 = concatenate([gap1, gap2, gap3, flatten1], axis=-1) # FC layers fc1 = Dense(1024, activation="relu")(concat5) dropout1 = Dropout(0.5)(fc1) fc2 = Dense(1024, activation="relu")(dropout1) dropout2 = Dropout(0.5)(fc2) classification_output = Dense(num_classes, activation="softmax", name="classification_output")(dropout2) # Define the model model = Model(inputs=inputs, outputs=[classification_output, segmentation_output]) return model def segmentation_loss(y_true, y_pred): y_true = tf.cast(y_true, tf.float32) y_pred = tf.cast(y_pred, tf.float32) bce_loss = tf.keras.losses.binary_crossentropy(y_true, y_pred) smooth = 1e-5 intersection = tf.reduce_sum(y_true * y_pred) union = tf.reduce_sum(y_true) + tf.reduce_sum(y_pred) dice_loss = 1.0 - 2.0 * (intersection + smooth) / (union + smooth) segmentation_loss = bce_loss + 1 * dice_loss return segmentation_loss def train_model(model, X_train, y_train_class, y_train_seg, X_val, y_val_class, y_val_seg, batch_size, epochs): checkpoint = ModelCheckpoint( "multitask_best_weights.h5", monitor="val_classification_output_accuracy", save_best_only=True, mode="max", verbose=1,) reduce_lr = ReduceLROnPlateau( monitor="val_classification_output_accuracy", factor=0.3, patience=2, min_delta=0.001, mode="auto", verbose=1,) tensorboard = TensorBoard(log_dir="logs") model.compile( optimizer=Adam(lr=0.001), loss={"classification_output": "categorical_crossentropy", "segmentation_output": segmentation_loss}, metrics={"classification_output": "accuracy", "segmentation_output": "accuracy"}, loss_weights={"classification_output": 1, "segmentation_output": 1},) history = model.fit( X_train, {"classification_output": y_train_class, "segmentation_output": y_train_seg}, validation_data=(X_val, {"classification_output": y_val_class, "segmentation_output": y_val_seg}), epochs=epochs, verbose=1, batch_size=batch_size, callbacks=[checkpoint, reduce_lr, tensorboard],) return history def evaluate_model(model, X_test, y_test_class, y_test_seg): with tf.keras.utils.custom_object_scope({"segmentation_loss": segmentation_loss}): # Load the best model weights best_model = load_model("multitask_best_weights.h5") # Evaluate the model on test data test_loss, test_class_loss, test_seg_loss, test_class_acc, test_seg_acc = best_model.evaluate( X_test, {"classification_output": y_test_class, "segmentation_output": y_test_seg}) print("Test Classification Loss:", test_class_loss) print("Test Segmentation Loss:", test_seg_loss) print("Test Classification Accuracy:", test_class_acc) print("Test Segmentation Accuracy:", test_seg_acc) # Evaluate the model on validation data val_loss, val_class_loss, val_seg_loss, val_class_acc, val_seg_acc = best_model.evaluate( X_val, {'classification_output': y_val_class, 'segmentation_output': y_val_seg}) print("Validation Classification Loss:", val_class_loss) print("Validation Segmentation Loss:", val_seg_loss) print("Validation Classification Accuracy:", val_class_acc) print("Validation Segmentation Accuracy:", val_seg_acc) # Evaluate the model on training data train_loss, train_class_loss, train_seg_loss, train_class_acc, train_seg_acc = best_model.evaluate(X_train, {'classification_output': y_train_class, 'segmentation_output': y_train_seg}) print("Train Classification Loss:", train_class_loss) print("Train Segmentation Loss:", train_seg_loss) print("Train Classification Accuracy:", train_class_acc) print("Train Segmentation Accuracy:", train_seg_acc) # Return test classification accuracy return test_class_acc def plot_performance(history): # Plot classification accuracy classification_train_accuracy = history.history["classification_output_accuracy"] classification_val_accuracy = history.history["val_classification_output_accuracy"] plt.figure(figsize=(7, 3)) plt.plot(classification_train_accuracy, label="Training Accuracy") plt.plot(classification_val_accuracy, label="Validation Accuracy") plt.title("Classification Accuracy") plt.xlabel("Epochs") plt.ylabel("Accuracy") plt.legend() plt.show() # Plot classification loss classification_train_loss = history.history["classification_output_loss"] classification_val_loss = history.history["val_classification_output_loss"] plt.figure(figsize=(7, 3)) plt.plot(classification_train_loss, "b", label="Training Loss") plt.plot(classification_val_loss, "r", label="Validation Loss") plt.title("Classification Loss") plt.xlabel("Epochs") plt.ylabel("Loss") plt.legend() plt.show() # Plot segmentation accuracy segmentation_train_accuracy = history.history["segmentation_output_accuracy"] segmentation_val_accuracy = history.history["val_segmentation_output_accuracy"] plt.figure(figsize=(7, 3)) plt.plot(segmentation_train_accuracy, label="Training Accuracy") plt.plot(segmentation_val_accuracy, label="Validation Accuracy") plt.title("Segmentation Accuracy") plt.xlabel("Epochs") plt.ylabel("Accuracy") plt.legend() plt.show() # Plot segmentation loss segmentation_train_loss = history.history["segmentation_output_loss"] segmentation_val_loss = history.history["val_segmentation_output_loss"] plt.figure(figsize=(7, 3)) plt.plot(segmentation_train_loss, "b", label="Training Loss") plt.plot(segmentation_val_loss, "r", label="Validation Loss") plt.title("Segmentation Loss") plt.xlabel("Epochs") plt.ylabel("Loss") plt.legend() plt.show() # Set image size image_size = 224 # Define labels labels = ["bridge", "excess", "good"] # Set data folders data_folders = [ "/content/gdrive/MyDrive/Deep learning/FYP_2/4 Dataset Ratio 60 20 20/jit012/jit0/f_dip/train", "/content/gdrive/MyDrive/Deep learning/FYP_2/4 Dataset Ratio 60 20 20/jit012/jit0/f_dip/val", "/content/gdrive/MyDrive/Deep learning/FYP_2/4 Dataset Ratio 60 20 20/jit012/jit0/f_dip/test",] # Load data X_data, y_class_labels, y_seg_labels = load_data(data_folders) # Define train:val:test ratio for each class (ratio x4 = exact) class_data_counts = { "bridge": [40, 80, 80], "excess": [40, 80, 80], "good": [40, 80, 80], } # Split data X_train, y_train_class, y_train_seg, X_val, y_val_class, y_val_seg, X_test, y_test_class, y_test_seg = split_data( X_data, y_class_labels, y_seg_labels, class_data_counts) ''' print("Number of train images:", len(X_train)) print("Number of train binary masks:", len(y_train_seg)) print("Number of validation images:", len(X_val)) print("Number of validation binary masks:", len(y_val_seg)) print("Number of test images:", len(X_test)) print("Number of test binary masks:", len(y_test_seg)) ''' # Initialize the label encoder label_encoder = LabelEncoder() label_encoder.fit(y_class_labels) # Count the number of images of each class in the train, validation, and test sets train_counts = count_labels(y_train_class, label_encoder) val_counts = count_labels(y_val_class, label_encoder) test_counts = count_labels(y_test_class, label_encoder) print("Train counts: ", train_counts," Total in train set:", sum(train_counts.values())) print("Validation counts:", val_counts, " Total in validation set:", sum(val_counts.values())) print("Test counts: ", test_counts," Total in test set:", sum(test_counts.values())) # Build model input_shape = (image_size, image_size, 3) num_classes = len(labels) model = build_model(input_shape, num_classes) model.summary() # Train model n times test_class_acc_list = [] for i in range(5): print(f"\nTrain {i+1}:\n") model = build_model(input_shape, num_classes) batch_size = 16 epochs = 50 history = train_model(model, X_train, y_train_class, y_train_seg, X_val, y_val_class, y_val_seg, batch_size, epochs) # Evaluate model on test data test_class_acc = evaluate_model(model, X_test, y_test_class, y_test_seg) plot_performance(history) test_class_acc_list.append(test_class_acc) # Calculate average test classification accuracy average_test_class_acc = sum(test_class_acc_list) / len(test_class_acc_list) print("Test Classification Accuracy List:", test_class_acc_list) print("Average Test Classification Accuracy:", average_test_class_acc) " The above is the Python code with Keras to do multi-task learning with binary segmentation and classification using one mult-task learning model. I train the model 5 times and take the average accuracy. Modify the code to change the model to resnet50 (from keras library), so no need to perform segmentation, only perform classification. Do not modify the other part of my code. Show full code.
7b05b9ad1d00796f3843f476e471bc47
{ "intermediate": 0.3006076216697693, "beginner": 0.3237382769584656, "expert": 0.3756541907787323 }
42,753
You are a Python expert who can provide clear, concise, high-quality code. " import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns import cv2 import random import tensorflow as tf import tkinter as tk from tkinter import filedialog from PIL import ImageTk, Image from ipywidgets import interact, interactive, fixed, interact_manual import ipywidgets as widgets from IPython.display import display, clear_output from tensorflow.keras.preprocessing import image from tensorflow.keras.optimizers import Adam, SGD, RMSprop, AdamW, Adadelta, Adagrad, Adamax, Adafactor, Nadam, Ftrl from tensorflow.keras.preprocessing.image import ImageDataGenerator from tqdm import tqdm import os from sklearn.utils import shuffle from sklearn.preprocessing import LabelEncoder from sklearn.model_selection import train_test_split from tensorflow.keras.models import Sequential, Model, load_model from tensorflow.keras.layers import ( GlobalAveragePooling2D, Dropout, Dense, Conv2D, MaxPooling2D, Flatten, Dropout, BatchNormalization, Activation, concatenate, Conv2DTranspose, Input, Reshape, UpSampling2D, ) from tensorflow.keras.applications import ( EfficientNetV2B0, EfficientNetV2B1, EfficientNetV2B2, EfficientNetV2B3, EfficientNetV2L, EfficientNetV2M, EfficientNetV2S, ) from tensorflow.keras.applications import Xception from tensorflow.keras.applications import VGG16, VGG19 from tensorflow.keras.applications import ResNet50, ResNet101, ResNet152, ResNetRS50, ResNetRS101 from tensorflow.keras.applications import InceptionResNetV2, ConvNeXtXLarge, ConvNeXtBase, DenseNet121, MobileNetV2, NASNetLarge, NASNetMobile from tensorflow.keras.utils import to_categorical from tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau, TensorBoard, ModelCheckpoint from sklearn.metrics import classification_report, confusion_matrix import ipywidgets as widgets import io from PIL import Image from IPython.display import display, clear_output from warnings import filterwarnings from google.colab import drive drive.mount("/content/gdrive") def load_data(data_folders): X_data = [] # Combined data y_class_labels = [] # Combined classification labels y_seg_labels = [] # Combined segmentation labels for folderPath in data_folders: for label in labels: label_folder_path = os.path.join(folderPath, label) for filename in tqdm(os.listdir(label_folder_path)): if filename.endswith(".jpg"): img = cv2.imread(os.path.join(label_folder_path, filename)) img = cv2.resize(img, (image_size, image_size)) X_data.append(img) y_class_labels.append(label) seg_filename = filename.split(".")[0] + ".png" seg_img = cv2.imread(os.path.join(label_folder_path, seg_filename), 0) seg_img = cv2.resize(seg_img, (image_size, image_size)) seg_img = np.where(seg_img > 0, 1, 0) # Convert segmentation mask to binary y_seg_labels.append(seg_img) X_data = np.array(X_data) y_class_labels = np.array(y_class_labels) y_seg_labels = np.array(y_seg_labels) X_data, y_class_labels, y_seg_labels = shuffle(X_data, y_class_labels, y_seg_labels, random_state=101) return X_data, y_class_labels, y_seg_labels def split_data(X_data, y_class_labels, y_seg_labels, class_data_counts): X_train = [] y_train_class = [] y_train_seg = [] X_val = [] y_val_class = [] y_val_seg = [] X_test = [] y_test_class = [] y_test_seg = [] for label, count in class_data_counts.items(): label_indices = np.where(y_class_labels == label)[0] class_X_data = X_data[label_indices] class_y_class_labels = y_class_labels[label_indices] class_y_seg_labels = y_seg_labels[label_indices] train_count = count[0] val_count = count[1] test_count = count[2] class_X_train = class_X_data[:train_count] class_y_train_class = class_y_class_labels[:train_count] class_y_train_seg = class_y_seg_labels[:train_count] class_X_val = class_X_data[train_count: train_count + val_count] class_y_val_class = class_y_class_labels[train_count: train_count + val_count] class_y_val_seg = class_y_seg_labels[train_count: train_count + val_count] class_X_test = class_X_data[train_count + val_count: train_count + val_count + test_count] class_y_test_class = class_y_class_labels[train_count + val_count: train_count + val_count + test_count] class_y_test_seg = class_y_seg_labels[train_count + val_count: train_count + val_count + test_count] X_train.extend(class_X_train) y_train_class.extend(class_y_train_class) y_train_seg.extend(class_y_train_seg) X_val.extend(class_X_val) y_val_class.extend(class_y_val_class) y_val_seg.extend(class_y_val_seg) X_test.extend(class_X_test) y_test_class.extend(class_y_test_class) y_test_seg.extend(class_y_test_seg) # Convert class labels to categorical label_encoder = LabelEncoder() y_train_class_encoded = label_encoder.fit_transform(y_train_class) y_train_class_categorical = to_categorical(y_train_class_encoded) y_val_class_encoded = label_encoder.transform(y_val_class) y_val_class_categorical = to_categorical(y_val_class_encoded) y_test_class_encoded = label_encoder.transform(y_test_class) y_test_class_categorical = to_categorical(y_test_class_encoded) return ( np.array(X_train), np.array(y_train_class_categorical), np.array(y_train_seg), np.array(X_val), np.array(y_val_class_categorical), np.array(y_val_seg), np.array(X_test), np.array(y_test_class_categorical), np.array(y_test_seg), ) def count_labels(y_class_categorical, label_encoder): # Convert one-hot encoded labels back to label encoded y_class_labels = np.argmax(y_class_categorical, axis=1) # Convert label encoded labels back to original class names y_class_names = label_encoder.inverse_transform(y_class_labels) unique, counts = np.unique(y_class_names, return_counts=True) return dict(zip(unique, counts)) def build_model(input_shape, num_classes): num_filter = 32 # 16/32 best, 8: best classification but no segment # Encoder (Done) inputs = Input(input_shape) conv1 = Conv2D(num_filter * 1, 3, activation="linear", padding="same", strides=1)(inputs) bn1 = BatchNormalization()(conv1) relu1 = Activation("relu")(bn1) conv2 = Conv2D(num_filter * 1, 3, activation="linear", padding="same", strides=1)(relu1) bn2 = BatchNormalization()(conv2) relu2 = Activation("relu")(bn2) down1 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu2) conv3 = Conv2D(num_filter * 2, 3, activation="linear", padding="same", strides=1)(down1) bn3 = BatchNormalization()(conv3) relu3 = Activation("relu")(bn3) conv4 = Conv2D(num_filter * 2, 3, activation="linear", padding="same", strides=1)(relu3) bn4 = BatchNormalization()(conv4) relu4 = Activation("relu")(bn4) down2 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu4) conv5 = Conv2D(num_filter * 4, 3, activation="linear", padding="same", strides=1)(down2) bn5 = BatchNormalization()(conv5) relu5 = Activation("relu")(bn5) conv6 = Conv2D(num_filter * 4, 3, activation="linear", padding="same", strides=1)(relu5) bn6 = BatchNormalization()(conv6) relu6 = Activation("relu")(bn6) down3 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu6) conv7 = Conv2D(num_filter * 8, 3, activation="linear", padding="same", strides=1)(down3) bn7 = BatchNormalization()(conv7) relu7 = Activation("relu")(bn7) conv8 = Conv2D(num_filter * 8, 3, activation="linear", padding="same", strides=1)(relu7) bn8 = BatchNormalization()(conv8) relu8 = Activation("relu")(bn8) # Middle down4 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu8) conv9 = Conv2D(num_filter * 16, 3, activation="linear", padding="same", strides=1)(down4) bn9 = BatchNormalization()(conv9) relu9 = Activation("relu")(bn9) conv10 = Conv2D(num_filter * 16, 3, activation="linear", padding="same", strides=1)(relu9) bn10 = BatchNormalization()(conv10) relu10 = Activation("relu")(bn10) up1 = UpSampling2D(size=(2, 2), interpolation="bilinear")(relu10) # Decoder (Done) concat1 = concatenate([up1, relu8], axis=-1) # , axis=3 conv11 = Conv2D(num_filter * 8, 3, activation="linear", padding="same", strides=1)(concat1) bn11 = BatchNormalization()(conv11) relu11 = Activation("relu")(bn11) conv12 = Conv2D(num_filter * 8, 3, activation="linear", padding="same", strides=1)(relu11) bn12 = BatchNormalization()(conv12) relu12 = Activation("relu")(bn12) up2 = UpSampling2D(size=(2, 2), interpolation="bilinear")(relu12) concat2 = concatenate([up2, relu6], axis=-1) # , axis=3 conv13 = Conv2D(num_filter * 4, 3, activation="linear", padding="same", strides=1)(concat2) bn13 = BatchNormalization()(conv13) relu13 = Activation("relu")(bn13) conv14 = Conv2D(num_filter * 4, 3, activation="linear", padding="same", strides=1)(relu13) bn14 = BatchNormalization()(conv14) relu14 = Activation("relu")(bn14) up3 = UpSampling2D(size=(2, 2), interpolation="bilinear")(relu14) concat3 = concatenate([up3, relu4], axis=-1) # , axis=3 conv15 = Conv2D(num_filter * 2, 3, activation="linear", padding="same", strides=1)(concat3) bn15 = BatchNormalization()(conv15) relu15 = Activation("relu")(bn15) conv16 = Conv2D(num_filter * 2, 3, activation="linear", padding="same", strides=1)(relu15) bn16 = BatchNormalization()(conv16) relu16 = Activation("relu")(bn16) up4 = UpSampling2D(size=(2, 2), interpolation="bilinear")(relu16) concat4 = concatenate([up4, relu2], axis=-1) # , axis=3 conv17 = Conv2D(num_filter * 1, 3, activation="linear", padding="same", strides=1)(concat4) bn17 = BatchNormalization()(conv17) relu17 = Activation("relu")(bn17) conv18 = Conv2D(num_filter * 1, 3, activation="linear", padding="same", strides=1)(relu17) bn18 = BatchNormalization()(conv18) relu18 = Activation("relu")(bn18) # Segmentation branch segmentation_output = Conv2D(1, 1, activation="sigmoid", name="segmentation_output")(relu18) # original # Classification branch (Not done) gap1 = GlobalAveragePooling2D()(relu8) gap2 = GlobalAveragePooling2D()(relu10) gap3 = GlobalAveragePooling2D()(relu12) conv20 = Conv2D(16, 3, activation="linear", padding="same", strides=1)(segmentation_output) bn20 = BatchNormalization()(conv20) relu20 = Activation("relu")(bn20) down5 = MaxPooling2D(pool_size=(4, 4), strides=4)(relu20) conv21 = Conv2D(32, 3, activation="linear", padding="same", strides=1)(down5) bn21 = BatchNormalization()(conv21) relu21 = Activation("relu")(bn21) down6 = MaxPooling2D(pool_size=(4, 4), strides=4)(relu21) conv22 = Conv2D(64, 3, activation="linear", padding="same", strides=1)(down6) bn22 = BatchNormalization()(conv22) relu22 = Activation("relu")(bn22) down7 = MaxPooling2D(pool_size=(4, 4), strides=4)(relu22) flatten1 = Flatten()(down7) concat5 = concatenate([gap1, gap2, gap3, flatten1], axis=-1) # FC layers fc1 = Dense(1024, activation="relu")(concat5) dropout1 = Dropout(0.5)(fc1) fc2 = Dense(1024, activation="relu")(dropout1) dropout2 = Dropout(0.5)(fc2) classification_output = Dense(num_classes, activation="softmax", name="classification_output")(dropout2) # Define the model model = Model(inputs=inputs, outputs=[classification_output, segmentation_output]) return model def segmentation_loss(y_true, y_pred): y_true = tf.cast(y_true, tf.float32) y_pred = tf.cast(y_pred, tf.float32) bce_loss = tf.keras.losses.binary_crossentropy(y_true, y_pred) smooth = 1e-5 intersection = tf.reduce_sum(y_true * y_pred) union = tf.reduce_sum(y_true) + tf.reduce_sum(y_pred) dice_loss = 1.0 - 2.0 * (intersection + smooth) / (union + smooth) segmentation_loss = bce_loss + 1 * dice_loss return segmentation_loss def train_model(model, X_train, y_train_class, y_train_seg, X_val, y_val_class, y_val_seg, batch_size, epochs): checkpoint = ModelCheckpoint( "multitask_best_weights.h5", monitor="val_classification_output_accuracy", save_best_only=True, mode="max", verbose=1,) reduce_lr = ReduceLROnPlateau( monitor="val_classification_output_accuracy", factor=0.3, patience=2, min_delta=0.001, mode="auto", verbose=1,) tensorboard = TensorBoard(log_dir="logs") model.compile( optimizer=Adam(lr=0.001), loss={"classification_output": "categorical_crossentropy", "segmentation_output": segmentation_loss}, metrics={"classification_output": "accuracy", "segmentation_output": "accuracy"}, loss_weights={"classification_output": 1, "segmentation_output": 1},) history = model.fit( X_train, {"classification_output": y_train_class, "segmentation_output": y_train_seg}, validation_data=(X_val, {"classification_output": y_val_class, "segmentation_output": y_val_seg}), epochs=epochs, verbose=1, batch_size=batch_size, callbacks=[checkpoint, reduce_lr, tensorboard],) return history def evaluate_model(model, X_test, y_test_class, y_test_seg): with tf.keras.utils.custom_object_scope({"segmentation_loss": segmentation_loss}): # Load the best model weights best_model = load_model("multitask_best_weights.h5") # Evaluate the model on test data test_loss, test_class_loss, test_seg_loss, test_class_acc, test_seg_acc = best_model.evaluate( X_test, {"classification_output": y_test_class, "segmentation_output": y_test_seg}) print("Test Classification Loss:", test_class_loss) print("Test Segmentation Loss:", test_seg_loss) print("Test Classification Accuracy:", test_class_acc) print("Test Segmentation Accuracy:", test_seg_acc) # Evaluate the model on validation data val_loss, val_class_loss, val_seg_loss, val_class_acc, val_seg_acc = best_model.evaluate( X_val, {'classification_output': y_val_class, 'segmentation_output': y_val_seg}) print("Validation Classification Loss:", val_class_loss) print("Validation Segmentation Loss:", val_seg_loss) print("Validation Classification Accuracy:", val_class_acc) print("Validation Segmentation Accuracy:", val_seg_acc) # Evaluate the model on training data train_loss, train_class_loss, train_seg_loss, train_class_acc, train_seg_acc = best_model.evaluate(X_train, {'classification_output': y_train_class, 'segmentation_output': y_train_seg}) print("Train Classification Loss:", train_class_loss) print("Train Segmentation Loss:", train_seg_loss) print("Train Classification Accuracy:", train_class_acc) print("Train Segmentation Accuracy:", train_seg_acc) # Return test classification accuracy return test_class_acc def plot_performance(history): # Plot classification accuracy classification_train_accuracy = history.history["classification_output_accuracy"] classification_val_accuracy = history.history["val_classification_output_accuracy"] plt.figure(figsize=(7, 3)) plt.plot(classification_train_accuracy, label="Training Accuracy") plt.plot(classification_val_accuracy, label="Validation Accuracy") plt.title("Classification Accuracy") plt.xlabel("Epochs") plt.ylabel("Accuracy") plt.legend() plt.show() # Plot classification loss classification_train_loss = history.history["classification_output_loss"] classification_val_loss = history.history["val_classification_output_loss"] plt.figure(figsize=(7, 3)) plt.plot(classification_train_loss, "b", label="Training Loss") plt.plot(classification_val_loss, "r", label="Validation Loss") plt.title("Classification Loss") plt.xlabel("Epochs") plt.ylabel("Loss") plt.legend() plt.show() # Plot segmentation accuracy segmentation_train_accuracy = history.history["segmentation_output_accuracy"] segmentation_val_accuracy = history.history["val_segmentation_output_accuracy"] plt.figure(figsize=(7, 3)) plt.plot(segmentation_train_accuracy, label="Training Accuracy") plt.plot(segmentation_val_accuracy, label="Validation Accuracy") plt.title("Segmentation Accuracy") plt.xlabel("Epochs") plt.ylabel("Accuracy") plt.legend() plt.show() # Plot segmentation loss segmentation_train_loss = history.history["segmentation_output_loss"] segmentation_val_loss = history.history["val_segmentation_output_loss"] plt.figure(figsize=(7, 3)) plt.plot(segmentation_train_loss, "b", label="Training Loss") plt.plot(segmentation_val_loss, "r", label="Validation Loss") plt.title("Segmentation Loss") plt.xlabel("Epochs") plt.ylabel("Loss") plt.legend() plt.show() # Set image size image_size = 224 # Define labels labels = ["bridge", "excess", "good"] # Set data folders data_folders = [ "/content/gdrive/MyDrive/Deep learning/FYP_2/4 Dataset Ratio 60 20 20/jit012/jit0/f_dip/train", "/content/gdrive/MyDrive/Deep learning/FYP_2/4 Dataset Ratio 60 20 20/jit012/jit0/f_dip/val", "/content/gdrive/MyDrive/Deep learning/FYP_2/4 Dataset Ratio 60 20 20/jit012/jit0/f_dip/test",] # Load data X_data, y_class_labels, y_seg_labels = load_data(data_folders) # Define train:val:test ratio for each class (ratio x4 = exact) class_data_counts = { "bridge": [40, 80, 80], "excess": [40, 80, 80], "good": [40, 80, 80], } # Split data X_train, y_train_class, y_train_seg, X_val, y_val_class, y_val_seg, X_test, y_test_class, y_test_seg = split_data( X_data, y_class_labels, y_seg_labels, class_data_counts) ''' print("Number of train images:", len(X_train)) print("Number of train binary masks:", len(y_train_seg)) print("Number of validation images:", len(X_val)) print("Number of validation binary masks:", len(y_val_seg)) print("Number of test images:", len(X_test)) print("Number of test binary masks:", len(y_test_seg)) ''' # Initialize the label encoder label_encoder = LabelEncoder() label_encoder.fit(y_class_labels) # Count the number of images of each class in the train, validation, and test sets train_counts = count_labels(y_train_class, label_encoder) val_counts = count_labels(y_val_class, label_encoder) test_counts = count_labels(y_test_class, label_encoder) print("Train counts: ", train_counts," Total in train set:", sum(train_counts.values())) print("Validation counts:", val_counts, " Total in validation set:", sum(val_counts.values())) print("Test counts: ", test_counts," Total in test set:", sum(test_counts.values())) # Build model input_shape = (image_size, image_size, 3) num_classes = len(labels) model = build_model(input_shape, num_classes) model.summary() # Train model n times test_class_acc_list = [] for i in range(5): print(f"\nTrain {i+1}:\n") model = build_model(input_shape, num_classes) batch_size = 16 epochs = 50 history = train_model(model, X_train, y_train_class, y_train_seg, X_val, y_val_class, y_val_seg, batch_size, epochs) # Evaluate model on test data test_class_acc = evaluate_model(model, X_test, y_test_class, y_test_seg) plot_performance(history) test_class_acc_list.append(test_class_acc) # Calculate average test classification accuracy average_test_class_acc = sum(test_class_acc_list) / len(test_class_acc_list) print("Test Classification Accuracy List:", test_class_acc_list) print("Average Test Classification Accuracy:", average_test_class_acc) " The above is the Python code with Keras to do multi-task learning with binary segmentation and classification using one mult-task learning model. I train the model 5 times and take the average accuracy. Modify the code to change the model to resnet50 (from keras library), so no need to perform segmentation, only perform classification. Do not modify the other part of my code. Show full code.
dcba266fe0b8ebf0b6e76bc27cddc076
{ "intermediate": 0.3006076216697693, "beginner": 0.3237382769584656, "expert": 0.3756541907787323 }
42,754
class EmailNator(_Nator): def __init__(self): super().__init__("https://www.emailnator.com/", "email") def generate_email(self, options: List[str] = None) -> str: response = self._generate( ["domain", "plusGmail", "dotGmail", "googleMail"], options ) return response["email"][0] def get_messages(self, email: str) -> List[Email]: messages = self._messages_list(email) return [ Email( message["messageID"], message["from"], message["subject"], message["time"], ) for message in messages if message["messageID"] != "ADSVPN" ] def get_message(self, email: str, message_id: str) -> str: json_data = {"email": email, "messageID": message_id} response = self.session.post(self.url + "message-list", json=json_data) response.raise_for_status() return response.text перенеси это в C#
33a99cc1abae1a4946ee7ce626e8c713
{ "intermediate": 0.3312707841396332, "beginner": 0.42662814259529114, "expert": 0.24210108816623688 }
42,755
Можно ли улучшить этот код на C++: #include "pch.h" #include <Windows.h> #include <tlhelp32.h> #include <psapi.h> #include <fstream> #include <vector> #include <string> #include <memory> #include <thread> #include <array> #include <iomanip> #include <sstream> // Класс для управления защитой памяти с помощью RAII class ScopedVirtualProtect { public: ScopedVirtualProtect(HANDLE hProcess, LPCVOID addr, SIZE_T size, DWORD newProtect) : m_hProcess(hProcess), m_addr(const_cast<LPVOID>(addr)), m_size(size), m_oldProtect(0) { if (!VirtualProtectEx(hProcess, m_addr, m_size, newProtect, &m_oldProtect)) { throw std::runtime_error("VirtualProtectEx failed to change protection."); } } ~ScopedVirtualProtect() { VirtualProtectEx(m_hProcess, m_addr, m_size, m_oldProtect, &m_oldProtect); } private: HANDLE m_hProcess; LPVOID m_addr; SIZE_T m_size; DWORD m_oldProtect; }; // Класс для логирования class Logger { public: explicit Logger(const std::string& filename) : m_logFile(filename, std::ios::app) { if (!m_logFile.is_open()) { throw std::runtime_error("Failed to open the log file."); } } void Log(const std::string& message) { m_logFile << message << "\n"; } private: std::ofstream m_logFile; }; Logger g_logger("patcher_log.txt"); // Функция для конвертации указателя в строку с шестнадцатеричным адресом std::string PtrToStr(const void* ptr) { std::stringstream ss; ss << "0x" << std::hex << std::uppercase << std::setw(8) << std::setfill('0') << reinterpret_cast<uintptr_t>(ptr); return ss.str(); } // Применение патча к найденной сигнатуре bool ApplyPatch(HANDLE hProcess, BYTE* addr, size_t offset, BYTE patchByte) { ScopedVirtualProtect protect(hProcess, addr + offset, 1, PAGE_EXECUTE_READWRITE); SIZE_T bytesWritten; if (!WriteProcessMemory(hProcess, addr + offset, &patchByte, 1, &bytesWritten)) { g_logger.Log("Failed to write the patch at " + PtrToStr(addr + offset) + "."); return false; } g_logger.Log("Patch applied successfully at " + PtrToStr(addr + offset) + "."); return true; } // Функция для поиска и патчинга сигнатуры в памяти процесса bool PatchSignatureInProcessMemory(HANDLE hProcess, const std::vector<BYTE>& signature, BYTE patchByte) { MEMORY_BASIC_INFORMATION mbi{}; for (BYTE* addr = nullptr; VirtualQueryEx(hProcess, addr, &mbi, sizeof(mbi)) && reinterpret_cast<uintptr_t>(addr) < 0x7FFFFFFF; addr += mbi.RegionSize) { if (mbi.State != MEM_COMMIT || (mbi.Protect != PAGE_EXECUTE_READWRITE && mbi.Protect != PAGE_EXECUTE_READ)) { continue; } std::vector<BYTE> buffer(mbi.RegionSize); SIZE_T bytesRead; if (!ReadProcessMemory(hProcess, mbi.BaseAddress, buffer.data(), mbi.RegionSize, &bytesRead)) { continue; } for (size_t j = 0; j <= bytesRead - signature.size(); ++j) { if (memcmp(buffer.data() + j, signature.data(), signature.size()) == 0) { if (ApplyPatch(hProcess, addr, j + signature.size() - 1, patchByte)) { g_logger.Log("Signature found and patched at " + PtrToStr(addr + j) + "."); return true; } } } } g_logger.Log("No signature matched for patching."); return false; } bool PatchProcess(DWORD processID, const std::vector<BYTE>& signature, BYTE patchByte) { HANDLE hProcess = OpenProcess(PROCESS_VM_OPERATION | PROCESS_VM_READ | PROCESS_VM_WRITE, FALSE, processID); if (hProcess == NULL) { g_logger.Log("Failed to open the target process."); return false; } std::unique_ptr<void, decltype(&CloseHandle)> processCloser(hProcess, CloseHandle); return PatchSignatureInProcessMemory(hProcess, signature, patchByte); } void AttemptToPatch(DWORD currentPID) { std::vector<BYTE> signature = { 0x85, 0xC0, 0x74, 0x57, 0x5F, 0xB8, 0x01 }; // Наша сигнатура BYTE patchByte = 0x00; // Байт, который будет пропатчен в последнем байте сигнатуры g_logger.Log("Attempting to patch the current process."); if (PatchProcess(currentPID, signature, patchByte)) { g_logger.Log("Process patched successfully."); } else { g_logger.Log("Failed to patch the process."); } } DWORD WINAPI MonitorProcess(LPVOID lpParam) { DWORD currentPID = GetCurrentProcessId(); AttemptToPatch(currentPID); return 0; } BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: DisableThreadLibraryCalls(hModule); CreateThread(nullptr, 0, MonitorProcess, nullptr, 0, nullptr); break; case DLL_THREAD_ATTACH: case DLL_THREAD_DETACH: case DLL_PROCESS_DETACH: break; } return TRUE; }
34b56eab86c39cc2f4b243f85b06f5fb
{ "intermediate": 0.3395146131515503, "beginner": 0.451468825340271, "expert": 0.2090165913105011 }
42,756
Можно ли улучшить этот код на C++: #include "pch.h" #include <Windows.h> #include <tlhelp32.h> #include <psapi.h> #include <fstream> #include <vector> #include <string> #include <memory> #include <thread> #include <array> #include <iomanip> #include <sstream> #include <mutex> // Specialization for managing HANDLEs through smart pointer struct HandleDeleter { void operator()(HANDLE handle) { if (handle != NULL && handle != INVALID_HANDLE_VALUE) { CloseHandle(handle); } } }; using UniqueHandle = std::unique_ptr<std::remove_pointer<HANDLE>::type, HandleDeleter>; // RAII class for memory protection management class ScopedVirtualProtect { public: ScopedVirtualProtect(HANDLE hProcess, LPCVOID addr, SIZE_T size, DWORD newProtect) : m_hProcess(hProcess), m_addr(const_cast<LPVOID>(addr)), m_size(size), m_oldProtect(0) { if (!VirtualProtectEx(hProcess, m_addr, m_size, newProtect, &m_oldProtect)) { throw std::runtime_error("VirtualProtectEx failed to change protection."); } } // On object destruction, restore old protection without throwing exceptions ~ScopedVirtualProtect() noexcept { DWORD temp; VirtualProtectEx(m_hProcess, m_addr, m_size, m_oldProtect, &temp); } private: HANDLE m_hProcess; LPVOID m_addr; SIZE_T m_size; DWORD m_oldProtect; }; // Logging class class Logger { public: explicit Logger(const std::string& filename) : m_logFile(filename, std::ios::app) { if (!m_logFile.is_open()) { throw std::runtime_error("Failed to open the log file."); } } void Log(const std::string& message) { std::lock_guard<std::mutex> lock(m_mutex); // Protect from thread racing m_logFile << message << "\n"; } private: std::mutex m_mutex; // Mutex for synchronized writing to the log file std::ofstream m_logFile; }; Logger g_logger("patcher_log.txt"); std::string PtrToStr(const void* ptr) { std::stringstream ss; ss << "0x" << std::hex << std::uppercase << std::setw(8) << std::setfill('0') << reinterpret_cast<uintptr_t>(ptr); return ss.str(); } bool ApplyPatch(HANDLE hProcess, BYTE* addr, size_t offset, BYTE patchByte) { ScopedVirtualProtect protect(hProcess, addr + offset, 1, PAGE_EXECUTE_READWRITE); SIZE_T bytesWritten; if (!WriteProcessMemory(hProcess, addr + offset, &patchByte, 1, &bytesWritten)) { g_logger.Log("Failed to write the patch at " + PtrToStr(addr + offset) + "."); return false; } g_logger.Log("Patch applied successfully at " + PtrToStr(addr + offset) + "."); return true; } bool PatchSignatureInProcessMemory(HANDLE hProcess, const std::vector<BYTE>& signature, BYTE patchByte) { MEMORY_BASIC_INFORMATION mbi{}; std::vector<BYTE> buffer; for (BYTE* addr = nullptr; VirtualQueryEx(hProcess, addr, &mbi, sizeof(mbi)) && reinterpret_cast<uintptr_t>(addr) < 0x7FFFFFFF; addr += mbi.RegionSize) { if (mbi.State != MEM_COMMIT || (mbi.Protect != PAGE_EXECUTE_READWRITE && mbi.Protect != PAGE_EXECUTE_READ)) { continue; } // Reuse the buffer if it’s not large enough if (buffer.size() < mbi.RegionSize) { buffer.resize(mbi.RegionSize); } SIZE_T bytesRead; if (!ReadProcessMemory(hProcess, mbi.BaseAddress, buffer.data(), mbi.RegionSize, &bytesRead)) { continue; } for (size_t j = 0; j <= bytesRead - signature.size(); ++j) { if (memcmp(buffer.data() + j, signature.data(), signature.size()) == 0) { if (ApplyPatch(hProcess, addr, j + signature.size() - 1, patchByte)) { g_logger.Log("Signature found and patched at " + PtrToStr(addr + j) + "."); return true; } } } } g_logger.Log("No signature matched for patching."); return false; } bool PatchProcess(DWORD processID, const std::vector<BYTE>& signature, BYTE patchByte) { UniqueHandle hProcess(OpenProcess(PROCESS_VM_OPERATION | PROCESS_VM_READ | PROCESS_VM_WRITE, FALSE, processID)); if (!hProcess) { g_logger.Log("Failed to open the target process."); return false; } return PatchSignatureInProcessMemory(hProcess.get(), signature, patchByte); } void AttemptToPatch(DWORD currentPID) { std::vector<BYTE> signature = { 0x85, 0xC0, 0x74, 0x57, 0x5F, 0xB8, 0x01 }; BYTE patchByte = 0x00; g_logger.Log("Attempting to patch the current process."); if (PatchProcess(currentPID, signature, patchByte)) { g_logger.Log("Process patched successfully."); } else { g_logger.Log("Failed to patch the process."); } } DWORD WINAPI MonitorProcess(LPVOID lpParam) { DWORD currentPID = GetCurrentProcessId(); AttemptToPatch(currentPID); return 0; } BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: DisableThreadLibraryCalls(hModule); CreateThread(nullptr, 0, MonitorProcess, nullptr, 0, nullptr); break; case DLL_THREAD_ATTACH: case DLL_THREAD_DETACH: case DLL_PROCESS_DETACH: break; } return TRUE; }
3c90492e4c626be3d68f66d24b14b02a
{ "intermediate": 0.312288373708725, "beginner": 0.5052035450935364, "expert": 0.18250799179077148 }
42,757
je veux que les deux boutons soient toujours à une position fixe sur l’écran (en bas), je veux que le reste soit scrollable s’il y a de l’overflow. import 'package:allo/utils/bottom_round_clipper.dart'; import 'package:flutter/material.dart'; class RegisterPage extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( body: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ ClipPath( clipper: BottomRoundClipper(), child: Container( color: Color(0xFFD9D9D9), child: Transform.translate( offset: Offset(10, -55), // décale l'image de 50 pixels vers le haut child: Transform.scale( scale: 1.2, // zoom sur l'image (1.0 est la taille normale) child: Image.asset( 'assets/register.png', fit: BoxFit .fill, // remplir le conteneur (peut recadrer l'image) ), ), ), ), ), Padding( padding: EdgeInsets.all(20.0), child: Form( child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ Text( 'M\'inscrire', style: TextStyle( fontSize: 24.0, fontWeight: FontWeight.bold, ), ), SizedBox( height: 20.0), // espace entre le titre et le premier champ de texte TextFormField( decoration: InputDecoration( labelText: 'Email', ), ), SizedBox(height: 20.0), // espace entre les champs de texte TextFormField( decoration: InputDecoration( labelText: 'Nom d\'utilisateur', ), ), SizedBox(height: 20.0), // espace entre les champs de texte TextFormField( decoration: InputDecoration( labelText: 'Mot de passe', ), obscureText: true, // cache le mot de passe ), SizedBox( height: 20.0), // espace entre le dernier champ de texte et les boutons Row( mainAxisAlignment: MainAxisAlignment .spaceEvenly, // aligne les boutons horizontalement avec un espace égal entre eux children: [ Expanded( child: Padding( padding: const EdgeInsets.all(8.0), child: ElevatedButton( onPressed: () { print('Button 1'); }, style: ButtonStyle( backgroundColor: MaterialStateProperty.all(Color(0xFFD4D7EC)), ), child: Text( 'Me connecter', style: TextStyle( color: Color(0xFF0F0D11), fontSize: 18.0, ), ), ), ), ), Expanded( child: Padding( padding: const EdgeInsets.all(8.0), child: ElevatedButton( onPressed: () { print('Button 2'); }, style: ButtonStyle( backgroundColor: MaterialStateProperty.all(Color(0xFFD4D7EC)), ), child: Text( 'M\'inscrire', style: TextStyle( color: Color(0xFF0F0D11), fontSize: 18.0, ), ), ), ), ), ], ), ], ), ), ), ], ), ); } }
d66eaf6dc7e7242af024fb46145b751c
{ "intermediate": 0.4194319248199463, "beginner": 0.4487037658691406, "expert": 0.13186432421207428 }
42,758
how can i code the farmer's dillema riddle in prolog
8fe268c5efcbe347e255d2384dcec8d9
{ "intermediate": 0.24927687644958496, "beginner": 0.32639968395233154, "expert": 0.4243234097957611 }
42,759
Нужно ли как-то улучшать код на C++ или оставить как есть: #include "pch.h" #include <Windows.h> #include <tlhelp32.h> #include <psapi.h> #include <fstream> #include <vector> #include <string> #include <memory> #include <thread> #include <array> #include <iomanip> #include <sstream> #include <mutex> #include <chrono> // Структура для удаления HANDLE с помощью умного указателя struct HandleDeleter { void operator()(HANDLE handle) { if (handle != NULL && handle != INVALID_HANDLE_VALUE) { CloseHandle(handle); } } }; using UniqueHandle = std::unique_ptr<std::remove_pointer<HANDLE>::type, HandleDeleter>; // Класс для автоматического управления защитой памяти RAII стиль class ScopedVirtualProtect { public: ScopedVirtualProtect(HANDLE hProcess, LPCVOID addr, SIZE_T size, DWORD newProtect) : m_hProcess(hProcess), m_addr(const_cast<LPVOID>(addr)), m_size(size), m_oldProtect(0) { // Пытаемся изменить защиту памяти, если не получается - бросаем исключение if (!VirtualProtectEx(hProcess, m_addr, m_size, newProtect, &m_oldProtect)) { throw std::runtime_error("VirtualProtectEx failed to change protection."); } } ~ScopedVirtualProtect() noexcept { // В деструкторе восстанавливаем старую защиту памяти. Ошибки игнорируются, так как деструктор не должен бросать исключения DWORD temp; VirtualProtectEx(m_hProcess, m_addr, m_size, m_oldProtect, &temp); } private: HANDLE m_hProcess; LPVOID m_addr; SIZE_T m_size; DWORD m_oldProtect; }; // Класс для логирования class Logger { public: explicit Logger(const std::string& filename) : m_logFile(filename, std::ios::app) { // Открываем файл для записи. Если не удаётся - бросаем исключение if (!m_logFile.is_open()) { throw std::runtime_error("Failed to open the log file."); } } void Log(const std::string& message) { std::lock_guard<std::mutex> lock(m_mutex); // Защита записи в файл от гонок auto now = std::chrono::system_clock::now(); // Получаем текущее время auto now_time_t = std::chrono::system_clock::to_time_t(now); auto localtm = std::localtime(&now_time_t); // Записываем время и сообщение в лог m_logFile << std::put_time(localtm, " % H: % M : % S") << " > " << message << "\n"; } private: std::mutex m_mutex; // Мьютекс для синхронизации записи в файл std::ofstream m_logFile; }; Logger g_logger("patcher_log.txt"); // Функция для преобразования указателя в строку в шестнадцатеричном формате std::string PtrToStr(const void* ptr) { std::stringstream ss; ss << "0x" << std::hex << std::uppercase << std::setw(8) << std::setfill('0') << reinterpret_cast<uintptr_t>(ptr); return ss.str(); } // Функция применения патча в память процесса bool ApplyPatch(HANDLE hProcess, BYTE* addr, size_t offset, BYTE patchByte) { ScopedVirtualProtect protect(hProcess, addr + offset, 1, PAGE_EXECUTE_READWRITE); SIZE_T bytesWritten; // Пытаемся записать байт и проверяем результат if (!WriteProcessMemory(hProcess, addr + offset, &patchByte, 1, &bytesWritten)) { g_logger.Log("Failed to write the patch at " + PtrToStr(addr + offset) + "."); return false; } g_logger.Log("Patch applied successfully at " + PtrToStr(addr + offset) + "."); return true; } // Поиск и применение патча для заданной сигнатуры в памяти процесса bool PatchSignatureInProcessMemory(HANDLE hProcess, const std::vector<BYTE>& signature, BYTE patchByte) { MEMORY_BASIC_INFORMATION mbi{}; std::vector<BYTE> buffer; // Перебор областей памяти for (BYTE* addr = nullptr; VirtualQueryEx(hProcess, addr, &mbi, sizeof(mbi)) && reinterpret_cast<uintptr_t>(addr) < 0x7FFFFFFF; addr += mbi.RegionSize) { // Фильтруем области памяти, которые не подходят if (mbi.State != MEM_COMMIT || (mbi.Protect != PAGE_EXECUTE_READWRITE && mbi.Protect != PAGE_EXECUTE_READ)) { continue; } // Оптимизация: переиспользование буфера if (buffer.size() < mbi.RegionSize) { buffer.resize(mbi.RegionSize); } SIZE_T bytesRead; // Читаем содержимое области памяти if (!ReadProcessMemory(hProcess, mbi.BaseAddress, buffer.data(), mbi.RegionSize, &bytesRead)) { continue; } // Поиск сигнатуры и патчинг for (size_t j = 0; j <= bytesRead - signature.size(); ++j) { if (memcmp(buffer.data() + j, signature.data(), signature.size()) == 0) { if (ApplyPatch(hProcess, reinterpret_cast<BYTE*>(mbi.BaseAddress), j + signature.size() - 1, patchByte)) { g_logger.Log("Signature found and patched at " + PtrToStr(reinterpret_cast<BYTE*>(mbi.BaseAddress) + j) + "."); return true; } } } } g_logger.Log("No signature matched for patching."); return false; } // Функция для патчинга процесса по его ID bool PatchProcess(DWORD processID, const std::vector<BYTE>& signature, BYTE patchByte) { UniqueHandle hProcess(OpenProcess(PROCESS_VM_OPERATION | PROCESS_VM_READ | PROCESS_VM_WRITE, FALSE, processID)); // Проверка на успешное открытие процесса if (!hProcess) { g_logger.Log("Failed to open the target process."); return false; } return PatchSignatureInProcessMemory(hProcess.get(), signature, patchByte); } // Попытка патча текущего процесса void AttemptToPatch(DWORD currentPID) { std::vector<BYTE> signature = { 0x85, 0xC0, 0x74, 0x57, 0x5F, 0xB8, 0x01 }; BYTE patchByte = 0x00; g_logger.Log("Attempting to patch the current process."); if (PatchProcess(currentPID, signature, patchByte)) { g_logger.Log("Process patched successfully."); } else { g_logger.Log("Failed to patch the process."); } } // Функция потока для мониторинга и патчинга процесса DWORD WINAPI MonitorProcess(LPVOID lpParam) { DWORD currentPID = GetCurrentProcessId(); AttemptToPatch(currentPID); return 0; } // Точка входа для DLL BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: // Отключаем вызовы для потоков DLL DisableThreadLibraryCalls(hModule); // Запускаем поток для мониторинга и патчинга std::thread(MonitorProcess).detach(); break; case DLL_THREAD_ATTACH: case DLL_THREAD_DETACH: case DLL_PROCESS_DETACH: break; } return TRUE; }
dc3be21ed8e1f6bbcd6fe2821683c113
{ "intermediate": 0.3698371648788452, "beginner": 0.4525761008262634, "expert": 0.1775866597890854 }
42,760
hello
c4ed7bd43a21af75353e35402606aeef
{ "intermediate": 0.32064199447631836, "beginner": 0.28176039457321167, "expert": 0.39759764075279236 }
42,761
Improve the code below: function isObject(obj) { return typeof obj === 'function' || typeof obj === 'object'; } function merge(target, source) { for (let key in source) { if (isObject(target[key]) && isObject(source[key])) { merge(target[key], source[key]); } else { target[key] = source[key]; } } return target; } function clone(target) { if (target.admin) { return "you cannot change the admin" } return merge({admin: 'bob'}, target); } const res = clone({claims: ['foo', 'bar']})
269a2d7bbfa84b3b709ec385eeae1c82
{ "intermediate": 0.3143385052680969, "beginner": 0.5041518807411194, "expert": 0.1815095841884613 }
42,762
User where is the vulnerabilty here function isObject(obj) { return typeof obj === 'function' || typeof obj === 'object'; } function merge(target, source) { for (let key in source) { if (isObject(target[key]) && isObject(source[key])) { merge(target[key], source[key]); } else { target[key] = source[key]; } } return target; } function clone(target) { if (target.admin) { return "you cannot change the admin" } return merge({admin: 'bob'}, target); } const res = clone({claims: ['foo', 'bar']}) console.log(res)
d31fc1c1c09ab62ab7ed01a5c068a8af
{ "intermediate": 0.3269999921321869, "beginner": 0.5007191896438599, "expert": 0.17228078842163086 }
42,763
from datasets import load_dataset def preprocess_for_question_generation(examples): if examples["answer"] is None or examples["context"] is None: return None ​ if not isinstance(examples["answer"], list) or not isinstance(examples["context"], list): return None ​ if len(examples["answer"]) != len(examples["context"]): return None ​ prepared_questions = [] prepared_input_texts = [] for context, answer in zip(examples["context"], examples["answer"]): input_format = f"generate question: context: {context} answer: {answer}" prepared_input_texts.append(input_format) tokenized_inputs = tokenizer( prepared_input_texts, max_length=128, padding="max_length", truncation=True, return_tensors="pt" ) ​ if "question" in examples: tokenized_questions = tokenizer( examples["question"], max_length=64, padding="max_length", truncation=True, return_tensors="pt" ) tokenized_inputs["labels"] = tokenized_questions["input_ids"].clone() # Convert tensors to NumPy arrays tokenized_inputs_numpy = {} for key, value in tokenized_inputs.items(): tokenized_inputs_numpy[key] = value.numpy() ​ return tokenized_inputs_numpy ​ # Apply preprocessing to datasets tokenized_train_dataset = train_dataset.map(preprocess_for_question_generation, batched=True) tokenized_val_dataset = val_dataset.map(preprocess_for_question_generation, batched=True) tokenized_test_dataset = test_dataset.map(preprocess_for_question_generation, batched=True) 100% 43/43 [00:20<00:00, 2.28ba/s] 100% 11/11 [00:05<00:00, 2.40ba/s] 100% 6/6 [00:02<00:00, 2.33ba/s] add Codeadd Markdown # Define data collator for sequence-to-sequence models data_collator = DataCollatorForSeq2Seq(tokenizer) add Codeadd Markdown # Define the training arguments training_args = TrainingArguments( output_dir="./question_generation_arat1024_3_model", num_train_epochs=3, per_device_train_batch_size=8, per_device_eval_batch_size=8, save_total_limit=2, evaluation_strategy="epoch", report_to=[], # Set report_to to an empty list to disable wandb logging learning_rate=5e-5 # Set your desired learning rate here ) # Model trainer trainer = Trainer( model=model, args=training_args, train_dataset=tokenized_train_dataset, eval_dataset=tokenized_val_dataset, tokenizer=tokenizer, data_collator=data_collator, #optimizers=(optimizer, scheduler), # Add the following line to specify decoder_input_ids or decoder_inputs_embeds #decoder_input_ids=torch.tensor([[tokenizer.pad_token_id]*128]), # Example, adjust as needed ) ​ # Train the model trainer.train() [16092/16092 1:42:41, Epoch 3/3] Epoch Training Loss Validation Loss 1 0.594300 0.511139 2 0.529000 0.493306 3 0.501300 0.489161 TrainOutput(global_step=16092, training_loss=0.6901373387923917, metrics={'train_runtime': 6162.841, 'train_samples_per_second': 20.889, 'train_steps_per_second': 2.611, 'total_flos': 2.796696858997555e+16, 'train_loss': 0.6901373387923917, 'epoch': 3.0}) after i train how can compute blue and add function generate question
62b53578cc0ab32c0c77221f37b1f0e5
{ "intermediate": 0.30863773822784424, "beginner": 0.2657862603664398, "expert": 0.42557600140571594 }
42,764
Improve this code considering that some params may be user-provided: function isObject(obj) { return typeof obj === 'function' || typeof obj === 'object'; } function merge(target, source) { for (let key in source) { if (isObject(target[key]) && isObject(source[key])) { merge(target[key], source[key]); } else { target[key] = source[key]; } } return target; } function clone(target) { if (target.admin) { return "you cannot change the admin" } return merge({admin: 'bob'}, target); } const res = clone({claims: ['foo', 'bar']})
1f6d9b5f374909d1571dba48c82fbcf2
{ "intermediate": 0.3070972263813019, "beginner": 0.549833357334137, "expert": 0.14306944608688354 }
42,765
В верной ли последовательности расположены функции и строки в этом коде DLL на C++: #include "pch.h" #include <Windows.h> #include <tlhelp32.h> #include <psapi.h> #include <fstream> #include <vector> #include <string> #include <memory> #include <thread> #include <array> #include <iomanip> #include <sstream> #include <mutex> #include <chrono> // Thread-safe logger class class Logger { public: explicit Logger(const std::string& filename) : m_logFile(filename, std::ios::app) { if (!m_logFile.is_open()) { throw std::runtime_error("Failed to open log file."); } } void Log(const std::string& message) { std::lock_guard<std::mutex> lock(m_mutex); auto now = std::chrono::system_clock::now(); auto now_time_t = std::chrono::system_clock::to_time_t(now); std::tm localtm; localtime_s(&localtm, &now_time_t); m_logFile << std::put_time(&localtm, " %H:%M:%S") << " > " << message << "\n"; } private: std::mutex m_mutex; std::ofstream m_logFile; }; Logger g_logger("patcher_log.txt"); // Converts a pointer to a string representation std::string PtrToStr(const void* ptr) { std::stringstream ss; ss << "0x" << std::hex << std::uppercase << std::setw(8) << std::setfill('0') << reinterpret_cast<uintptr_t>(ptr); return ss.str(); } // Wrapper for automatic HANDLE closing struct HandleDeleter { void operator()(HANDLE handle) { if (handle != NULL && handle != INVALID_HANDLE_VALUE) { CloseHandle(handle); } } }; using UniqueHandle = std::unique_ptr<void, HandleDeleter>; // RAII class for safe memory protection setting class ScopedVirtualProtect { public: ScopedVirtualProtect(HANDLE hProcess, LPCVOID addr, SIZE_T size, DWORD newProtect) : m_hProcess(hProcess), m_addr(const_cast<LPVOID>(addr)), m_size(size), m_oldProtect(0) { if (!VirtualProtectEx(hProcess, m_addr, m_size, newProtect, &m_oldProtect)) { g_logger.Log("VirtualProtectEx failed to change protection at address " + PtrToStr(addr) + "."); } } ~ScopedVirtualProtect() noexcept { DWORD temp; if (!VirtualProtectEx(m_hProcess, m_addr, m_size, m_oldProtect, &temp)) { g_logger.Log("Failed to revert protection at address " + PtrToStr(m_addr) + "."); } } private: HANDLE m_hProcess; LPVOID m_addr; SIZE_T m_size; DWORD m_oldProtect; }; // Apply a patch to a process bool ApplyPatch(HANDLE hProcess, BYTE* addr, size_t offset, BYTE patchByte) { ScopedVirtualProtect protect(hProcess, addr + offset, 1, PAGE_EXECUTE_READWRITE); SIZE_T bytesWritten; if (!WriteProcessMemory(hProcess, addr + offset, &patchByte, 1, &bytesWritten)) { g_logger.Log("Failed to write patch to " + PtrToStr(addr + offset) + "."); return false; } g_logger.Log("Patch successfully applied at " + PtrToStr(addr + offset) + "."); return true; } // Search and apply a patch to a signature in process memory bool PatchSignatureInProcessMemory(HANDLE hProcess, const std::vector<BYTE>& signature, BYTE patchByte) { MEMORY_BASIC_INFORMATION mbi{}; std::vector<BYTE> buffer; for (BYTE* addr = nullptr; VirtualQueryEx(hProcess, addr, &mbi, sizeof(mbi)) && reinterpret_cast<uintptr_t>(addr) < 0x7FFFFFFF; addr += mbi.RegionSize) { if (mbi.State != MEM_COMMIT || (mbi.Protect != PAGE_EXECUTE_READWRITE && mbi.Protect != PAGE_EXECUTE_READ)) { continue; } buffer.resize(mbi.RegionSize); SIZE_T bytesRead; if (!ReadProcessMemory(hProcess, mbi.BaseAddress, buffer.data(), mbi.RegionSize, &bytesRead)) { continue; } for (size_t j = 0; j <= bytesRead - signature.size(); ++j) { if (memcmp(buffer.data() + j, signature.data(), signature.size()) == 0) { if (ApplyPatch(hProcess, reinterpret_cast<BYTE*>(mbi.BaseAddress), j + signature.size() - 1, patchByte)) { g_logger.Log("Signature found and patched at " + PtrToStr(reinterpret_cast<BYTE*>(mbi.BaseAddress) + j) + "."); return true; } } } } g_logger.Log("No signature found for patching."); return false; } // Entry point for patching process bool PatchProcess(DWORD processID, const std::vector<BYTE>& signature, BYTE patchByte) { UniqueHandle hProcess(OpenProcess(PROCESS_VM_OPERATION | PROCESS_VM_READ | PROCESS_VM_WRITE, FALSE, processID)); if (!hProcess) { g_logger.Log("Failed to open target process."); return false; } return PatchSignatureInProcessMemory(hProcess.get(), signature, patchByte); } void AttemptToPatch(DWORD currentPID) { std::vector<BYTE> signature = { 0x85, 0xC0, 0x74, 0x57, 0x5F, 0xB8, 0x01 }; BYTE patchByte = 0x00; g_logger.Log("Attempting to patch the current process."); if (PatchProcess(currentPID, signature, patchByte)) { g_logger.Log("Process patched successfully."); } else { g_logger.Log("Failed to patch the process."); } } DWORD WINAPI MonitorProcess(LPVOID lpParam) { DWORD currentPID = GetCurrentProcessId(); AttemptToPatch(currentPID); return 0; } BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: DisableThreadLibraryCalls(hModule); std::thread(MonitorProcess).detach(); break; case DLL_THREAD_ATTACH: case DLL_THREAD_DETACH: case DLL_PROCESS_DETACH: break; } return TRUE; }
76c520f48db1724abdfeb5bfef88a2bf
{ "intermediate": 0.29071536660194397, "beginner": 0.5135412812232971, "expert": 0.19574333727359772 }
42,766
can you write me a log simulator with a gui and buttons for vcreating and viewing the logs make it modern and advanced
40a314acdbd645060134dd12d96f030d
{ "intermediate": 0.5312727093696594, "beginner": 0.1687103509902954, "expert": 0.30001696944236755 }
42,767
Modify this code to just do the computations to get Start, End, Speaker and Text. Words and word level probabilities are not required - import base64 import datetime import subprocess import os import requests import time import torch import re import json import pandas as pd from typing import List from faster_whisper import WhisperModel from pyannote.audio import Pipeline class Output: def __init__(self, segments: list, language: str = None, num_speakers: int = None): self.segments = segments self.language = language self.num_speakers = num_speakers class Predictor: def __init__(self): """Load the model into memory to make running multiple predictions efficient""" model_name = "large-v3" self.model = WhisperModel( model_name, device="cuda" if torch.cuda.is_available() else "cpu", compute_type="float16", ) self.diarization_model = Pipeline.from_pretrained( "pyannote/speaker-diarization-3.1", use_auth_token="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", ).to(torch.device("cuda")) def predict(self, file_string: str = None, file_url: str = None, file: str = None, group_segments: bool = True, transcript_output_format: str = "both", num_speakers: int = None, language: str = None, prompt: str = None, offset_seconds: int = 0, ) -> Output: """Run a single prediction on the model""" try: temp_wav_filename = f"temp-{time.time_ns()}.wav" if file: subprocess.run(["ffmpeg", "-i", file, "-ar", "16000", "-ac", "1", "-c:a", "pcm_s16le", temp_wav_filename, ]) elif file_url: response = requests.get(file_url) temp_audio_filename = f"temp-{time.time_ns()}.audio" with open(temp_audio_filename, "wb") as f: f.write(response.content) subprocess.run(["ffmpeg", "-i", temp_audio_filename, "-ar", "16000", "-ac", "1", "-c:a", "pcm_s16le", temp_wav_filename, ]) if os.path.exists(temp_audio_filename): os.remove(temp_audio_filename) elif file_string: audio_data = base64.b64decode(file_string.split(",")[1] if "," in file_string else file_string) temp_audio_filename = f"temp-{time.time_ns()}.audio" with open(temp_audio_filename, "wb") as f: f.write(audio_data) subprocess.run(["ffmpeg", "-i", temp_audio_filename, "-ar", "16000", "-ac", "1", "-c:a", "pcm_s16le", temp_wav_filename, ]) if os.path.exists(temp_audio_filename): os.remove(temp_audio_filename) segments, detected_num_speakers, detected_language = self.speech_to_text(temp_wav_filename, num_speakers, prompt, offset_seconds, group_segments, language, word_timestamps=True, transcript_output_format=transcript_output_format, ) return Output(segments=segments, language=detected_language, num_speakers=detected_num_speakers,) except Exception as e: raise RuntimeError("Error Running inference with local model", e) finally: if os.path.exists(temp_wav_filename): os.remove(temp_wav_filename) def convert_time(self, secs, offset_seconds=0): return datetime.timedelta(seconds=(round(secs) + offset_seconds)) def speech_to_text(self, audio_file_wav, num_speakers=None, prompt="",offset_seconds=0, group_segments=True, language=None, word_timestamps=True, transcript_output_format="both", ): time_start = time.time() options = dict(vad_filter=True, vad_parameters=dict(min_silence_duration_ms=1000), initial_prompt=prompt, word_timestamps=word_timestamps, language=language, ) segments, transcript_info = self.model.transcribe(audio_file_wav, **options) segments = list(segments) segments = [ { "avg_logprob": s.avg_logprob, "start": float(s.start + offset_seconds), "end": float(s.end + offset_seconds), "text": s.text, "words": [ { "start": float(w.start + offset_seconds), "end": float(w.end + offset_seconds), "word": w.word, "probability": w.probability, } for w in s.words ], } for s in segments ] diarization = self.diarization_model(audio_file_wav, min_speakers=2, max_speakers=3) diarization_list = list(diarization.itertracks(yield_label=True)) unique_speakers = {speaker for _, _, speaker in diarization.itertracks(yield_label=True)} detected_num_speakers = len(unique_speakers) speaker_idx = 0 n_speakers = len(diarization_list) final_segments = [] for segment in segments: segment_start = segment["start"] + offset_seconds segment_end = segment["end"] + offset_seconds segment_text = [] segment_words = [] for word in segment["words"]: word_start = word["start"] + offset_seconds - 0.1 word_end = word["end"] + offset_seconds + 0.1 while speaker_idx < n_speakers: turn, _, speaker = diarization_list[speaker_idx] if turn.start <= word_end and turn.end >= word_start: segment_text.append(word["word"]) word["word"] = word["word"].strip() segment_words.append(word) if turn.end <= word_end: speaker_idx += 1 break elif turn.end < word_start: speaker_idx += 1 else: break if segment_text: combined_text = "".join(segment_text) cleaned_text = re.sub(" ", " ", combined_text).strip() new_segment = { "avg_logprob": segment["avg_logprob"], "start": segment_start - offset_seconds, "end": segment_end - offset_seconds, "speaker": speaker, "text": cleaned_text, "words": segment_words, } final_segments.append(new_segment) output = [] current_group = { "start": str(final_segments[0]["start"]), "end": str(final_segments[0]["end"]), "speaker": final_segments[0]["speaker"], "avg_logprob": final_segments } if transcript_output_format in ("segments_only", "both"): current_group["text"] = final_segments[0]["text"] if transcript_output_format in ("words_only", "both"): current_group["words"] = final_segments[0]["words"] for segment in final_segments[1:]: time_gap = segment["start"] - float(current_group["end"]) if segment["speaker"] == current_group["speaker"] and time_gap <= 2 and group_segments: current_group["end"] = str(segment["end"]) if transcript_output_format in ("segments_only", "both"): current_group["text"] += " " + segment["text"] if transcript_output_format in ("words_only", "both"): current_group.setdefault("words", []).extend(segment["words"]) else: output.append(current_group) current_group = { "start": str(segment["start"]), "end": str(segment["end"]), "speaker": segment["speaker"], "avg_logprob": segment["avg_logprob"], } if transcript_output_format in ("segments_only", "both"): current_group["text"] = segment["text"] if transcript_output_format in ("words_only", "both"): current_group["words"] = segment["words"] output.append(current_group) time_end = time.time() time_diff = time_end - time_start system_info = f"Processing time: {time_diff:.5} seconds" print(system_info) return output, detected_num_speakers, transcript_info.language if __name__ == "__main__": predictor = Predictor() audio_file_path = "audio.wav" output = predictor.predict(file=audio_file_path) #print("Segments:", output.segments) print("Detected Language:", output.language) print("Number of Speakers:", output.num_speakers) modified_data = [] for item in output.segments: modified_item = { 'start': item['start'], 'end': item['end'], 'speaker': item['speaker'], 'text': item['text'] } modified_data.append(modified_item) df = pd.DataFrame(modified_data) # Convert 'start' and 'end' columns to numeric #df['start'] = pd.to_numeric(df['start']) #df['end'] = pd.to_numeric(df['end']) # Print DataFrame print(df)
3e0298f17f134078860f5c97f8c9a742
{ "intermediate": 0.3785155117511749, "beginner": 0.4909466505050659, "expert": 0.13053788244724274 }
42,768
write some python code for a simple gui and some buttons
c13c24f9df7035538fb4083a48651134
{ "intermediate": 0.40086472034454346, "beginner": 0.3490391671657562, "expert": 0.25009608268737793 }