kernel_id
int64
24.2k
23.3M
prompt
stringlengths
8
1.85M
completetion
stringlengths
1
182k
comp_name
stringlengths
5
57
11,281,017
import os from typing import Dict, List, Tuple from joblib import Parallel, delayed import pandas as pd import numpy as np from scipy.optimize.minpack import curve_fit from scipy.optimize import least_squares from xgboost import XGBRegressor<load_from_csv>
class Visibility(tf.keras.callbacks.Callback): def __init__(self): super(Visibility, self ).__init__() self.metrics = ['sparse_categorical_accuracy', 'loss'] def on_train_begin(self, logs=None): self.train_begin = time.time() def on_train_end(self, logs=None): print(' Training took ', time.time() - self.train_begin, 'seconds') def on_epoch_end(self, epoch, logs=None): output = "" for metric in self.metrics: diff =(( logs['val_'+metric] / logs[metric])- 1)*100 output += f"val/{metric}: {diff:.2f}% " print(" " + output) def on_train_batch_begin(self, batch, logs=None): print("▪", end="") def on_test_batch_end(self, batch, logs=None): print("▫", end="")
Petals to the Metal - Flower Classification on TPU
11,281,017
def load_kaggle_csv(dataset: str, datadir: str)-> pd.DataFrame: df = pd.read_csv( f"{os.path.join(datadir,dataset)}.csv", parse_dates=["Date"] ) df['country'] = df["Country_Region"] if "Province_State" in df: df["Country_Region"] = np.where( df["Province_State"].isnull() , df["Country_Region"], df["Country_Region"] + "_" + df["Province_State"], ) df.drop(columns="Province_State", inplace=True) if "ConfirmedCases" in df: df["ConfirmedCases"] = df.groupby("Country_Region")[ "ConfirmedCases" ].cummax() if "Fatalities" in df: df["Fatalities"] = df.groupby("Country_Region")["Fatalities"].cummax() if not "DayOfYear" in df: df["DayOfYear"] = df["Date"].dt.dayofyear df["Date"] = df["Date"].dt.date return df def RMSLE(actual: np.ndarray, prediction: np.ndarray)-> float: return np.sqrt( np.mean( np.power(np.log1p(np.maximum(0, prediction)) - np.log1p(actual), 2) ) )<load_from_csv>
EPOCHS = 50 history = {} def fit_models(models, history): for x in models: print(f'Starting training for {x}') hist = models[x].fit( train_ds.data() , validation_data = val_ds.data() , epochs = EPOCHS, steps_per_epoch = train_ds.count() // BATCH_SIZE, verbose=2, callbacks=[ tf.keras.callbacks.ModelCheckpoint( monitor='val_sparse_categorical_accuracy', verbose=2, save_best_only=True, save_weights_only=True, mode='max', filepath=f'{x}.h5'), lr_callback, tf.keras.callbacks.EarlyStopping( monitor='val_sparse_categorical_accuracy', min_delta=0.001, patience=3, verbose=2, mode='max', baseline=None, restore_best_weights=True ), Visibility() , ], ) history[x] = hist fit_models(models, history )
Petals to the Metal - Flower Classification on TPU
11,281,017
train = load_kaggle_csv( "train", "/kaggle/input/covid19-global-forecasting-week-3") country_health_indicators =( pd.read_csv("/kaggle/input/country-health-indicators/country_health_indicators_v3.csv")).rename( columns={'Country_Region': 'country'}) train = pd.merge(train, country_health_indicators, on="country", how="left" )<merge>
highest_f1 = 0 highest_f1_model = '' preds = list() def get_y_true() : def get_val_classes() : all_classes = np.array([]) for examples in val_ds.data() : all_classes = np.concatenate([all_classes, examples[1].numpy() ]) return all_classes y_true = get_val_classes() print('True Values:: Length:', len(y_true), ', List:', y_true) return y_true def predict_models(models, y_true): global highest_f1 global highest_f1_model global preds val_tpu_ds = val_aug_ds.data().map(lambda image, ids: image) for x in models: val_aug_count = 2 y_val_pred = np.zeros(( 3712,104), dtype=np.float64) for i in range(val_aug_count): y_val_loop = models[x].predict(val_tpu_ds, verbose=1) y_val_loop = tf.cast(y_val_loop, tf.float32) y_val_pred += y_val_loop.numpy() y_val_pred /= val_aug_count y_val = np.argmax(y_val_pred, axis=-1 ).astype(np.float32) print(f' Scores for {x} ') print(f'{x}: Pred Values:: Length:{len(y_val)} List: {y_val}') model_f1_score = f1_score(y_true, y_val, average='macro', zero_division=0)*100 if model_f1_score > highest_f1: highest_f1 = model_f1_score highest_f1_model = x scores = { "metrics": [ "F1", "Precision", "Recall", ], "scores": [ model_f1_score, precision_score(y_true, y_val, average='macro', zero_division=0)*100, recall_score(y_true, y_val, average='macro', zero_division=0)*100, ] } print(pd.DataFrame.from_dict(scores)) preds.append(( x, y_val_pred, model_f1_score, )) y_true = get_y_true() predict_models(models, y_true )
Petals to the Metal - Flower Classification on TPU
11,281,017
test = load_kaggle_csv( "test", "/kaggle/input/covid19-global-forecasting-week-3") test = pd.merge(test, country_health_indicators, on="country", how="left" )<train_on_grid>
def get_best_alpha(pred1, pred2): best_alpha = 0 best_f1 = 0 for x in np.linspace(0, 1, 101): mixed =(pred1 * x)+(pred2 *(1-x)) y_mixed = np.argmax(mixed, axis=-1 ).astype(np.float32) mixed_f1 = f1_score(y_true, y_mixed, average='macro', zero_division=0)*100 if mixed_f1 > best_f1: best_f1 = mixed_f1 best_alpha = x return best_alpha, best_f1 def get_alpha(preds, y_true): output = list() preds = np.array(preds) preds = preds[preds[:,2].argsort() [::-1]] model_name = preds[0][0] predictions = preds[0][1] model_f1 = preds[0][2] output.append(( model_name, 1)) best_predictions = predictions best_f1 = model_f1 print(best_f1, output) for i in range(1, len(preds)) : i_name = preds[i][0] i_preds = preds[i][1] i_f1 = preds[i][1] alpha, f1 = get_best_alpha(best_predictions, i_preds) if f1 > best_f1: best_predictions =(alpha * i_preds)+(( 1-alpha)* best_predictions) best_f1 = f1 output.append(( i_name, alpha)) print(best_f1, output) return output alpha_chain = get_alpha(preds, y_true )
Petals to the Metal - Flower Classification on TPU
11,281,017
def logistic(x: np.ndarray, x0: float, L: float, k: float)-> np.ndarray: return L /(1 + np.exp(-k *(x - x0))) def fit_single_logistic(x: np.ndarray, y: np.ndarray, maxfev: float)-> Tuple: p0 = [np.median(x), y[-1], 0.1] pn0 = p0 *(np.random.random(len(p0)) + [0.5, 1.0, 0.5]) try: params, pcov = curve_fit( logistic, x, y, p0=pn0, maxfev=maxfev, sigma=np.maximum(1, np.sqrt(y)) *(0.1 + 0.9 * np.random.random()), bounds=([0, y[-1], 0.01], [200, 1e6, 1.5]), ) pcov = pcov[np.triu_indices_from(pcov)] except(RuntimeError, ValueError): params = p0 pcov = np.zeros(len(p0)*(len(p0)- 1)) y_hat = logistic(x, *params) rmsle = RMSLE(y_hat, y) return(params, pcov, rmsle, y_hat) def fit_logistic( df: pd.DataFrame, n_jobs: int = 8, n_samples: int = 80, maxfev: int = 8000, x_col: str = "DayOfYear", y_cols: List[str] = ["ConfirmedCases", "Fatalities"], )-> pd.DataFrame: def fit_one(df: pd.DataFrame, y_col: str)-> Dict: best_rmsle = None best_params = None x = df[x_col].to_numpy() y = df[y_col].to_numpy() for(params, cov, rmsle, y_hat)in Parallel(n_jobs=n_jobs )( delayed(fit_single_logistic )(x, y, maxfev=maxfev) for i in range(n_samples) ): if rmsle >=(best_rmsle or rmsle): best_rmsle = rmsle best_params = params result = {f"{y_col}_rmsle": best_rmsle} result.update({f"{y_col}_p_{i}": p for i, p in enumerate(best_params)}) return result result = {} for y_col in y_cols: result.update(fit_one(df, y_col)) return pd.DataFrame([result]) def predict_logistic( df: pd.DataFrame, x_col: str = "DayOfYear", y_cols: List[str] = ["ConfirmedCases", "Fatalities"], ): def predict_one(col): df[f"yhat_logistic_{col}"] = logistic( df[x_col].to_numpy() , df[f"{col}_p_0"].to_numpy() , df[f"{col}_p_1"].to_numpy() , df[f"{col}_p_2"].to_numpy() , ) for y_col in y_cols: predict_one(y_col )<merge>
print(f'{highest_f1_model} has the highest f1 score - {highest_f1:0.5f}' )
Petals to the Metal - Flower Classification on TPU
11,281,017
<train_model><EOS>
ds_submission = DS(TEST_FILES, training=False, augment=True, batch_size=BATCH_SIZE ).data() ds_submission = ds_submission.map(lambda image, ids: image) def get_test_ids() : all_ids = np.array([]) for examples in test_ds.data() : all_ids = np.concatenate([all_ids, examples[1].numpy().astype('U')]) return all_ids def get_prediction_with_tta(model, ds_submission): tta = 5 y_pred = np.zeros(( 7382,104), dtype=np.float64) for x in range(tta): y_pred_loop = model.predict(ds_submission, verbose=2) y_pred_loop = tf.cast(y_pred_loop, tf.float32) y_pred += y_pred_loop.numpy() y_pred /= tta return y_pred def create_submission(alpha_chain, models, ds_submission): y_pred = np.zeros(( 7382,104), dtype=np.float64) for x in alpha_chain: model = x[0] alpha = x[1] print('Predicting with', model, 'with alpha', alpha) y_pred_chain = get_prediction_with_tta(models[model], ds_submission) y_pred =(alpha * y_pred_chain)+(( 1-alpha)* y_pred) y_pred = np.argmax(y_pred, axis=-1) filename = f'submission.csv' np.savetxt( filename, np.column_stack(( get_test_ids() , y_pred)) , fmt=('%s', '%s'), delimiter=',', header='id,label', comments='' ) create_submission(alpha_chain, models, ds_submission )
Petals to the Metal - Flower Classification on TPU
11,172,062
<SOS> metric: macrofscore Kaggle data source: petals-to-the-metal-flower-classification-on-tpu<define_variables>
!pip install -q tensorflow==2.3.0 !pip install -q git+https://github.com/keras-team/keras-tuner@master !pip install -q cloud-tpu-client
Petals to the Metal - Flower Classification on TPU
11,172,062
xgb_params = dict( gamma=0.2, learning_rate=0.15, n_estimators=100, max_depth=11, min_child_weight=1, nthread=8, objective="reg:squarederror") x_columns = [ 'DayOfYear', 'cases_growth', 'death_growth', 'Cardiovascular diseases(%)', 'Cancers(%)', 'Diabetes, blood, & endocrine diseases(%)', 'Respiratory diseases(%)', 'Liver disease(%)', 'Diarrhea & common infectious diseases(%)', 'Musculoskeletal disorders(%)', 'HIV/AIDS and tuberculosis(%)', 'Malaria & neglected tropical diseases(%)', 'Nutritional deficiencies(%)', 'pneumonia-death-rates', 'Share of deaths from smoking(%)', 'alcoholic_beverages', 'animal_fats', 'animal_products', 'aquatic_products,_other', 'cereals_-_excluding_beer', 'eggs', 'fish,_seafood', 'fruits_-_excluding_wine', 'meat', 'milk_-_excluding_butter', 'miscellaneous', 'offals', 'oilcrops', 'pulses', 'spices', 'starchy_roots', 'stimulants', 'sugar_&_sweeteners', 'treenuts', 'vegetable_oils', 'vegetables', 'vegetal_products', 'hospital_beds_per10k', 'hospital_density', 'nbr_surgeons', 'nbr_obstetricians', 'nbr_anaesthesiologists', 'medical_doctors_per10k', 'bcg_coverage', 'bcg_year_delta', 'population', 'median age', 'population growth rate', 'birth rate', 'death rate', 'net migration rate', 'maternal mortality rate', 'infant mortality rate', 'life expectancy at birth', 'total fertility rate', 'obesity - adult prevalence rate', 'school_shutdown_1case', 'school_shutdown_10case', 'school_shutdown_50case', 'school_shutdown_1death', 'FF_DayOfYear', 'case1_DayOfYear', 'case10_DayOfYear', 'case50_DayOfYear', 'yhat_logistic_ConfirmedCases', 'yhat_logistic_Fatalities'] xgb_c_rmsle, xgb_c_fit = apply_xgb_model( train, x_columns, "ConfirmedCases", xgb_params) xgb_f_rmsle, xgb_f_fit = apply_xgb_model( train, x_columns, "Fatalities", xgb_params )<train_model>
print('Tensorflow version ' + tf.__version__)
Petals to the Metal - Flower Classification on TPU
11,172,062
def interpolate(alpha, x0, x1): return x0 * alpha + x1 *(1 - alpha) def RMSLE_interpolate(alpha, y, x0, x1): return RMSLE(y, interpolate(alpha, x0, x1)) def fit_hybrid( train: pd.DataFrame, y_cols: List[str] = ["ConfirmedCases", "Fatalities"] )-> pd.DataFrame: def fit_one(y_col: str): opt = least_squares( fun=RMSLE_interpolate, args=( train[y_col], train[f"yhat_logistic_{y_col}"], train[f"yhat_xgb_{y_col}"], ), x0=(0.5,), bounds=(( 0.0),(1.0,)) , ) return {f"{y_col}_alpha": opt.x[0], f"{y_col}_cost": opt.cost} result = {} for y_col in y_cols: result.update(fit_one(y_col)) return pd.DataFrame([result]) def predict_hybrid( df: pd.DataFrame, x_col: str = "DayOfYear", y_cols: List[str] = ["ConfirmedCases", "Fatalities"], ): def predict_one(col): df[f"yhat_hybrid_{col}"] = interpolate( df[f"{y_col}_alpha"].to_numpy() , df[f"yhat_logistic_{y_col}"].to_numpy() , df[f"yhat_xgb_{y_col}"].to_numpy() , ) for y_col in y_cols: predict_one(y_col )<merge>
try: c = Client() c.configure_tpu_version(tf.__version__, restart_type='ifNeeded') tpu = tf.distribute.cluster_resolver.TPUClusterResolver() print('Running on TPU ', tpu.master()) except ValueError: tpu = None if tpu: tf.config.experimental_connect_to_cluster(tpu) tf.tpu.experimental.initialize_tpu_system(tpu) strategy = tf.distribute.TPUStrategy(tpu) else: strategy = tf.distribute.get_strategy() print("REPLICAS: ", strategy.num_replicas_in_sync )
Petals to the Metal - Flower Classification on TPU
11,172,062
train = pd.merge( train, train.groupby(["Country_Region"], observed=True, sort=False) .apply(lambda x: fit_hybrid(x)) .reset_index() , on=["Country_Region"], how="left", )<predict_on_test>
IMAGE_SIZE = [331, 331] EPOCHS_SEARCH = 10 EPOCHS_FINAL = 20 SEED = 123 BATCH_SIZE = 32 * strategy.num_replicas_in_sync
Petals to the Metal - Flower Classification on TPU
11,172,062
predict_hybrid(train )<compute_test_metric>
GCS_DS_PATH = KaggleDatasets().get_gcs_path('tpu-getting-started') GCS_PATH_SELECT = { 192: GCS_DS_PATH + '/tfrecords-jpeg-192x192', 224: GCS_DS_PATH + '/tfrecords-jpeg-224x224', 331: GCS_DS_PATH + '/tfrecords-jpeg-331x331', 512: GCS_DS_PATH + '/tfrecords-jpeg-512x512' } GCS_PATH = GCS_PATH_SELECT[IMAGE_SIZE[0]] TRAINING_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/train/*.tfrec') VALIDATION_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/val/*.tfrec') TEST_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/test/*.tfrec' )
Petals to the Metal - Flower Classification on TPU
11,172,062
print( "Confirmed: " f'Logistic\t{RMSLE(train["ConfirmedCases"], train["yhat_logistic_ConfirmedCases"])} ' f'XGBoost\t{RMSLE(train["ConfirmedCases"], train["yhat_xgb_ConfirmedCases"])} ' f'Hybrid\t{RMSLE(train["ConfirmedCases"], train["yhat_hybrid_ConfirmedCases"])} ' f"Fatalities: " f'Logistic\t{RMSLE(train["Fatalities"], train["yhat_logistic_Fatalities"])} ' f'XGBoost\t{RMSLE(train["Fatalities"], train["yhat_xgb_Fatalities"])} ' f'Hybrid\t{RMSLE(train["Fatalities"], train["yhat_hybrid_Fatalities"])} ' )<merge>
CLASSES = ['pink primrose', 'hard-leaved pocket orchid', 'canterbury bells', 'sweet pea', 'wild geranium', 'tiger lily', 'moon orchid', 'bird of paradise', 'monkshood', 'globe thistle', 'snapdragon', "colt's foot", 'king protea', 'spear thistle', 'yellow iris', 'globe-flower', 'purple coneflower', 'peruvian lily', 'balloon flower', 'giant white arum lily', 'fire lily', 'pincushion flower', 'fritillary', 'red ginger', 'grape hyacinth', 'corn poppy', 'prince of wales feathers', 'stemless gentian', 'artichoke', 'sweet william', 'carnation', 'garden phlox', 'love in the mist', 'cosmos', 'alpine sea holly', 'ruby-lipped cattleya', 'cape flower', 'great masterwort', 'siam tulip', 'lenten rose', 'barberton daisy', 'daffodil', 'sword lily', 'poinsettia', 'bolero deep blue', 'wallflower', 'marigold', 'buttercup', 'daisy', 'common dandelion', 'petunia', 'wild pansy', 'primula', 'sunflower', 'lilac hibiscus', 'bishop of llandaff', 'gaura', 'geranium', 'orange dahlia', 'pink-yellow dahlia', 'cautleya spicata', 'japanese anemone', 'black-eyed susan', 'silverbush', 'californian poppy', 'osteospermum', 'spring crocus', 'iris', 'windflower', 'tree poppy', 'gazania', 'azalea', 'water lily', 'rose', 'thorn apple', 'morning glory', 'passion flower', 'lotus', 'toad lily', 'anthurium', 'frangipani', 'clematis', 'hibiscus', 'columbine', 'desert-rose', 'tree mallow', 'magnolia', 'cyclamen ', 'watercress', 'canna lily', 'hippeastrum ', 'bee balm', 'pink quill', 'foxglove', 'bougainvillea', 'camellia', 'mallow', 'mexican petunia', 'bromelia', 'blanket flower', 'trumpet creeper', 'blackberry lily', 'common tulip', 'wild rose']
Petals to the Metal - Flower Classification on TPU
11,172,062
test = pd.merge( test, train[["Country_Region"] + ['ConfirmedCases_p_0', 'ConfirmedCases_p_1', 'ConfirmedCases_p_2']+ ['Fatalities_p_0','Fatalities_p_1', 'Fatalities_p_2'] + ["Fatalities_alpha"] + ["ConfirmedCases_alpha"]].groupby(['Country_Region'] ).head(1), on="Country_Region", how="left" )<predict_on_test>
def decode_image(image_data): image = tf.image.decode_jpeg(image_data, channels=3) image = tf.cast(image, tf.float32) image = tf.ensure_shape(image, [*IMAGE_SIZE, 3]) return image def read_labeled_tfrecord(example): LABELED_TFREC_FORMAT = { "image": tf.io.FixedLenFeature([], tf.string), "class": tf.io.FixedLenFeature([], tf.int64), } example = tf.io.parse_single_example(example, LABELED_TFREC_FORMAT) image = decode_image(example['image']) label = tf.cast(example['class'], tf.int32) return image, label def read_unlabeled_tfrecord(example): UNLABELED_TFREC_FORMAT = { "image": tf.io.FixedLenFeature([], tf.string), "id": tf.io.FixedLenFeature([], tf.string), } example = tf.io.parse_single_example(example, UNLABELED_TFREC_FORMAT) image = decode_image(example['image']) idnum = example['id'] return image, idnum def load_dataset(filenames, labeled = True, ordered = False): ignore_order = tf.data.Options() if not ordered: ignore_order.experimental_deterministic = False dataset = tf.data.TFRecordDataset(filenames, num_parallel_reads = AUTOTUNE) dataset = dataset.with_options(ignore_order) dataset = dataset.map(read_labeled_tfrecord if labeled else read_unlabeled_tfrecord, num_parallel_calls = AUTOTUNE) return dataset def one_hot_encoding(image, label, num_classes=len(CLASSES)) : return image, tf.one_hot(label, num_classes) def get_training_dataset(dataset,do_aug=True): dataset = dataset.map(one_hot_encoding, num_parallel_calls=AUTOTUNE) if do_aug: dataset = dataset.map(transform, num_parallel_calls=AUTOTUNE) dataset = dataset.repeat() dataset = dataset.shuffle(2048) dataset = dataset.batch(BATCH_SIZE, drop_remainder=True) dataset = dataset.prefetch(AUTOTUNE) return dataset def get_validation_dataset(dataset): dataset = dataset.map(one_hot_encoding, num_parallel_calls=AUTOTUNE) dataset = dataset.batch(BATCH_SIZE, drop_remainder=True) dataset = dataset.cache() dataset = dataset.prefetch(AUTOTUNE) return dataset def get_test_dataset(ordered=False): dataset = load_dataset(TEST_FILENAMES, labeled=False, ordered=ordered) dataset = dataset.batch(BATCH_SIZE, drop_remainder=False) dataset = dataset.prefetch(AUTOTUNE) return dataset def count_data_items(filenames): n = [int(re.compile(r"-([0-9]*)\." ).search(filename ).group(1)) for filename in filenames] return np.sum(n )
Petals to the Metal - Flower Classification on TPU
11,172,062
predict_logistic(test) test["yhat_xgb_ConfirmedCases"] = xgb_c_fit.predict(test[x_columns].to_numpy()) test["yhat_xgb_Fatalities"] = xgb_f_fit.predict(test[x_columns].to_numpy()) predict_hybrid(test )<prepare_output>
def get_mat(rotation, shear, height_zoom, width_zoom, height_shift, width_shift): rotation = math.pi * rotation / 180. shear = math.pi * shear / 180. c1 = tf.math.cos(rotation) s1 = tf.math.sin(rotation) one = tf.constant([1],dtype='float32') zero = tf.constant([0],dtype='float32') rotation_matrix = tf.reshape(tf.concat([c1,s1,zero, -s1,c1,zero, zero,zero,one],axis=0),[3,3]) c2 = tf.math.cos(shear) s2 = tf.math.sin(shear) shear_matrix = tf.reshape(tf.concat([one,s2,zero, zero,c2,zero, zero,zero,one],axis=0),[3,3]) zoom_matrix = tf.reshape(tf.concat([one/height_zoom,zero,zero, zero,one/width_zoom,zero, zero,zero,one],axis=0),[3,3]) shift_matrix = tf.reshape(tf.concat([one,zero,height_shift, zero,one,width_shift, zero,zero,one],axis=0),[3,3]) return K.dot(K.dot(rotation_matrix, shear_matrix), K.dot(zoom_matrix, shift_matrix))
Petals to the Metal - Flower Classification on TPU
11,172,062
submission = test[["ForecastId", "yhat_hybrid_ConfirmedCases", "yhat_hybrid_Fatalities"]].round().astype(int ).rename( columns={ "yhat_hybrid_ConfirmedCases": "ConfirmedCases", "yhat_hybrid_Fatalities": "Fatalities", } ) submission["ConfirmedCases"] = np.maximum(0, submission["ConfirmedCases"]) submission["Fatalities"] = np.maximum(0, submission["Fatalities"] )<save_to_csv>
def transform(image,label): image = tf.image.random_flip_left_right(image) DIM = IMAGE_SIZE[0] XDIM = DIM%2 rot = 15.* tf.random.normal([1],dtype='float32') shr = 5.* tf.random.normal([1],dtype='float32') h_zoom = 1.0 + tf.random.normal([1],dtype='float32')/10. w_zoom = 1.0 + tf.random.normal([1],dtype='float32')/10. h_shift = 16.* tf.random.normal([1],dtype='float32') w_shift = 16.* tf.random.normal([1],dtype='float32') m = get_mat(rot,shr,h_zoom,w_zoom,h_shift,w_shift) x = tf.repeat(tf.range(DIM//2,-DIM//2,-1), DIM) y = tf.tile(tf.range(-DIM//2,DIM//2),[DIM]) z = tf.ones([DIM*DIM],dtype='int32') idx = tf.stack([x,y,z]) idx2 = K.dot(m,tf.cast(idx,dtype='float32')) idx2 = K.cast(idx2,dtype='int32') idx2 = K.clip(idx2,-DIM//2+XDIM+1,DIM//2) idx3 = tf.stack([DIM//2-idx2[0,], DIM//2-1+idx2[1,]]) d = tf.gather_nd(image,tf.transpose(idx3)) return tf.reshape(d,[DIM,DIM,3]),label
Petals to the Metal - Flower Classification on TPU
11,172,062
submission.to_csv("submission.csv", index=False )<save_to_csv>
hm = HyperEfficientNet(input_shape=[IMAGE_SIZE[0], IMAGE_SIZE[1], 3] , classes=len(CLASSES)) hp = HyperParameters() hp.Choice('version', ['B0', 'B1', 'B2', 'B3', 'B4']) tuner = kt.tuners.randomsearch.RandomSearch( hypermodel=hm, objective='val_accuracy', max_trials=5, distribution_strategy=strategy, directory='flower_classification', project_name='randomsearch_efficientnet', hyperparameters=hp, ) tuner.search_space_summary()
Petals to the Metal - Flower Classification on TPU
11,172,062
submission.to_csv("submission.csv", index=False )<import_modules>
num_val_samples = count_data_items(VALIDATION_FILENAMES) num_train_samples = count_data_items(TRAINING_FILENAMES) train_ds = get_training_dataset(load_dataset(TRAINING_FILENAMES)) validation_ds = get_validation_dataset(load_dataset(VALIDATION_FILENAMES)) num_train_batches = num_train_samples // BATCH_SIZE num_val_batches = num_val_samples // BATCH_SIZE
Petals to the Metal - Flower Classification on TPU
11,172,062
K.set_image_data_format('channels_last') print(os.listdir(".. /input")) <load_from_csv>
tuner.search(train_ds, epochs=EPOCHS_SEARCH, validation_data=validation_ds, steps_per_epoch=num_train_batches, verbose=2 )
Petals to the Metal - Flower Classification on TPU
11,172,062
train = pd.read_csv('.. /input/train.csv') test = pd.read_csv('.. /input/test.csv') df = train.copy() df_test = test.copy()<train_model>
ds_all = get_training_dataset(load_dataset(TRAINING_FILENAMES + VALIDATION_FILENAMES)) model.fit(ds_all, epochs=EPOCHS_FINAL, steps_per_epoch=num_train_batches + num_val_batches, callbacks=[tf.keras.callbacks.ReduceLROnPlateau() ], verbose=2 )
Petals to the Metal - Flower Classification on TPU
11,172,062
print("Train: ", df.shape) print("Test: ", df_test.shape )<count_missing_values>
ds_test = get_test_dataset(ordered=True) print('Computing predictions...') predictions = [] for i,(test_img, test_id)in enumerate(ds_test): print('Processing batch ', i) probabilities = model(test_img) prediction = np.argmax(probabilities, axis=-1) predictions.append(prediction) predictions = np.concatenate(predictions) print('Number of test examples predicted: ', predictions.shape )
Petals to the Metal - Flower Classification on TPU
11,172,062
<count_missing_values><EOS>
ds_test_ids = ds_test.map(lambda image, idnum: idnum ).unbatch() test_ids = next(iter(ds_test_ids.batch(np.iinfo(np.int64 ).max)) ).numpy().astype('U') np.savetxt( 'submission.csv', np.rec.fromarrays([test_ids, predictions]), fmt=['%s', '%d'], delimiter=',', header='id,label', comments='', ) !head submission.csv
Petals to the Metal - Flower Classification on TPU
11,010,976
<SOS> metric: macrofscore Kaggle data source: petals-to-the-metal-flower-classification-on-tpu<prepare_x_and_y>
!pip install -q efficientnet
Petals to the Metal - Flower Classification on TPU
11,010,976
x = train.drop(labels = ["label"],axis = 1) y = train["label"]<split>
print("Tensorflow version " + tf.__version__ )
Petals to the Metal - Flower Classification on TPU
11,010,976
xtrain, xtest, ytrain, ytest = train_test_split(x,y, test_size = 0.2, random_state = 123) xtrain.shape, xtest.shape, ytrain.shape, ytest.shape<data_type_conversions>
AUTO = tf.data.experimental.AUTOTUNE try: tpu = tf.distribute.cluster_resolver.TPUClusterResolver() print('Running on TPU ', tpu.master()) except ValueError: tpu = None if tpu: tf.config.experimental_connect_to_cluster(tpu) tf.tpu.experimental.initialize_tpu_system(tpu) strategy = tf.distribute.experimental.TPUStrategy(tpu) else: strategy = tf.distribute.get_strategy() print("REPLICAS: ", strategy.num_replicas_in_sync) GCS_DS_PATH = KaggleDatasets().get_gcs_path()
Petals to the Metal - Flower Classification on TPU
11,010,976
xtrain = xtrain.astype("float32")/255 xtest = xtest.astype("float32")/255 test = test.astype("float32")/255 ytrain = to_categorical(ytrain, num_classes=10) ytest = to_categorical(ytest, num_classes=10 )<choose_model_class>
IMAGE_SIZE = [512, 512] EPOCHS = 20 BATCH_SIZE = 16 * strategy.num_replicas_in_sync
Petals to the Metal - Flower Classification on TPU
11,010,976
model = Sequential() model.add(Conv2D(filters = 32, kernel_size =(3,3),padding = 'Same', activation ='relu', input_shape =(28,28,1))) model.add(BatchNormalization()) model.add(Conv2D(filters = 32, kernel_size =(3,3),padding = 'Same', activation ='relu')) model.add(BatchNormalization()) model.add(MaxPool2D(pool_size=(2,2))) model.add(Dropout(0.25)) model.add(Conv2D(filters = 64, kernel_size =(3,3),padding = 'Same', activation ='relu')) model.add(BatchNormalization()) model.add(Conv2D(filters = 64, kernel_size =(3,3),padding = 'Same', activation ='relu')) model.add(BatchNormalization()) model.add(MaxPool2D(pool_size=(2,2), strides=(2,2))) model.add(Dropout(0.25)) model.add(Conv2D(filters = 64, kernel_size =(3,3), padding = 'Same', activation ='relu')) model.add(BatchNormalization()) model.add(Dropout(0.25)) model.add(Flatten()) model.add(Dense(256, activation = "relu")) model.add(BatchNormalization()) model.add(Dropout(0.25)) model.add(Dense(10, activation = "softmax"))<choose_model_class>
LR_START = 0.00001 LR_MAX = 0.00005 * strategy.num_replicas_in_sync LR_MIN = 0.00001 LR_RAMPUP_EPOCHS = 5 LR_SUSTAIN_EPOCHS = 0 LR_EXP_DECAY =.8 def lrfn(epoch): if epoch < LR_RAMPUP_EPOCHS: lr =(LR_MAX - LR_START)/ LR_RAMPUP_EPOCHS * epoch + LR_START elif epoch < LR_RAMPUP_EPOCHS + LR_SUSTAIN_EPOCHS: lr = LR_MAX else: lr =(LR_MAX - LR_MIN)* LR_EXP_DECAY**(epoch - LR_RAMPUP_EPOCHS - LR_SUSTAIN_EPOCHS)+ LR_MIN return lr lr_callback = tf.keras.callbacks.LearningRateScheduler(lrfn, verbose=True) rng = [i for i in range(EPOCHS)] y = [lrfn(x)for x in rng] plt.plot(rng, y) print("Learning rate schedule: {:.3g} to {:.3g} to {:.3g}".format(y[0], max(y), y[-1]))
Petals to the Metal - Flower Classification on TPU
11,010,976
optimizer = Adam(lr=0.001, beta_1=0.9, beta_2=0.999) model.compile(optimizer=optimizer, loss="categorical_crossentropy", metrics=["accuracy"]) model.summary()<train_model>
GCS_PATH_SELECT = { 192: GCS_DS_PATH + '/tfrecords-jpeg-192x192', 224: GCS_DS_PATH + '/tfrecords-jpeg-224x224', 331: GCS_DS_PATH + '/tfrecords-jpeg-331x331', 512: GCS_DS_PATH + '/tfrecords-jpeg-512x512' } GCS_PATH = GCS_PATH_SELECT[IMAGE_SIZE[0]] TRAINING_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/train/*.tfrec') VALIDATION_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/val/*.tfrec') TEST_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/test/*.tfrec') SKIP_VALIDATION = True if SKIP_VALIDATION: TRAINING_FILENAMES = TRAINING_FILENAMES + VALIDATION_FILENAMES VALIDATION_MISMATCHES_IDS = []
Petals to the Metal - Flower Classification on TPU
11,010,976
batch_size = 128 epochs = 50 reduce_lr = LearningRateScheduler(lambda x: 1e-3 * 0.9 ** x) history = model.fit_generator(datagen.flow(xtrain, ytrain, batch_size = batch_size), epochs = epochs, validation_data =(xtest, ytest), verbose=2, steps_per_epoch=xtrain.shape[0] // batch_size, callbacks = [reduce_lr] )<compute_test_metric>
CLASSES = ['pink primrose', 'hard-leaved pocket orchid', 'canterbury bells', 'sweet pea', 'wild geranium', 'tiger lily', 'moon orchid', 'bird of paradise', 'monkshood', 'globe thistle', 'snapdragon', "colt's foot", 'king protea', 'spear thistle', 'yellow iris', 'globe-flower', 'purple coneflower', 'peruvian lily', 'balloon flower', 'giant white arum lily', 'fire lily', 'pincushion flower', 'fritillary', 'red ginger', 'grape hyacinth', 'corn poppy', 'prince of wales feathers', 'stemless gentian', 'artichoke', 'sweet william', 'carnation', 'garden phlox', 'love in the mist', 'cosmos', 'alpine sea holly', 'ruby-lipped cattleya', 'cape flower', 'great masterwort', 'siam tulip', 'lenten rose', 'barberton daisy', 'daffodil', 'sword lily', 'poinsettia', 'bolero deep blue', 'wallflower', 'marigold', 'buttercup', 'daisy', 'common dandelion', 'petunia', 'wild pansy', 'primula', 'sunflower', 'lilac hibiscus', 'bishop of llandaff', 'gaura', 'geranium', 'orange dahlia', 'pink-yellow dahlia', 'cautleya spicata', 'japanese anemone', 'black-eyed susan', 'silverbush', 'californian poppy', 'osteospermum', 'spring crocus', 'iris', 'windflower', 'tree poppy', 'gazania', 'azalea', 'water lily', 'rose', 'thorn apple', 'morning glory', 'passion flower', 'lotus', 'toad lily', 'anthurium', 'frangipani', 'clematis', 'hibiscus', 'columbine', 'desert-rose', 'tree mallow', 'magnolia', 'cyclamen ', 'watercress', 'canna lily', 'hippeastrum ', 'bee balm', 'pink quill', 'foxglove', 'bougainvillea', 'camellia', 'mallow', 'mexican petunia', 'bromelia', 'blanket flower', 'trumpet creeper', 'blackberry lily', 'common tulip', 'wild rose']
Petals to the Metal - Flower Classification on TPU
11,010,976
model.evaluate(xtest, ytest )<compute_test_metric>
def get_mat(rotation, shear, height_zoom, width_zoom, height_shift, width_shift): rotation = math.pi * rotation / 180. shear = math.pi * shear / 180. c1 = tf.math.cos(rotation) s1 = tf.math.sin(rotation) one = tf.constant([1],dtype='float32') zero = tf.constant([0],dtype='float32') rotation_matrix = tf.reshape(tf.concat([c1,s1,zero, -s1,c1,zero, zero,zero,one],axis=0),[3,3]) c2 = tf.math.cos(shear) s2 = tf.math.sin(shear) shear_matrix = tf.reshape(tf.concat([one,s2,zero, zero,c2,zero, zero,zero,one],axis=0),[3,3]) zoom_matrix = tf.reshape(tf.concat([one/height_zoom,zero,zero, zero,one/width_zoom,zero, zero,zero,one],axis=0),[3,3]) shift_matrix = tf.reshape(tf.concat([one,zero,height_shift, zero,one,width_shift, zero,zero,one],axis=0),[3,3]) return K.dot(K.dot(rotation_matrix, shear_matrix), K.dot(zoom_matrix, shift_matrix)) def transform(image,label): DIM = IMAGE_SIZE[0] XDIM = DIM%2 rot = 15.* tf.random.normal([1],dtype='float32') shr = 5.* tf.random.normal([1],dtype='float32') h_zoom = 1.0 + tf.random.normal([1],dtype='float32')/10. w_zoom = 1.0 + tf.random.normal([1],dtype='float32')/10. h_shift = 16.* tf.random.normal([1],dtype='float32') w_shift = 16.* tf.random.normal([1],dtype='float32') m = get_mat(rot,shr,h_zoom,w_zoom,h_shift,w_shift) x = tf.repeat(tf.range(DIM//2,-DIM//2,-1), DIM) y = tf.tile(tf.range(-DIM//2,DIM//2),[DIM]) z = tf.ones([DIM*DIM],dtype='int32') idx = tf.stack([x,y,z]) idx2 = K.dot(m,tf.cast(idx,dtype='float32')) idx2 = K.cast(idx2,dtype='int32') idx2 = K.clip(idx2,-DIM//2+XDIM+1,DIM//2) idx3 = tf.stack([DIM//2-idx2[0,], DIM//2-1+idx2[1,]]) d = tf.gather_nd(image,tf.transpose(idx3)) return tf.reshape(d,[DIM,DIM,3]),label
Petals to the Metal - Flower Classification on TPU
11,010,976
model.evaluate(xtrain, ytrain )<save_to_csv>
def decode_image(image_data): image = tf.image.decode_jpeg(image_data, channels=3) image = tf.cast(image, tf.float32)/ 255.0 image = tf.reshape(image, [*IMAGE_SIZE, 3]) return image def read_labeled_tfrecord(example): LABELED_TFREC_FORMAT = { "image": tf.io.FixedLenFeature([], tf.string), "class": tf.io.FixedLenFeature([], tf.int64), } example = tf.io.parse_single_example(example, LABELED_TFREC_FORMAT) image = decode_image(example['image']) label = tf.cast(example['class'], tf.int32) return image, label def read_unlabeled_tfrecord(example): UNLABELED_TFREC_FORMAT = { "image": tf.io.FixedLenFeature([], tf.string), "id": tf.io.FixedLenFeature([], tf.string), } example = tf.io.parse_single_example(example, UNLABELED_TFREC_FORMAT) image = decode_image(example['image']) idnum = example['id'] return image, idnum def read_labeled_id_tfrecord(example): LABELED_ID_TFREC_FORMAT = { "image": tf.io.FixedLenFeature([], tf.string), "class": tf.io.FixedLenFeature([], tf.int64), "id": tf.io.FixedLenFeature([], tf.string), } example = tf.io.parse_single_example(example, LABELED_ID_TFREC_FORMAT) image = decode_image(example['image']) label = tf.cast(example['class'], tf.int32) idnum = example['id'] return image, label, idnum def load_dataset(filenames, labeled=True, ordered=False): ignore_order = tf.data.Options() if not ordered: ignore_order.experimental_deterministic = False dataset = tf.data.TFRecordDataset(filenames, num_parallel_reads=AUTO) dataset = dataset.with_options(ignore_order) dataset = dataset.map(read_labeled_id_tfrecord if labeled else read_unlabeled_tfrecord, num_parallel_calls=AUTO) return dataset def load_dataset_with_id(filenames, ordered=False): ignore_order = tf.data.Options() if not ordered: ignore_order.experimental_deterministic = False dataset = tf.data.TFRecordDataset(filenames, num_parallel_reads=AUTO) dataset = dataset.with_options(ignore_order) dataset = dataset.map(read_labeled_id_tfrecord, num_parallel_calls=AUTO) return dataset def data_augment(image, label): image = tf.image.random_flip_left_right(image) return image, label def get_training_dataset() : dataset = load_dataset(TRAINING_FILENAMES, labeled=True) dataset = dataset.filter(lambda image, label, idnum: tf.reduce_sum(tf.cast(idnum == VALIDATION_MISMATCHES_IDS, tf.int32)) ==0) dataset = dataset.map(lambda image, label, idnum: [image, label]) dataset = dataset.map(transform, num_parallel_calls=AUTO) dataset = dataset.map(data_augment, num_parallel_calls=AUTO) dataset = dataset.repeat() dataset = dataset.shuffle(2048) dataset = dataset.batch(BATCH_SIZE) dataset = dataset.prefetch(AUTO) return dataset def get_validation_dataset(ordered=False): dataset = load_dataset(VALIDATION_FILENAMES, labeled=True, ordered=ordered) dataset = dataset.filter(lambda image, label, idnum: tf.reduce_sum(tf.cast(idnum == VALIDATION_MISMATCHES_IDS, tf.int32)) ==0) dataset = dataset.map(lambda image, label, idnum: [image, label]) dataset = dataset.batch(BATCH_SIZE) dataset = dataset.cache() dataset = dataset.prefetch(AUTO) return dataset def get_validation_dataset_with_id(ordered=False): dataset = load_dataset_with_id(VALIDATION_FILENAMES, ordered=ordered) dataset = dataset.batch(BATCH_SIZE) dataset = dataset.cache() dataset = dataset.prefetch(AUTO) return dataset def get_test_dataset(ordered=False): dataset = load_dataset(TEST_FILENAMES, labeled=False, ordered=ordered) dataset = dataset.batch(BATCH_SIZE) dataset = dataset.prefetch(AUTO) return dataset def count_data_items(filenames): dataset = load_dataset(filenames,labeled = False) dataset = dataset.map(lambda image, idnum: idnum) dataset = dataset.filter(lambda idnum: tf.reduce_sum(tf.cast(idnum == VALIDATION_MISMATCHES_IDS, tf.int32)) ==0) uids = next(iter(dataset.batch(21000)) ).numpy().astype('U') return len(np.unique(uids)) NUM_TRAINING_IMAGES = count_data_items(TRAINING_FILENAMES) NUM_VALIDATION_IMAGES =(1 - SKIP_VALIDATION)* count_data_items(VALIDATION_FILENAMES) NUM_TEST_IMAGES = count_data_items(TEST_FILENAMES) STEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE print('Dataset: {} training images, {} validation images, {} unlabeled test images'.format(NUM_TRAINING_IMAGES, NUM_VALIDATION_IMAGES, NUM_TEST_IMAGES))
Petals to the Metal - Flower Classification on TPU
11,010,976
testprediction=np.argmax(model.predict(test),axis=1) testimage=[] for i in range(len(testprediction)) : testimage.append(i+1) final={'ImageId':testimage,'Label':testprediction} submission=pd.DataFrame(final) submission.to_csv('submssion.csv',index=False )<load_from_csv>
with strategy.scope() : enet = efn.EfficientNetB7( input_shape=(512, 512, 3), weights='noisy-student', include_top=False ) model = tf.keras.Sequential([ enet, tf.keras.layers.GlobalAveragePooling2D() , tf.keras.layers.Dense(len(CLASSES), activation='softmax') ]) model.compile( optimizer=tf.keras.optimizers.Adam(lr=0.0001), loss = 'sparse_categorical_crossentropy', metrics=['sparse_categorical_accuracy'] ) model.summary()
Petals to the Metal - Flower Classification on TPU
11,010,976
pd.set_option('display.max_columns', 500) pd.set_option('display.max_rows', 500) df_train = pd.read_csv('.. /input/titanic/train.csv', delimiter = ",") df_test = pd.read_csv('.. /input/titanic/test.csv', delimiter = ",") df_sub = pd.read_csv('.. /input/titanic/gender_submission.csv', delimiter = "," )<concatenate>
history = model.fit( get_training_dataset() , steps_per_epoch=STEPS_PER_EPOCH, epochs=EPOCHS, callbacks=[lr_callback], validation_data=None if SKIP_VALIDATION else get_validation_dataset() )
Petals to the Metal - Flower Classification on TPU
11,010,976
df = pd.concat([df_train, df_test],sort=False) df.reset_index(drop=True,inplace=True )<feature_engineering>
with strategy.scope() : rnet = DenseNet201( input_shape=(512, 512, 3), weights='imagenet', include_top=False ) model2 = tf.keras.Sequential([ rnet, tf.keras.layers.GlobalAveragePooling2D() , tf.keras.layers.Dense(len(CLASSES), activation='softmax') ]) model2.compile( optimizer=tf.keras.optimizers.Adam(lr=0.0001), loss = 'sparse_categorical_crossentropy', metrics=['sparse_categorical_accuracy'] ) model2.summary()
Petals to the Metal - Flower Classification on TPU
11,010,976
age60=df[(df['Age']>60)&(df['Age']<70)] age60.groupby(['Pclass','Embarked','SibSp','Parch'] ).median() df.loc[df['PassengerId'] == 1044, 'Fare'] = 7.9<feature_engineering>
history2 = model2.fit( get_training_dataset() , steps_per_epoch=STEPS_PER_EPOCH, epochs=EPOCHS, callbacks=[lr_callback], validation_data=None if SKIP_VALIDATION else get_validation_dataset() )
Petals to the Metal - Flower Classification on TPU
11,010,976
df['Fare']=np.round(df['Fare']) p01 = df['Fare'].quantile(0.01) p99 = df['Fare'].quantile(0.99) df['Fare'] = df['Fare'].clip(p01, p99 )<feature_engineering>
test_ds = get_test_dataset(ordered=True) print('Computing predictions...') test_images_ds = test_ds.map(lambda image, idnum: image) probabilities = best_alpha*model.predict(test_images_ds)+(1-best_alpha)*model2.predict(test_images_ds) predictions = np.argmax(probabilities, axis=-1) print(predictions) print('Generating submission.csv file...') test_ids_ds = test_ds.map(lambda image, idnum: idnum ).unbatch() test_ids = next(iter(test_ids_ds.batch(NUM_TEST_IMAGES)) ).numpy().astype('U') np.savetxt('submission.csv', np.rec.fromarrays([test_ids, predictions]), fmt=['%s', '%d'], delimiter=',', header='id,label', comments='' )
Petals to the Metal - Flower Classification on TPU
10,514,418
df['Farecut']=pd.cut(df['Fare'], 5, labels=False )<feature_engineering>
try: tpu = tf.distribute.cluster_resolver.TPUClusterResolver() print("Running on tpu", tpu.master()) except ValueError: tpu = None if tpu: tf.config.experimental_connect_to_cluster(tpu) tf.tpu.experimental.initialize_tpu_system(tpu) strategy = tf.distribute.experimental.TPUStrategy(tpu) else: strategy = tf.distribute.get_strategy() print("Replicas", strategy.num_replicas_in_sync )
Petals to the Metal - Flower Classification on TPU
10,514,418
column = 'mrms' df[column] = df['Name'].str.extract('([A-Za-z]+)\.', expand = False) df[column] = df[column].replace(['Capt', 'Countess','Lady','Sir','Jonkheer', 'Don','Dona', 'Mlle','Mme','Major'], 'test_non') df[column] = df[column].replace(['Ms'], 'Miss') df[column] = df[column].replace(['Col','Dr', 'Rev'], 'Other' )<drop_column>
GCS_DS_PATH = KaggleDatasets().get_gcs_path('tpu-getting-started') GCS_PATH = GCS_DS_PATH + '/tfrecords-jpeg-512x512'
Petals to the Metal - Flower Classification on TPU
10,514,418
column='Embarked' df['Embarked'].fillna('S',inplace=True )<feature_engineering>
AUTO = tf.data.experimental.AUTOTUNE IMAGE_SIZE = [512,512] EPOCHS = 12 BATCH_SIZE = 16*strategy.num_replicas_in_sync TRAINING_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/train/*.tfrec') VALIDATION_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/val/*.tfrec') TEST_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/test/*.tfrec' )
Petals to the Metal - Flower Classification on TPU
10,514,418
df.loc[df['Parch'] >= 3, 'Parch'] = 3 df.loc[df['SibSp'] >= 3, 'SibSp'] = 3<feature_engineering>
def count_data_items(filenames): n = [int(re.compile(r"-([0-9]*)\." ).search(filename ).group(1)) for filename in filenames] return np.sum(n)
Petals to the Metal - Flower Classification on TPU
10,514,418
df['Parch+SibSp']=df['Parch']+df['SibSp']<feature_engineering>
NUM_TRAINING_IMAGES = count_data_items(TRAINING_FILENAMES) NUM_VALIDATION_IMAGES = count_data_items(VALIDATION_FILENAMES) NUM_TEST_IMAGES = count_data_items(TEST_FILENAMES) print('Dataset: {} training images, {} validation images, {} unlabeled test images'.format(NUM_TRAINING_IMAGES, NUM_VALIDATION_IMAGES, NUM_TEST_IMAGES))
Petals to the Metal - Flower Classification on TPU
10,514,418
df['Parch-SibSp']=df['Parch']-df['SibSp']<feature_engineering>
def decode_image(image_data): image = tf.image.decode_jpeg(image_data, channels = 3) image = tf.cast(image, tf.float32)/255.0 image = tf.reshape(image, [*IMAGE_SIZE, 3]) return image def read_labeled_tfrecord(example): LABELED_TFREC_FORMAT = { "image": tf.io.FixedLenFeature([], tf.string), "class": tf.io.FixedLenFeature([], tf.int64) } example = tf.io.parse_single_example(example, LABELED_TFREC_FORMAT) image = decode_image(example['image']) label = tf.cast(example['class'], tf.int32) return image,label def read_unlabeled_tfrecord(example): UNLABELED_TFREC_FORMAT = { "image": tf.io.FixedLenFeature([], tf.string), "id": tf.io.FixedLenFeature([], tf.string) } example = tf.io.parse_single_example(example, UNLABELED_TFREC_FORMAT) image = decode_image(example['image']) idnum = example['id'] return image,idnum
Petals to the Metal - Flower Classification on TPU
10,514,418
l=list(['Pclass','SibSp','Fare','Parch']) df['Agemedian'] = df['Age'].fillna(df.groupby(l)['Age'].transform('median')) df['Agemedian'] = df['Agemedian'].fillna(df['Agemedian'].median()) df['Agemedian'] = np.round(df['Agemedian'] )<feature_engineering>
def load_dataset(filenames, labeled = True, ordered = False): ignore_order = tf.data.Options() if not ordered: ignore_order.experimental_deterministic = False dataset = tf.data.TFRecordDataset(filenames, num_parallel_reads = AUTO) dataset = dataset.with_options(ignore_order) dataset = dataset.map(read_labeled_tfrecord if labeled else read_unlabeled_tfrecord, num_parallel_calls = AUTO) return dataset def data_augment(image,label): image = tf.image.random_flip_left_right(image) image = tf.image.random_saturation(image, 0, 2) return image,label def get_training_dataset() : dataset = load_dataset(TRAINING_FILENAMES, labeled = True) dataset = dataset.map(data_augment, num_parallel_calls = AUTO) dataset = dataset.repeat() dataset = dataset.shuffle(2048) dataset = dataset.batch(BATCH_SIZE) dataset = dataset.prefetch(AUTO) return dataset def get_validation_dataset(ordered= False): dataset = load_dataset(VALIDATION_FILENAMES, labeled = True, ordered = ordered) dataset = dataset.batch(BATCH_SIZE) dataset = dataset.cache() dataset = dataset.prefetch(AUTO) return dataset def get_test_dataset(ordered = False): dataset = load_dataset(TEST_FILENAMES, labeled = False, ordered= ordered) dataset = dataset.batch(BATCH_SIZE) dataset = dataset.prefetch(AUTO) return dataset
Petals to the Metal - Flower Classification on TPU
10,514,418
column = 'Cabin' df[column+'head'] = df[column].str.extract('([A-Za-z]+)', expand = False) labels, uniques = pd.factorize(df['Cabinhead']) df['Cabinhead']=labels df['Cabinhead'].fillna(0,inplace=True) df['Cabinhead'].replace(-1,np.NaN,inplace=True) Ticket = df['Ticket'].str.extract(' (.*)\s (.*)') df['Ticket_head']=Ticket[0] df['Ticket_num']=Ticket[1] l = list(['Pclass','Farecut']) df['Cabinheadmedian'] = df['Cabinhead'].fillna(df.groupby(l)['Cabinhead'].transform('median')) df['Cabinheadmedian'] = np.round(df['Cabinheadmedian'] )<categorify>
ds_train = get_training_dataset() ds_val = get_validation_dataset() ds_test = get_test_dataset() print("Training", ds_train) print("Validation", ds_val) print("Test", ds_test)
Petals to the Metal - Flower Classification on TPU
10,514,418
l = list(['Farecut']) df['Cabinheadmedian'] = df['Cabinhead'].fillna(df.groupby(l)['Cabinhead'].transform('median'))<categorify>
CLASSES = ['pink primrose', 'hard-leaved pocket orchid', 'canterbury bells', 'sweet pea', 'wild geranium', 'tiger lily', 'moon orchid', 'bird of paradise', 'monkshood', 'globe thistle', 'snapdragon', "colt's foot", 'king protea', 'spear thistle', 'yellow iris', 'globe-flower', 'purple coneflower', 'peruvian lily', 'balloon flower', 'giant white arum lily', 'fire lily', 'pincushion flower', 'fritillary', 'red ginger', 'grape hyacinth', 'corn poppy', 'prince of wales feathers', 'stemless gentian', 'artichoke', 'sweet william', 'carnation', 'garden phlox', 'love in the mist', 'cosmos', 'alpine sea holly', 'ruby-lipped cattleya', 'cape flower', 'great masterwort', 'siam tulip', 'lenten rose', 'barberton daisy', 'daffodil', 'sword lily', 'poinsettia', 'bolero deep blue', 'wallflower', 'marigold', 'buttercup', 'daisy', 'common dandelion', 'petunia', 'wild pansy', 'primula', 'sunflower', 'lilac hibiscus', 'bishop of llandaff', 'gaura', 'geranium', 'orange dahlia', 'pink-yellow dahlia', 'cautleya spicata', 'japanese anemone', 'black-eyed susan', 'silverbush', 'californian poppy', 'osteospermum', 'spring crocus', 'iris', 'windflower', 'tree poppy', 'gazania', 'azalea', 'water lily', 'rose', 'thorn apple', 'morning glory', 'passion flower', 'lotus', 'toad lily', 'anthurium', 'frangipani', 'clematis', 'hibiscus', 'columbine', 'desert-rose', 'tree mallow', 'magnolia', 'cyclamen ', 'watercress', 'canna lily', 'hippeastrum ', 'bee balm', 'pink quill', 'foxglove', 'bougainvillea', 'camellia', 'mallow', 'mexican petunia', 'bromelia', 'blanket flower', 'trumpet creeper', 'blackberry lily', 'common tulip', 'wild rose']
Petals to the Metal - Flower Classification on TPU
10,514,418
for column in ['mrms','Sex','Embarked','Ticket_head']: labels, uniques = pd.factorize(df[column]) df[column]=labels<drop_column>
print("Number of classes: {}".format(len(CLASSES))) print("First five classes, sorted alphabetically:") for name in sorted(CLASSES)[:5]: print(name) print("number of training images: {}".format(NUM_TRAINING_IMAGES))
Petals to the Metal - Flower Classification on TPU
10,514,418
df = df.drop(['Name','Ticket','Cabin','Cabinhead','Age','Fare','Ticket_num'], axis=1 )<import_modules>
print("Training data shapes") for image,label in ds_train.take(3): print(image.numpy().shape, label.numpy().shape) print("training data label examples:", label.numpy() )
Petals to the Metal - Flower Classification on TPU
10,514,418
import operator import math import random from deap import gp from deap import algorithms from deap import base from deap import creator from deap import tools<define_variables>
print("Test data shapes") for image,idnum in ds_test.take(3): print(image.numpy().shape, idnum.numpy().shape) print("test data IDs", idnum.numpy().astype('U'))
Petals to the Metal - Flower Classification on TPU
10,514,418
train=df<prepare_x_and_y>
one_batch = next(iter(ds_train.unbatch().batch(20))) display_batch_of_images(one_batch )
Petals to the Metal - Flower Classification on TPU
10,514,418
target = train['Survived']<define_search_model>
LR_START = 0.00001 LR_MAX = 0.00005 * strategy.num_replicas_in_sync LR_MIN = LR_START LR_RAMPUP_EPOCHS = 5 LR_SUSTAIN_EPOCHS = 0 LR_EXP_DECAY = 0.80 def lrfn(epoch): if epoch < LR_RAMPUP_EPOCHS: lr = LR_START +(epoch *(LR_MAX - LR_START)/ LR_RAMPUP_EPOCHS) elif epoch <(LR_RAMPUP_EPOCHS + LR_SUSTAIN_EPOCHS): lr = LR_MAX else: lr = LR_MIN +(LR_MAX - LR_MIN)* LR_EXP_DECAY **(epoch - LR_RAMPUP_EPOCHS - LR_SUSTAIN_EPOCHS) return lr lr_callback = tf.keras.callbacks.LearningRateScheduler(lrfn, verbose = True) rng = [i for i in range(30)] y = [lrfn(x)for x in rng] plt.plot(rng, y )
Petals to the Metal - Flower Classification on TPU
10,514,418
def mydeap(mungedtrain): inputs = mungedtrain.iloc[:,2:14].values.tolist() outputs = mungedtrain['Survived'].values.tolist() def protectedDiv(left, right): try: return left / right except ZeroDivisionError: return 1 pset = gp.PrimitiveSet("MAIN", 12) pset.addPrimitive(operator.add, 2) pset.addPrimitive(operator.sub, 2) pset.addPrimitive(operator.mul, 2) pset.addPrimitive(protectedDiv, 2) pset.addPrimitive(operator.neg, 1) pset.addPrimitive(math.cos, 1) pset.addPrimitive(math.sin, 1) pset.addPrimitive(max, 2) pset.addPrimitive(min, 2) pset.addEphemeralConstant("rand101", lambda: random.uniform(-10,10)) pset.renameArguments(ARG0='x1') pset.renameArguments(ARG1='x2') pset.renameArguments(ARG2='x3') pset.renameArguments(ARG3='x4') pset.renameArguments(ARG4='x5') pset.renameArguments(ARG5='x6') pset.renameArguments(ARG6='x7') pset.renameArguments(ARG7='x8') pset.renameArguments(ARG8='x9') pset.renameArguments(ARG9='x10') pset.renameArguments(ARG10='x11') pset.renameArguments(ARG11='x12') creator.create("FitnessMin", base.Fitness, weights=(1.0,)) creator.create("Individual", gp.PrimitiveTree, fitness=creator.FitnessMin) toolbox = base.Toolbox() toolbox.register("expr", gp.genHalfAndHalf, pset=pset, min_=1, max_=3) toolbox.register("individual", tools.initIterate, creator.Individual, toolbox.expr) toolbox.register("population", tools.initRepeat, list, toolbox.individual) toolbox.register("compile", gp.compile, pset=pset) def evalSymbReg(individual): func = toolbox.compile(expr=individual) return sum(round(1.-(1./(1.+numpy.exp(-func(*in_)))))== out for in_, out in zip(inputs, outputs)) /len(mungedtrain), toolbox.register("evaluate", evalSymbReg) toolbox.register("select", tools.selTournament, tournsize=3) toolbox.register("mate", gp.cxOnePoint) toolbox.register("expr_mut", gp.genFull, min_=0, max_=2) toolbox.register("mutate", gp.mutUniform, expr=toolbox.expr_mut, pset=pset) toolbox.decorate("mate", gp.staticLimit(key=operator.attrgetter("height"), max_value=17)) toolbox.decorate("mutate", gp.staticLimit(key=operator.attrgetter("height"), max_value=17)) random.seed(318) pop = toolbox.population(n=300) hof = tools.HallOfFame(1) stats_fit = tools.Statistics(lambda ind: ind.fitness.values) stats_size = tools.Statistics(len) mstats = tools.MultiStatistics(fitness=stats_fit, size=stats_size) mstats.register("avg", numpy.mean) mstats.register("std", numpy.std) mstats.register("min", numpy.min) mstats.register("max", numpy.max) pop, log = algorithms.eaSimple(pop, toolbox, 0.5, 0.2, 1000, stats=mstats, halloffame=hof, verbose=True) print(hof[0]) func2 =toolbox.compile(expr=hof[0]) return func2<save_to_csv>
early_stop = tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience=20, restore_best_weights = True )
Petals to the Metal - Flower Classification on TPU
10,514,418
if __name__ == "__main__": mungedtrain = train[:df_train.shape[0]] GeneticFunction = mydeap(mungedtrain) mytrain = mungedtrain.iloc[:,2:14].values.tolist() trainPredictions = Outputs(np.array([GeneticFunction(*x)for x in mytrain])) pdtrain = pd.DataFrame({'PassengerId': mungedtrain.PassengerId.astype(int), 'Predicted': trainPredictions.astype(int), 'Survived': mungedtrain.Survived.astype(int)}) pdtrain.to_csv('MYgptrain.csv', index=False )<save_to_csv>
!pip install -q efficientnet
Petals to the Metal - Flower Classification on TPU
10,514,418
print(accuracy_score(df_train.Survived.astype(int),trainPredictions.astype(int))) mungedtest = train[df_train.shape[0]:] mytest = mungedtest.iloc[:,2:14].values.tolist() testPredictions = Outputs(np.array([GeneticFunction(*x)for x in mytest])) pdtest = pd.DataFrame({'PassengerId': mungedtest.PassengerId.astype(int), 'Survived': testPredictions.astype(int)}) pdtest.to_csv('gptest.csv', index=False )<train_model>
with strategy.scope() : pretrained_model = efficientnet.EfficientNetB7( weights = 'noisy-student', include_top = False, input_shape = [*IMAGE_SIZE, 3] ) pretrained_model.trainable = True model = tf.keras.Sequential([ pretrained_model, tf.keras.layers.GlobalAveragePooling2D() , tf.keras.layers.Dense(len(CLASSES),activation = 'softmax') ]) model.compile( optimizer = 'adam', loss = 'sparse_categorical_crossentropy', metrics = ['sparse_categorical_accuracy'], ) model.summary()
Petals to the Metal - Flower Classification on TPU
10,514,418
print('end' )<import_modules>
BATCH_SIZE = 16*strategy.num_replicas_in_sync EPOCHS = 11 STEPS_PER_EPOCH = NUM_TRAINING_IMAGES//BATCH_SIZE history = model.fit( ds_train, validation_data = ds_val, epochs = EPOCHS, steps_per_epoch = STEPS_PER_EPOCH, callbacks = [lr_callback, early_stop] )
Petals to the Metal - Flower Classification on TPU
10,514,418
import numpy as np import pandas as pd<load_from_csv>
cmdataset = get_validation_dataset(ordered = True) images_ds = cmdataset.map(lambda image,label:image) labels_ds = cmdataset.map(lambda image,label:label ).unbatch() cm_correct_labels = next(iter(labels_ds.batch(NUM_VALIDATION_IMAGES)) ).numpy() cm_probabilites = model.predict(images_ds) cm_predictions = np.argmax(cm_probabilites, axis = -1) labels = range(len(CLASSES)) cmat = confusion_matrix( cm_correct_labels, cm_predictions, labels = labels, ) cmat =(cmat.T/cmat.sum(axis=1)).T
Petals to the Metal - Flower Classification on TPU
10,514,418
sample_submission = pd.read_csv('.. /input/titanic/gender_submission.csv') test = pd.read_csv('.. /input/titanic/test.csv') train = pd.read_csv('.. /input/titanic/train.csv' )<count_values>
score = f1_score( cm_correct_labels, cm_predictions, labels = labels, average= 'macro', ) precision = precision_score( cm_correct_labels, cm_predictions, labels = labels, average = 'macro', ) recall = recall_score( cm_correct_labels, cm_predictions, labels = labels, average = 'macro', ) display_confusion_matrix(cmat,score,precision,recall )
Petals to the Metal - Flower Classification on TPU
10,514,418
train['Survived'].value_counts(dropna=False )<split>
dataset = get_validation_dataset() dataset = dataset.unbatch().batch(20) batch = iter(dataset)
Petals to the Metal - Flower Classification on TPU
10,514,418
kf = model_selection.StratifiedKFold(n_splits=5) x = list(kf.split(train, train['Survived'].values))<define_variables>
images,labels = next(batch) probabilites = model.predict(images) predictions = np.argmax(probabilites, axis = -1) display_batch_of_images(( images,labels), predictions )
Petals to the Metal - Flower Classification on TPU
10,514,418
[len(i)for i in x]<concatenate>
test_ds = get_test_dataset(ordered = True) print("Computing predictions for test set") test_images_ds = test_ds.map(lambda image,idnum: image) probabilities = model.predict(test_images_ds) predictions = np.argmax(probabilities, axis = -1) print(predictions)
Petals to the Metal - Flower Classification on TPU
10,514,418
all_data = train.append(test, sort=True ).fillna({'Survived': -1}) len(train), len(test), len(all_data )<groupby>
print('Generating submision file') test_ids_ds = test_ds.map(lambda image,idnum: idnum ).unbatch() test_ids = next(iter(test_ids_ds.batch(NUM_TEST_IMAGES)) ).numpy().astype('U') np.savetxt( "submission.csv", np.rec.fromarrays([test_ids, predictions]), fmt = ['%s', '%d'], delimiter = ',', header = 'id,label', comments = '', ) !head submission.csv
Petals to the Metal - Flower Classification on TPU
10,757,160
def count_na(series): return series.isna().sum() agg_funcs =('nunique', count_na) dv = 'Survived' summary_df = all_data.aggregate(agg_funcs, dropna=False ).transpose() for dv_val in all_data[dv].unique() : dv_val_data =( all_data .loc[lambda df: df[dv] == dv_val] .aggregate(agg_funcs, dropna=False ).transpose() ) summary_df[pd.MultiIndex.from_product([[f'{dv}_{dv_val}'], dv_val_data.columns])] = dv_val_data summary_df['dtypes'] = all_data.dtypes summary_df['cardinality'] = np.where(summary_df['nunique'] > 20, 'many', 'few') summary_df = summary_df.sort_values(['dtypes', 'nunique'] ).drop(dv) summary_df<count_duplicates>
!pip install efficientnet print("Tensorflow version " + tf.__version__)
Petals to the Metal - Flower Classification on TPU
10,757,160
for _, row in summary_df[['dtypes', 'cardinality']].drop_duplicates().iterrows() : print( f"{row['dtypes']} {row['cardinality']}:", summary_df.loc[ lambda df:(df['dtypes'] == row['dtypes'])&(df['cardinality'] == row['cardinality']) ].index.tolist() , )<load_from_csv>
AUTO = tf.data.experimental.AUTOTUNE AUTO
Petals to the Metal - Flower Classification on TPU
10,757,160
train_df = pd.read_csv('/kaggle/input/titanic/train.csv' )<load_from_csv>
tpu = tf.distribute.cluster_resolver.TPUClusterResolver() tf.config.experimental_connect_to_cluster(tpu) tf.tpu.experimental.initialize_tpu_system(tpu) strategy = tf.distribute.experimental.TPUStrategy(tpu)
Petals to the Metal - Flower Classification on TPU
10,757,160
test_df = pd.read_csv('/kaggle/input/titanic/test.csv') test_df.head()<filter>
IMAGE_SIZE = [512, 512] EPOCHS = 30 BATCH_SIZE = 32 * strategy.num_replicas_in_sync LEARNING_RATE = 1e-3 TTA_NUM = 5
Petals to the Metal - Flower Classification on TPU
10,757,160
women = train_df[train_df['Sex'] == 'female']['Survived'] sum(women)/len(women)* 100<filter>
GCS_DS_PATH = KaggleDatasets().get_gcs_path('tpu-getting-started' )
Petals to the Metal - Flower Classification on TPU
10,757,160
men = train_df[train_df['Sex'] == 'male']['Survived'] sum(men)/len(men)* 100<count_values>
GCS_PATH_SELECT = { 192: GCS_DS_PATH + '/tfrecords-jpeg-192x192', 224: GCS_DS_PATH + '/tfrecords-jpeg-224x224', 331: GCS_DS_PATH + '/tfrecords-jpeg-331x331', 512: GCS_DS_PATH + '/tfrecords-jpeg-512x512' } GCS_PATH = GCS_PATH_SELECT[IMAGE_SIZE[0]] TRAINING_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/train/*.tfrec') VALIDATION_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/val/*.tfrec') TEST_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/test/*.tfrec' )
Petals to the Metal - Flower Classification on TPU
10,757,160
train_df['SibSp'].value_counts()<save_to_csv>
SKIP_VALIDATION = True if SKIP_VALIDATION: TRAINING_FILENAMES = TRAINING_FILENAMES + VALIDATION_FILENAMES
Petals to the Metal - Flower Classification on TPU
10,757,160
y = train_df['Survived'] features = ["Sex", "Pclass", "SibSp", "Parch"] X = pd.get_dummies(train_df[features]) X_test = pd.get_dummies(test_df[features]) model = RandomForestClassifier(n_estimators=100, max_depth=5, random_state=1) model.fit(X, y) predictions = model.predict(X_test) output = pd.DataFrame({'PassengerId': test_df.PassengerId, 'Survived': predictions}) output.to_csv('my_submission.csv', index=False) print("Your submission was successfully saved!" )<count_values>
CLASSES = ['pink primrose', 'hard-leaved pocket orchid', 'canterbury bells', 'sweet pea', 'wild geranium', 'tiger lily', 'moon orchid', 'bird of paradise', 'monkshood', 'globe thistle', 'snapdragon', "colt's foot", 'king protea', 'spear thistle', 'yellow iris', 'globe-flower', 'purple coneflower', 'peruvian lily', 'balloon flower', 'giant white arum lily', 'fire lily', 'pincushion flower', 'fritillary', 'red ginger', 'grape hyacinth', 'corn poppy', 'prince of wales feathers', 'stemless gentian', 'artichoke', 'sweet william', 'carnation', 'garden phlox', 'love in the mist', 'cosmos', 'alpine sea holly', 'ruby-lipped cattleya', 'cape flower', 'great masterwort', 'siam tulip', 'lenten rose', 'barberton daisy', 'daffodil', 'sword lily', 'poinsettia', 'bolero deep blue', 'wallflower', 'marigold', 'buttercup', 'daisy', 'common dandelion', 'petunia', 'wild pansy', 'primula', 'sunflower', 'lilac hibiscus', 'bishop of llandaff', 'gaura', 'geranium', 'orange dahlia', 'pink-yellow dahlia', 'cautleya spicata', 'japanese anemone', 'black-eyed susan', 'silverbush', 'californian poppy', 'osteospermum', 'spring crocus', 'iris', 'windflower', 'tree poppy', 'gazania', 'azalea', 'water lily', 'rose', 'thorn apple', 'morning glory', 'passion flower', 'lotus', 'toad lily', 'anthurium', 'frangipani', 'clematis', 'hibiscus', 'columbine', 'desert-rose', 'tree mallow', 'magnolia', 'cyclamen ', 'watercress', 'canna lily', 'hippeastrum ', 'bee balm', 'pink quill', 'foxglove', 'bougainvillea', 'camellia', 'mallow', 'mexican petunia', 'bromelia', 'blanket flower', 'trumpet creeper', 'blackberry lily', 'common tulip', 'wild rose'] print(f"No of Flower classes in dataset: {len(CLASSES)}" )
Petals to the Metal - Flower Classification on TPU
10,757,160
train_df['Survived'].value_counts()<sort_values>
LR_START = 0.00001 LR_MAX = 0.00005 * strategy.num_replicas_in_sync LR_MIN = 0.00001 LR_RAMPUP_EPOCHS = 5 LR_SUSTAIN_EPOCHS = 0 LR_EXP_DECAY =.7 def lrfn(epoch): if epoch < LR_RAMPUP_EPOCHS: lr =(LR_MAX - LR_START)/ LR_RAMPUP_EPOCHS * epoch + LR_START elif epoch < LR_RAMPUP_EPOCHS + LR_SUSTAIN_EPOCHS: lr = LR_MAX else: lr =(LR_MAX - LR_MIN)* LR_EXP_DECAY**(epoch - LR_RAMPUP_EPOCHS - LR_SUSTAIN_EPOCHS)+ LR_MIN return lr lr_callback = tf.keras.callbacks.LearningRateScheduler(lrfn, verbose=True) rng = [i for i in range(EPOCHS)] y = [lrfn(x)for x in rng] plt.plot(rng, y) print("Learning rate schedule: {:.3g} to {:.3g} to {:.3g}".format(y[0], max(y), y[-1]))
Petals to the Metal - Flower Classification on TPU
10,757,160
train_df[['Pclass','Survived']].groupby(['Pclass'], as_index=False ).mean().sort_values(by='Survived', ascending='False' )<sort_values>
def decode_image(image_data): image = tf.image.decode_jpeg(image_data, channels=3) image = tf.cast(image, tf.float32)/ 255.0 image = tf.reshape(image, [*IMAGE_SIZE, 3]) return image def read_labeled_tfrecord(example): LABELED_TFREC_FORMAT = { "image": tf.io.FixedLenFeature([], tf.string), "class": tf.io.FixedLenFeature([], tf.int64), } example = tf.io.parse_single_example(example, LABELED_TFREC_FORMAT) image = decode_image(example['image']) label = tf.cast(example['class'], tf.int32) return image, label def read_unlabeled_tfrecord(example): UNLABELED_TFREC_FORMAT = { "image": tf.io.FixedLenFeature([], tf.string), "id": tf.io.FixedLenFeature([], tf.string), } example = tf.io.parse_single_example(example, UNLABELED_TFREC_FORMAT) image = decode_image(example['image']) idnum = example['id'] return image, idnum def data_augment(image, label, seed=2020): image = tf.image.random_flip_left_right(image, seed=seed) return image, label def get_training_dataset() : dataset = load_dataset(TRAINING_FILENAMES, labeled=True) dataset = dataset.map(data_augment, num_parallel_calls=AUTO) dataset = dataset.repeat() dataset = dataset.shuffle(2048) dataset = dataset.batch(BATCH_SIZE) dataset = dataset.prefetch(AUTO) return dataset def get_validation_dataset(ordered=False): dataset = load_dataset(VALIDATION_FILENAMES, labeled=True, ordered=ordered) dataset = dataset.batch(BATCH_SIZE) dataset = dataset.cache() dataset = dataset.prefetch(AUTO) return dataset def get_train_valid_datasets() : dataset = load_dataset(TRAINING_FILENAMES + VALIDATION_FILENAMES, labeled=True) dataset = dataset.map(data_augment, num_parallel_calls=AUTO) dataset = dataset.repeat() dataset = dataset.shuffle(2048) dataset = dataset.batch(BATCH_SIZE) dataset = dataset.prefetch(AUTO) return dataset def get_test_dataset(ordered=False): dataset = load_dataset(TEST_FILENAMES, labeled=False, ordered=ordered) dataset = dataset.batch(BATCH_SIZE) dataset = dataset.prefetch(AUTO) return dataset def count_data_items(filenames): n = [int(re.compile(r"-([0-9]*)\." ).search(filename ).group(1)) for filename in filenames] return np.sum(n )
Petals to the Metal - Flower Classification on TPU
10,757,160
train_df[['Sex','Survived']].groupby(['Sex'], as_index=False ).mean().sort_values(by='Survived', ascending='False' )<sort_values>
models = [] histories = []
Petals to the Metal - Flower Classification on TPU
10,757,160
train_df[['SibSp','Survived']].groupby(['SibSp'], as_index=False ).mean().sort_values(by='Survived', ascending='False' )<sort_values>
NUM_TRAINING_IMAGES = count_data_items(TRAINING_FILENAMES) NUM_VALIDATION_IMAGES = count_data_items(VALIDATION_FILENAMES) NUM_TEST_IMAGES = count_data_items(TEST_FILENAMES) STEPS_PER_EPOCH =(NUM_TRAINING_IMAGES + NUM_VALIDATION_IMAGES)// BATCH_SIZE print('Dataset: {} training images, {} unlabeled test images'.format(NUM_TRAINING_IMAGES+NUM_VALIDATION_IMAGES, NUM_TEST_IMAGES))
Petals to the Metal - Flower Classification on TPU
10,757,160
train_df[['Parch','Survived']].groupby(['Parch'], as_index=False ).mean().sort_values(by='Survived', ascending='False' )<sort_values>
def load_dataset(filenames, labeled=True, ordered=False): ignore_order = tf.data.Options() if not ordered: ignore_order.experimental_deterministic = False dataset = tf.data.TFRecordDataset(filenames, num_parallel_reads=AUTO) dataset = dataset.with_options(ignore_order) dataset = dataset.map(read_labeled_tfrecord if labeled else read_unlabeled_tfrecord, num_parallel_calls=AUTO) return dataset def get_training_dataset_preview(ordered=True): dataset = load_dataset(TRAINING_FILENAMES, labeled=True, ordered=ordered) dataset = dataset.batch(BATCH_SIZE) dataset = dataset.cache() dataset = dataset.prefetch(AUTO) return dataset np.set_printoptions(threshold=15, linewidth=80) def batch_to_numpy_images_and_labels(data): images, labels = data numpy_images = images.numpy() numpy_labels = labels.numpy() if numpy_labels.dtype == object: numpy_labels = [None for _ in enumerate(numpy_images)] return numpy_images, numpy_labels def title_from_label_and_target(label, correct_label): if correct_label is None: return CLASSES[label], True correct =(label == correct_label) return "{} [{}{}{}]".format(CLASSES[label], 'OK' if correct else 'NO', u"\u2192" if not correct else '', CLASSES[correct_label] if not correct else ''), correct def dataset_to_numpy_util(dataset, N): dataset = dataset.unbatch().batch(N) for images, labels in dataset: numpy_images = images.numpy() numpy_labels = labels.numpy() break; return numpy_images, numpy_labels
Petals to the Metal - Flower Classification on TPU
10,757,160
train_df[['Embarked','Survived']].groupby(['Embarked'], as_index=False ).mean().sort_values(by='Survived', ascending='False' )<feature_engineering>
train_dataset = get_training_dataset_preview(ordered=True) y_train = next(iter(train_dataset.unbatch().map(lambda image, label: label ).batch(NUM_TRAINING_IMAGES)) ).numpy() print('Number of training images %d' % NUM_TRAINING_IMAGES)
Petals to the Metal - Flower Classification on TPU
10,757,160
for dataset in combine: dataset['Title'] = dataset.Name.str.extract('([A-Za-z]+)\.', expand=False) pd.crosstab(train_df['Title'], train_df['Sex'] )<feature_engineering>
display_batch_of_images(next(iter(train_dataset.unbatch().batch(20))))
Petals to the Metal - Flower Classification on TPU
10,757,160
for dataset in combine: dataset['Title'] = dataset['Title'].replace(['Lady', 'Countess','Capt', 'Col', 'Don', 'Dr', 'Major', 'Rev', 'Sir', 'Jonkheer', 'Dona'], 'Rare') dataset['Title'] = dataset['Title'].replace('Mlle', 'Miss') dataset['Title'] = dataset['Title'].replace('Ms', 'Miss') dataset['Title'] = dataset['Title'].replace('Mme', 'Mrs') train_df[['Title', 'Survived']].groupby(['Title'], as_index=False ).mean()<categorify>
test_dataset = get_test_dataset() test_dataset = test_dataset.unbatch().batch(20) test_batch = iter(test_dataset)
Petals to the Metal - Flower Classification on TPU
10,757,160
title_mapping = {"Mr": 1, "Miss": 2, "Mrs": 3, "Master": 4, "Rare": 5} for dataset in combine: dataset['Title'] = dataset['Title'].map(title_mapping) dataset['Title'] = dataset['Title'].fillna(0) train_df.head()<drop_column>
def create_model() : pretrained_model = tf.keras.applications.Xception(input_shape=(IMAGE_SIZE[0],IMAGE_SIZE[1],3),weights='imagenet',include_top=False) pretrained_model.trainable = True model = tf.keras.Sequential([ pretrained_model, tf.keras.layers.GlobalAveragePooling2D(name="Layer1"), tf.keras.layers.Dropout(0.4), tf.keras.layers.Dense(len(CLASSES), activation='softmax') ]) model.compile( optimizer=tf.keras.optimizers.Adam(lr=0.0001), loss = 'sparse_categorical_crossentropy', metrics=['categorical_accuracy'] ) return model
Petals to the Metal - Flower Classification on TPU
10,757,160
train_df = train_df.drop(['Name', 'PassengerId'], axis=1) test_df = test_df.drop(['Name'], axis=1) combine = [train_df, test_df] train_df.shape, test_df.shape<data_type_conversions>
with strategy.scope() : Xception_model = create_model() Xception_model.summary()
Petals to the Metal - Flower Classification on TPU
10,757,160
for dataset in combine: dataset['Sex'] = dataset['Sex'].map({'female': 1, 'male': 0} ).astype(int) train_df.head()<define_variables>
%%time Checkpoint=tf.keras.callbacks.ModelCheckpoint(f"xception_model.h5", monitor='val_accuracy', verbose=1, save_best_only=True, save_weights_only=True,mode='max') Xception_history1 = Xception_model.fit( get_training_dataset() , steps_per_epoch=STEPS_PER_EPOCH, epochs=EPOCHS, callbacks=[lr_callback, Checkpoint]) histories.append(Xception_history1 )
Petals to the Metal - Flower Classification on TPU
10,757,160
guess_ages = np.zeros(( 2,3)) guess_ages<find_best_params>
with strategy.scope() : enet = efn.EfficientNetB7( input_shape=(IMAGE_SIZE[0], IMAGE_SIZE[1], 3), weights='imagenet', include_top=False ) enet.trainable = True model1 = tf.keras.Sequential([ enet, tf.keras.layers.GlobalMaxPooling2D(name="Layer1"), tf.keras.layers.Dropout(0.4), tf.keras.layers.Dense(len(CLASSES), activation='softmax') ]) model1.compile( optimizer=tf.keras.optimizers.Adam(lr=0.0001), loss = 'sparse_categorical_crossentropy', metrics=['categorical_accuracy'] ) model1.summary() models.append(model1 )
Petals to the Metal - Flower Classification on TPU
10,757,160
for dataset in combine: for i in range(0, 2): for j in range(0, 3): guess_df = dataset[(dataset['Sex'] == i)& \ (dataset['Pclass'] == j+1)]['Age'].dropna() age_guess = guess_df.median() guess_ages[i,j] = int(age_guess/0.5 + 0.5)* 0.5 for i in range(0, 2): for j in range(0, 3): dataset.loc[(dataset.Age.isnull())&(dataset.Sex == i)&(dataset.Pclass == j+1),\ 'Age'] = guess_ages[i,j] dataset['Age'] = dataset['Age'].astype(int) train_df.head()<sort_values>
%%time Checkpoint=tf.keras.callbacks.ModelCheckpoint(f"Enet_model.h5", monitor='val_accuracy', verbose=1, save_best_only=True, save_weights_only=True,mode='max') train_history1 = model1.fit( get_training_dataset() , steps_per_epoch=STEPS_PER_EPOCH, epochs=EPOCHS, callbacks=[lr_callback, Checkpoint], ) histories.append(train_history1)
Petals to the Metal - Flower Classification on TPU
10,757,160
train_df['AgeBand'] = pd.cut(train_df['Age'], 5) train_df[['AgeBand', 'Survived']].groupby(['AgeBand'], as_index=False ).mean().sort_values(by='AgeBand', ascending=True )<feature_engineering>
if not SKIP_VALIDATION: cmdataset = get_validation_dataset(ordered=True) images_ds = cmdataset.map(lambda image, label: image) labels_ds = cmdataset.map(lambda image, label: label ).unbatch() cm_correct_labels = next(iter(labels_ds.batch(NUM_VALIDATION_IMAGES)) ).numpy() m1 = model1.predict(images_ds) m2 = Xception_model.predict(images_ds) scores = [] for alpha in np.linspace(0,1,100): cm_probabilities = alpha*m1+(1-alpha)*m2 cm_predictions = np.argmax(cm_probabilities, axis=-1) scores.append(f1_score(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)) , average='macro')) best_alpha = np.argmax(scores)/100 else: best_alpha = 0.51 print('Best alpha: ' + str(best_alpha))
Petals to the Metal - Flower Classification on TPU
10,757,160
for dataset in combine: dataset.loc[ dataset['Age'] <= 16, 'Age'] = 0 dataset.loc[(dataset['Age'] > 16)&(dataset['Age'] <= 32), 'Age'] = 1 dataset.loc[(dataset['Age'] > 32)&(dataset['Age'] <= 48), 'Age'] = 2 dataset.loc[(dataset['Age'] > 48)&(dataset['Age'] <= 64), 'Age'] = 3 dataset.loc[ dataset['Age'] > 64, 'Age'] train_df.head()<drop_column>
if not SKIP_VALIDATION: cmat = confusion_matrix(cm_correct_labels, cm_predictions, labels=range(len(CLASSES))) score = f1_score(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)) , average='macro') precision = precision_score(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)) , average='macro') recall = recall_score(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)) , average='macro') display_confusion_matrix(cmat, score, precision, recall) print('f1 score: {:.3f}, precision: {:.3f}, recall: {:.3f}'.format(score, precision, recall))
Petals to the Metal - Flower Classification on TPU
10,757,160
train_df = train_df.drop(['AgeBand'], axis=1) combine = [train_df, test_df] train_df.head()<sort_values>
def predict_tta(model, n_iter): probs = [] for i in range(n_iter): test_ds = get_test_dataset(ordered=True) test_images_ds = test_ds.map(lambda image, idnum: image) probs.append(model.predict(test_images_ds,verbose=0)) return probs
Petals to the Metal - Flower Classification on TPU
10,757,160
<feature_engineering><EOS>
test_ds = get_test_dataset(ordered=True) print('Calculating predictions...') test_images_ds = test_ds.map(lambda image, idnum: image) probs1 = np.mean(predict_tta(model1, TTA_NUM), axis=0) probs2 = np.mean(predict_tta(Xception_model, TTA_NUM), axis=0) probabilities = best_alpha*probs1 +(1-best_alpha)*probs2 predictions = np.argmax(probabilities, axis=-1) print('Generating submission file...') test_ids_ds = test_ds.map(lambda image, idnum: idnum ).unbatch() test_ids = next(iter(test_ids_ds.batch(NUM_TEST_IMAGES)) ).numpy().astype('U') np.savetxt('submission.csv', np.rec.fromarrays([test_ids, predictions]), fmt=['%s', '%d'], delimiter=',', header='id,label', comments='')
Petals to the Metal - Flower Classification on TPU
10,683,657
<SOS> metric: macrofscore Kaggle data source: petals-to-the-metal-flower-classification-on-tpu<drop_column>
import numpy as np import pandas as pd import tensorflow as tf import matplotlib.pyplot as plt from kaggle_datasets import KaggleDatasets
Petals to the Metal - Flower Classification on TPU
10,683,657
train_df = train_df.drop(['Parch', 'SibSp', 'FamilySize'], axis=1) test_df = test_df.drop(['Parch', 'SibSp', 'FamilySize'], axis=1) combine = [train_df, test_df] train_df.head()<feature_engineering>
!pip install -q efficientnet
Petals to the Metal - Flower Classification on TPU
10,683,657
for dataset in combine: dataset['Age*Class'] = dataset.Age * dataset.Pclass train_df.loc[:, ['Age*Class', 'Age', 'Pclass']].head(10 )<correct_missing_values>
GCS_DS_PATH = KaggleDatasets().get_gcs_path('tpu-getting-started') print(GCS_DS_PATH )
Petals to the Metal - Flower Classification on TPU
10,683,657
freq_port = train_df.Embarked.dropna().mode() [0] freq_port<sort_values>
IMAGE_SIZE = 512 EPOCHS = 35 BATCH_SIZE = 16 * strategy.num_replicas_in_sync NUM_TRAINING_IMAGES = 12753 NUM_TEST_IMAGES = 7382 STEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE
Petals to the Metal - Flower Classification on TPU
10,683,657
for dataset in combine: dataset['Embarked'] = dataset['Embarked'].fillna(freq_port) train_df[['Embarked', 'Survived']].groupby(['Embarked'], as_index=False ).mean().sort_values(by='Survived', ascending=False )<data_type_conversions>
train_data = tf.data.TFRecordDataset( tf.io.gfile.glob(GCS_DS_PATH + '/tfrecords-jpeg-' + str(IMAGE_SIZE)+ 'x' + str(IMAGE_SIZE)+ '/train/*.tfrec'), num_parallel_reads = tf.data.experimental.AUTOTUNE )
Petals to the Metal - Flower Classification on TPU
10,683,657
for dataset in combine: dataset['Embarked'] = dataset['Embarked'].map({'S': 0, 'C': 1, 'Q': 2} ).astype(int) train_df.head()<data_type_conversions>
ignore_order = tf.data.Options() ignore_order.experimental_deterministic = False train_data = train_data.with_options(ignore_order )
Petals to the Metal - Flower Classification on TPU
10,683,657
test_df['Fare'].fillna(test_df['Fare'].dropna().median() , inplace=True) test_df.head()<data_type_conversions>
def read_labeled_tfrecord(example): tfrec_format = { "image": tf.io.FixedLenFeature([], tf.string), "class": tf.io.FixedLenFeature([], tf.int64), } example = tf.io.parse_single_example(example, tfrec_format) image = decode_image(example['image']) label = tf.cast(example['class'], tf.int32) return image, label def decode_image(image_data): image = tf.image.decode_jpeg(image_data, channels=3) image = tf.cast(image, tf.float32)/ 255.0 image = tf.reshape(image, [IMAGE_SIZE, IMAGE_SIZE, 3]) return image
Petals to the Metal - Flower Classification on TPU
10,683,657
for dataset in combine: dataset.loc[ dataset['Fare'] <= 7.91, 'Fare'] = 0 dataset.loc[(dataset['Fare'] > 7.91)&(dataset['Fare'] <= 14.454), 'Fare'] = 1 dataset.loc[(dataset['Fare'] > 14.454)&(dataset['Fare'] <= 31), 'Fare'] = 2 dataset.loc[ dataset['Fare'] > 31, 'Fare'] = 3 dataset['Fare'] = dataset['Fare'].astype(int) combine = [train_df, test_df] train_df.head(10 )<prepare_x_and_y>
train_data = train_data.map(read_labeled_tfrecord )
Petals to the Metal - Flower Classification on TPU
10,683,657
X_train = train_df.drop("Survived", axis=1) Y_train = train_df["Survived"] X_test = test_df.drop("PassengerId", axis=1 ).copy() X_train.shape, Y_train.shape, X_test.shape<compute_train_metric>
train_data = train_data.map(augment, num_parallel_calls=tf.data.experimental.AUTOTUNE )
Petals to the Metal - Flower Classification on TPU
10,683,657
logreg = LogisticRegression() logreg.fit(X_train, Y_train) Y_pred = logreg.predict(X_test) acc_log = round(logreg.score(X_train, Y_train)* 100, 2) acc_log<predict_on_test>
train_data = train_data.repeat() train_data = train_data.shuffle(2048) train_data = train_data.batch(BATCH_SIZE) train_data = train_data.prefetch(tf.data.experimental.AUTOTUNE )
Petals to the Metal - Flower Classification on TPU
10,683,657
knn = KNeighborsClassifier(n_neighbors = 3) knn.fit(X_train, Y_train) Y_pred = knn.predict(X_test) acc_knn = round(knn.score(X_train, Y_train)* 100, 2) acc_knn<train_model>
val_data = tf.data.TFRecordDataset( tf.io.gfile.glob(GCS_DS_PATH + '/tfrecords-jpeg-' + str(IMAGE_SIZE)+ 'x' + str(IMAGE_SIZE)+ '/val/*.tfrec'), num_parallel_reads = tf.data.experimental.AUTOTUNE ) val_data = val_data.with_options(ignore_order) val_data = val_data.map(read_labeled_tfrecord, num_parallel_calls = tf.data.experimental.AUTOTUNE) val_data = val_data.batch(BATCH_SIZE) val_data = val_data.cache() val_data = val_data.prefetch(tf.data.experimental.AUTOTUNE )
Petals to the Metal - Flower Classification on TPU
10,683,657
model = RandomForestClassifier(n_estimators=100, max_depth=5, random_state=1) model.fit(X_train, Y_train) predictions = model.predict(X_test) model.score(X_train, Y_train) acc_random_forest = round(model.score(X_train, Y_train)* 100, 2) acc_random_forest<save_to_csv>
with strategy.scope() : enet = efn.EfficientNetB7( input_shape=(IMAGE_SIZE, IMAGE_SIZE, 3), weights='imagenet', include_top=False ) enet.trainable = True model = tf.keras.Sequential([ enet, tf.keras.layers.GlobalAveragePooling2D() , tf.keras.layers.Dense(104, activation='softmax', dtype='float32') ] )
Petals to the Metal - Flower Classification on TPU
10,683,657
output = pd.DataFrame({'PassengerId': test_df.PassengerId, 'Survived': predictions}) output.to_csv('my_submission.csv', index=False) print("Your second submission was successfully saved!" )<define_variables>
model.compile( optimizer='adam', loss = 'sparse_categorical_crossentropy', metrics=['sparse_categorical_accuracy'] )
Petals to the Metal - Flower Classification on TPU
10,683,657
warnings.filterwarnings('ignore') daybasecount = 4 baseday = 98 - float(daybasecount-1)/2. exponent = 1./float(daybasecount) fatalityBaseDayShift = 10 maxincrease = 140 maxDeadPrDay = 1500<load_from_csv>
callbacks = [ tf.keras.callbacks.ReduceLROnPlateau(monitor='loss', patience=2, verbose=1), tf.keras.callbacks.EarlyStopping(monitor='loss', patience=5, verbose=1, restore_best_weights=True), ]
Petals to the Metal - Flower Classification on TPU
10,683,657
dftrain = pd.read_csv('.. /input/covid19-global-forecasting-week-3/train.csv', parse_dates=['Date'] ).sort_values(by=['Country_Region', 'Date']) dftest = pd.read_csv('.. /input/covid19-global-forecasting-week-3/test.csv', parse_dates=['Date'] ).sort_values(by=['Country_Region', 'Date']) ppp_tabel = pd.read_csv('.. /input/country-ppp/Country_PPP.csv', sep='\s+') ppp_tabel.drop('Id', 1,inplace=True) ppp_tabel = ppp_tabel.append({'Country' : 'Burma' , 'ppp' : 8000} , ignore_index=True) ppp_tabel = ppp_tabel.append({'Country' : 'MS_Zaandam' , 'ppp' : 40000} , ignore_index=True) ppp_tabel = ppp_tabel.append({'Country' : 'West_Bank_and_Gaza' , 'ppp' : 20000} , ignore_index=True) ppp_tabel["Country"].replace('_',' ', regex=True,inplace=True) ppp_tabel["Country"].replace('United States','US', regex=True,inplace=True) ppp_tabel.rename(columns={'Country':'Country_Region'},inplace=True) ppp_tabel.sort_values('Country_Region',inplace=True )<merge>
history = model.fit( train_data, validation_data = val_data, steps_per_epoch = STEPS_PER_EPOCH, epochs = EPOCHS, callbacks = callbacks, )
Petals to the Metal - Flower Classification on TPU
10,683,657
dftrain['Dayofyear'] = dftrain['Date'].dt.dayofyear dftest['Dayofyear'] = dftest['Date'].dt.dayofyear dftest['Expo'] = dftest['Dayofyear']-baseday print(dftrain.tail(5)) dftest = dftest.merge(dftrain[['Country_Region','Province_State','Date','ConfirmedCases','Fatalities']] , on=['Country_Region','Province_State','Date'], how='left', indicator=True) <merge>
def read_unlabeled_tfrecord(example): tfrec_format = { "image": tf.io.FixedLenFeature([], tf.string), "id": tf.io.FixedLenFeature([], tf.string), } example = tf.io.parse_single_example(example, tfrec_format) image = decode_image(example['image']) idnum = example['id'] return image, idnum
Petals to the Metal - Flower Classification on TPU