kernel_id
int64
24.2k
23.3M
prompt
stringlengths
8
1.85M
completetion
stringlengths
1
182k
comp_name
stringlengths
5
57
11,896,796
women_count = 0 women_survived_count = 0 for idx, row in train_data.iterrows() : if row['Sex'] == 'female': women_count += 1 if row['Survived'] == 1: women_survived_count += 1 women_survived_count / women_count<define_variables>
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')+ 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,896,796
predictions = [] for idx, row in test_data.iterrows() : if row['Sex'] == 'female': if row['Pclass'] == '1': predictions.append(1) elif row['Pclass'] == '2': if row['Embarked'] == 'C': predictions.append(1) else: predictions.append(0) else: if row['Embarked'] == 'C' or row['Fare'] > 8: predictions.append(1) else: predictions.append(0) else: if row['Age'] < 10 and row['Pclass'] != '3': predictions.append(1) else: predictions.append(0 )<feature_engineering>
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,896,796
test_data['Survived'] = predictions<save_to_csv>
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(50 if EPOCHS<50 else 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,896,796
test_data[['PassengerId', 'Survived']].to_csv('submission.csv', index=False )<set_options>
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 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) return image, label def get_training_dataset(dataset,do_aug=True): dataset = dataset.map(data_augment, num_parallel_calls=AUTO) if do_aug: dataset = dataset.map(transform, 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(dataset): 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): n = [int(re.compile(r"-([0-9]*)\." ).search(filename ).group(1)) for filename in filenames] return np.sum(n) NUM_TRAINING_IMAGES = int(count_data_items(TRAINING_FILENAMES)*(FOLDS-1.) /FOLDS) NUM_VALIDATION_IMAGES = int(count_data_items(TRAINING_FILENAMES)*(1./FOLDS)) 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,896,796
%matplotlib inline <load_from_csv>
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,896,796
test_df = pd.read_csv("/kaggle/input/titanic/test.csv") train_df = pd.read_csv("/kaggle/input/titanic/train.csv" )<sort_values>
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,896,796
total = train_df.isnull().sum().sort_values(ascending=False) percent_1 = train_df.isnull().sum() /train_df.isnull().count() *100 percent_2 =(round(percent_1, 1)).sort_values(ascending=False) missing_data = pd.concat([total, percent_2], axis=1, keys=['Total', '%']) missing_data.head(5 )<data_type_conversions>
def get_model() : with strategy.scope() : rnet = InceptionResNetV2( input_shape=(IMAGE_SIZE[0], IMAGE_SIZE[1], 3), weights='imagenet', include_top=False ) rnet.trainable = True model = tf.keras.Sequential([ rnet, tf.keras.layers.GlobalAveragePooling2D() , tf.keras.layers.Dense(len(CLASSES), activation='softmax',dtype='float32') ]) model.compile( optimizer='adam', loss = 'sparse_categorical_crossentropy', metrics=['sparse_categorical_accuracy'] ) return model def train_cross_validate(folds = 5): histories = [] models = [] early_stopping = tf.keras.callbacks.EarlyStopping(monitor = 'val_loss', patience = 3) kfold = KFold(folds, shuffle = True, random_state = SEED) for f,(trn_ind, val_ind)in enumerate(kfold.split(TRAINING_FILENAMES)) : print() ; print(' print(' print(' train_dataset = load_dataset(list(pd.DataFrame({'TRAINING_FILENAMES': TRAINING_FILENAMES} ).loc[trn_ind]['TRAINING_FILENAMES']), labeled = True) val_dataset = load_dataset(list(pd.DataFrame({'TRAINING_FILENAMES': TRAINING_FILENAMES} ).loc[val_ind]['TRAINING_FILENAMES']), labeled = True, ordered = True) model = get_model() history = model.fit( get_training_dataset(train_dataset), steps_per_epoch = STEPS_PER_EPOCH, epochs = EPOCHS, callbacks = [lr_callback], validation_data = get_validation_dataset(val_dataset), verbose=2 ) models.append(model) histories.append(history) return histories, models def train_and_predict(folds = 5): test_ds = get_test_dataset(ordered=True) test_images_ds = test_ds.map(lambda image, idnum: image) print('Start training %i folds'%folds) histories, models = train_cross_validate(folds = folds) print('Computing predictions...') probabilities = np.average([models[i].predict(test_images_ds)for i in range(folds)], axis = 0) predictions = np.argmax(probabilities, axis=-1) 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='') return histories, models histories_inception, inception_model = train_and_predict(folds = FOLDS )
Petals to the Metal - Flower Classification on TPU
11,896,796
data = [train_df, test_df] for dataset in data: dataset['relatives'] = dataset['SibSp'] + dataset['Parch'] dataset.loc[dataset['relatives'] > 0, 'not_alone'] = 0 dataset.loc[dataset['relatives'] == 0, 'not_alone'] = 1 dataset['not_alone'] = dataset['not_alone'].astype(int) train_df['not_alone'].value_counts()<drop_column>
def get_model() : with strategy.scope() : rnet = NASNetLarge( input_shape=(IMAGE_SIZE[0], IMAGE_SIZE[1], 3), weights='imagenet', include_top=False ) rnet.trainable = True model = tf.keras.Sequential([ rnet, tf.keras.layers.GlobalAveragePooling2D() , tf.keras.layers.Dense(len(CLASSES), activation='softmax',dtype='float32') ]) model.compile( optimizer='adam', loss = 'sparse_categorical_crossentropy', metrics=['sparse_categorical_accuracy'] ) return model def train_cross_validate(folds = 5): histories = [] models = [] early_stopping = tf.keras.callbacks.EarlyStopping(monitor = 'val_loss', patience = 3) kfold = KFold(folds, shuffle = True, random_state = SEED) for f,(trn_ind, val_ind)in enumerate(kfold.split(TRAINING_FILENAMES)) : print() ; print(' print(' print(' train_dataset = load_dataset(list(pd.DataFrame({'TRAINING_FILENAMES': TRAINING_FILENAMES} ).loc[trn_ind]['TRAINING_FILENAMES']), labeled = True) val_dataset = load_dataset(list(pd.DataFrame({'TRAINING_FILENAMES': TRAINING_FILENAMES} ).loc[val_ind]['TRAINING_FILENAMES']), labeled = True, ordered = True) model = get_model() history = model.fit( get_training_dataset(train_dataset), steps_per_epoch = STEPS_PER_EPOCH, epochs = EPOCHS, callbacks = [lr_callback], validation_data = get_validation_dataset(val_dataset), verbose=2 ) models.append(model) histories.append(history) return histories, models def train_and_predict(folds = 5): test_ds = get_test_dataset(ordered=True) test_images_ds = test_ds.map(lambda image, idnum: image) print('Start training %i folds'%folds) histories, models = train_cross_validate(folds = folds) print('Computing predictions...') probabilities = np.average([models[i].predict(test_images_ds)for i in range(folds)], axis = 0) predictions = np.argmax(probabilities, axis=-1) 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='') return histories, models
Petals to the Metal - Flower Classification on TPU
11,896,796
train_df = train_df.drop(['PassengerId'], axis=1 )<categorify>
%%time all_labels = []; all_prob = []; all_pred = [] kfold = KFold(FOLDS, shuffle = True, random_state = SEED) for j,(trn_ind, val_ind)in enumerate(kfold.split(TRAINING_FILENAMES)) : print('Inferring fold',j+1,'validation images...') VAL_FILES = list(pd.DataFrame({'TRAINING_FILENAMES': TRAINING_FILENAMES} ).loc[val_ind]['TRAINING_FILENAMES']) NUM_VALIDATION_IMAGES = count_data_items(VAL_FILES) cmdataset = get_validation_dataset(load_dataset(VAL_FILES, labeled = True, ordered = True)) images_ds = cmdataset.map(lambda image, label: image) labels_ds = cmdataset.map(lambda image, label: label ).unbatch() all_labels.append(next(iter(labels_ds.batch(NUM_VALIDATION_IMAGES)) ).numpy()) prob = inception_model[j].predict(images_ds) all_prob.append(prob) all_pred.append(np.argmax(prob, axis=-1)) cm_correct_labels = np.concatenate(all_labels) cm_probabilities = np.concatenate(all_prob) cm_predictions = np.concatenate(all_pred )
Petals to the Metal - Flower Classification on TPU
11,896,796
deck = {"A": 1, "B": 2, "C": 3, "D": 4, "E": 5, "F": 6, "G": 7, "U": 8} data = [train_df, test_df] for dataset in data: dataset['Cabin'] = dataset['Cabin'].fillna("U0") dataset['Deck'] = dataset['Cabin'].map(lambda x: re.compile("([a-zA-Z]+)" ).search(x ).group()) dataset['Deck'] = dataset['Deck'].map(deck) dataset['Deck'] = dataset['Deck'].fillna(0) dataset['Deck'] = dataset['Deck'].astype(int) train_df = train_df.drop(['Cabin'], axis=1) test_df = test_df.drop(['Cabin'], axis=1 )<data_type_conversions>
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)) ; print()
Petals to the Metal - Flower Classification on TPU
11,896,796
data = [train_df, test_df] for dataset in data: mean = train_df["Age"].mean() std = test_df["Age"].std() is_null = dataset["Age"].isnull().sum() rand_age = np.random.randint(mean - std, mean + std, size = is_null) age_slice = dataset["Age"].copy() age_slice[np.isnan(age_slice)] = rand_age dataset["Age"] = age_slice dataset["Age"] = train_df["Age"].astype(int) train_df["Age"].isnull().sum()<categorify>
Petals to the Metal - Flower Classification on TPU
11,756,240
common_value = 'S' data = [train_df, test_df] for dataset in data: dataset['Embarked'] = dataset['Embarked'].fillna(common_value )<data_type_conversions>
print("TF version " + tf.__version__) AUTO = tf.data.experimental.AUTOTUNE
Petals to the Metal - Flower Classification on TPU
11,756,240
data = [train_df, test_df] for dataset in data: dataset['Fare'] = dataset['Fare'].fillna(0) dataset['Fare'] = dataset['Fare'].astype(int) data = [train_df, test_df] titles = {"Mr": 1, "Miss": 2, "Mrs": 3, "Master": 4, "Rare": 5} for dataset in data: dataset['Title'] = dataset.Name.str.extract('([A-Za-z]+)\.', expand=False) 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') dataset['Title'] = dataset['Title'].map(titles) dataset['Title'] = dataset['Title'].fillna(0) train_df = train_df.drop(['Name'], axis=1) test_df = test_df.drop(['Name'], axis=1) genders = {"male": 0, "female": 1} data = [train_df, test_df] for dataset in data: dataset['Sex'] = dataset['Sex'].map(genders) train_df['Ticket'].describe() train_df = train_df.drop(['Ticket'], axis=1) test_df = test_df.drop(['Ticket'], axis=1 )<categorify>
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
11,756,240
ports = {"S": 0, "C": 1, "Q": 2} data = [train_df, test_df] for dataset in data: dataset['Embarked'] = dataset['Embarked'].map(ports )<feature_engineering>
IMAGE_SIZE = [512, 512] EPOCHS = 30 BATCH_SIZE = 16 * strategy.num_replicas_in_sync SKIP_VALIDATION = False TTA_NUM = 5 SEED = 42 random.seed(SEED) np.random.seed(SEED) tf.random.set_seed(SEED )
Petals to the Metal - Flower Classification on TPU
11,756,240
data = [train_df, test_df] for dataset in data: dataset['Age'] = dataset['Age'].astype(int) dataset.loc[ dataset['Age'] <= 11, 'Age'] = 0 dataset.loc[(dataset['Age'] > 11)&(dataset['Age'] <= 18), 'Age'] = 1 dataset.loc[(dataset['Age'] > 18)&(dataset['Age'] <= 22), 'Age'] = 2 dataset.loc[(dataset['Age'] > 22)&(dataset['Age'] <= 27), 'Age'] = 3 dataset.loc[(dataset['Age'] > 27)&(dataset['Age'] <= 33), 'Age'] = 4 dataset.loc[(dataset['Age'] > 33)&(dataset['Age'] <= 40), 'Age'] = 5 dataset.loc[(dataset['Age'] > 40)&(dataset['Age'] <= 66), 'Age'] = 6 dataset.loc[ dataset['Age'] > 66, 'Age'] = 6 <feature_engineering>
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]]
Petals to the Metal - Flower Classification on TPU
11,756,240
data = [train_df, test_df] for dataset in data: 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)&(dataset['Fare'] <= 99), 'Fare'] = 3 dataset.loc[(dataset['Fare'] > 99)&(dataset['Fare'] <= 250), 'Fare'] = 4 dataset.loc[ dataset['Fare'] > 250, 'Fare'] = 5 dataset['Fare'] = dataset['Fare'].astype(int )<feature_engineering>
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,756,240
data = [train_df, test_df] for dataset in data: dataset['Age_Class']= dataset['Age']* dataset['Pclass']<data_type_conversions>
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
Petals to the Metal - Flower Classification on TPU
11,756,240
for dataset in data: dataset['Fare_Per_Person'] = dataset['Fare']/(dataset['relatives']+1) dataset['Fare_Per_Person'] = dataset['Fare_Per_Person'].astype(int) train_df.head(10 )<save_to_csv>
def display_batch_of_images(databatch, predictions=None): images, labels = batch_to_numpy_images_and_labels(databatch) if labels is None: labels = [None for _ in enumerate(images)] rows = int(math.sqrt(len(images))) cols = len(images)//rows FIGSIZE = 13.0 SPACING = 0.1 subplot=(rows,cols,1) if rows < cols: plt.figure(figsize=(FIGSIZE,FIGSIZE/cols*rows)) else: plt.figure(figsize=(FIGSIZE/rows*cols,FIGSIZE)) for i,(image, label)in enumerate(zip(images[:rows*cols], labels[:rows*cols])) : title = '' if label is None else CLASSES[label] correct = True if predictions is not None: title, correct = title_from_label_and_target(predictions[i], label) dynamic_titlesize = FIGSIZE*SPACING/max(rows,cols)*40+3 subplot = display_one_flower(image, title, subplot, not correct, titlesize=dynamic_titlesize) plt.tight_layout() if label is None and predictions is None: plt.subplots_adjust(wspace=0, hspace=0) else: plt.subplots_adjust(wspace=SPACING, hspace=SPACING) plt.show()
Petals to the Metal - Flower Classification on TPU
11,756,240
X_train = train_df.drop("Survived", axis=1) Y_train = train_df["Survived"] X_test = test_df.drop("PassengerId", axis=1 ).copy() decision_tree = DecisionTreeClassifier() decision_tree.fit(X_train, Y_train) predictions = decision_tree.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!" )<set_options>
def random_blockout(img, sl=0.1, sh=0.2, rl=0.4): p=random.random() if p>=0.25: w, h, c = IMAGE_SIZE[0], IMAGE_SIZE[1], 3 origin_area = tf.cast(h*w, tf.float32) e_size_l = tf.cast(tf.round(tf.sqrt(origin_area * sl * rl)) , tf.int32) e_size_h = tf.cast(tf.round(tf.sqrt(origin_area * sh / rl)) , tf.int32) e_height_h = tf.minimum(e_size_h, h) e_width_h = tf.minimum(e_size_h, w) erase_height = tf.random.uniform(shape=[], minval=e_size_l, maxval=e_height_h, dtype=tf.int32) erase_width = tf.random.uniform(shape=[], minval=e_size_l, maxval=e_width_h, dtype=tf.int32) erase_area = tf.zeros(shape=[erase_height, erase_width, c]) erase_area = tf.cast(erase_area, tf.uint8) pad_h = h - erase_height pad_top = tf.random.uniform(shape=[], minval=0, maxval=pad_h, dtype=tf.int32) pad_bottom = pad_h - pad_top pad_w = w - erase_width pad_left = tf.random.uniform(shape=[], minval=0, maxval=pad_w, dtype=tf.int32) pad_right = pad_w - pad_left erase_mask = tf.pad([erase_area], [[0,0],[pad_top, pad_bottom], [pad_left, pad_right], [0,0]], constant_values=1) erase_mask = tf.squeeze(erase_mask, axis=0) erased_img = tf.multiply(tf.cast(img,tf.float32), tf.cast(erase_mask, tf.float32)) return tf.cast(erased_img, img.dtype) else: return tf.cast(img, img.dtype )
Petals to the Metal - Flower Classification on TPU
11,756,240
%matplotlib inline np.random.seed(2) <load_from_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
Petals to the Metal - Flower Classification on TPU
11,756,240
train = pd.read_csv('/kaggle/input/digit-recognizer/train.csv') test = pd.read_csv('/kaggle/input/digit-recognizer/test.csv' )<prepare_x_and_y>
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
Petals to the Metal - Flower Classification on TPU
11,756,240
Y_train = train['label'] X_train = train.drop(labels=['label'], axis=1) del train<count_values>
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
Petals to the Metal - Flower Classification on TPU
11,756,240
Y_train.value_counts()<feature_engineering>
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
Petals to the Metal - Flower Classification on TPU
11,756,240
X_train = X_train / 255.0 test = test / 255.0<categorify>
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
11,756,240
Y_train = to_categorical(Y_train, num_classes=10) print(Y_train.shape )<define_variables>
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,756,240
random_seed = 2<split>
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 // 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,756,240
X_train, X_val, Y_train, Y_val = train_test_split(X_train, Y_train, test_size=0.1, random_state=random_seed )<import_modules>
if SKIP_VALIDATION: TRAINING_FILENAMES = TRAINING_FILENAMES + VALIDATION_FILENAMES
Petals to the Metal - Flower Classification on TPU
11,756,240
from keras.models import Sequential from keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPool2D from keras.optimizers import RMSprop from keras.preprocessing.image import ImageDataGenerator from keras.callbacks import ReduceLROnPlateau<choose_model_class>
print("Training data shapes:") for image, label in get_training_dataset().take(3): print(image.numpy().shape, label.numpy().shape) print("Training data label examples:", label.numpy()) print("Validation data shapes:") for image, label in get_validation_dataset().take(3): print(image.numpy().shape, label.numpy().shape) print("Validation data label examples:", label.numpy()) print("Test data shapes:") for image, idnum in get_test_dataset().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
11,756,240
model = Sequential() model.add(Conv2D(filters=32, kernel_size=(5, 5), padding='same', activation='relu', input_shape=(28, 28, 1))) model.add(Conv2D(filters=32, kernel_size=(5, 5), padding='same', activation='relu')) 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(Conv2D(filters=64, kernel_size=(3, 3), padding='same', activation='relu')) model.add(MaxPool2D(pool_size=(2, 2), strides=(2, 2))) model.add(Dropout(0.25)) model.add(Flatten()) model.add(Dense(256, activation='relu')) model.add(Dropout(0.5)) model.add(Dense(10, activation='softmax'))<choose_model_class>
training_dataset = get_training_dataset() training_dataset = training_dataset.unbatch().batch(20) train_batch = iter(training_dataset )
Petals to the Metal - Flower Classification on TPU
11,756,240
optimizer = RMSprop(lr=0.001, rho=0.9, epsilon=1e-08, decay=0.0 )<choose_model_class>
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,756,240
model.compile(optimizer, loss='categorical_crossentropy', metrics=['accuracy'] )<choose_model_class>
display_batch_of_images(next(train_batch))
Petals to the Metal - Flower Classification on TPU
11,756,240
learning_rate_reduction = ReduceLROnPlateau(monitor='val_accuracy', patience=3, verbose=1, factor=0.5, min_lr=0.00001 )<define_variables>
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
11,756,240
epochs = 30 batch_size = 86<train_model>
display_batch_of_images(next(test_batch))
Petals to the Metal - Flower Classification on TPU
11,756,240
datagen = ImageDataGenerator( featurewise_center=False, samplewise_center=False, featurewise_std_normalization=False, samplewise_std_normalization=False, zca_whitening=False, rotation_range=10, zoom_range=0.1, height_shift_range=0.1, horizontal_flip=False, vertical_flip=False ) datagen.fit(X_train )<train_model>
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(25 if EPOCHS<25 else 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,756,240
history = model.fit_generator(datagen.flow(X_train, Y_train, batch_size=batch_size), epochs=epochs, validation_data=(X_val, Y_val), verbose=2, steps_per_epoch=X_train.shape[0] // batch_size, callbacks=[learning_rate_reduction] )<import_modules>
!pip install -q efficientnet
Petals to the Metal - Flower Classification on TPU
11,756,240
import itertools from sklearn.metrics import confusion_matrix<compute_test_metric>
with strategy.scope() : enet = efn.EfficientNetB7(input_shape=[*IMAGE_SIZE, 3], weights='noisy-student', include_top=False) enet.trainable = True model1 = tf.keras.Sequential([ enet, tf.keras.layers.GlobalAveragePooling2D() , tf.keras.layers.Dense(len(CLASSES), activation='softmax') ] )
Petals to the Metal - Flower Classification on TPU
11,756,240
errors =(Y_pred_classes - Y_true)!= 0 print(errors) print(np.sum(errors))<define_variables>
model1.compile( optimizer=tf.keras.optimizers.Adam() , loss = 'sparse_categorical_crossentropy', metrics=['sparse_categorical_accuracy'] )
Petals to the Metal - Flower Classification on TPU
11,756,240
Y_pred_classes_errors = Y_pred_classes[errors] Y_pred_errors = Y_pred[errors] Y_true_errors = Y_true[errors] X_val_errors = X_val[errors]<predict_on_test>
if not SKIP_VALIDATION: history1 = model1.fit(get_training_dataset() , steps_per_epoch=STEPS_PER_EPOCH, epochs=EPOCHS, validation_data=get_validation_dataset() , callbacks = [lr_callback]) else: history1 = model1.fit(get_training_dataset() , steps_per_epoch=STEPS_PER_EPOCH, epochs=EPOCHS, callbacks = [lr_callback] )
Petals to the Metal - Flower Classification on TPU
11,756,240
results = model.predict(test) results.shape<concatenate>
with strategy.scope() : densenet = tf.keras.applications.DenseNet201(input_shape=[*IMAGE_SIZE, 3], weights='imagenet', include_top=False) densenet.trainable = True model2 = tf.keras.Sequential([ densenet, tf.keras.layers.GlobalAveragePooling2D() , tf.keras.layers.Dense(len(CLASSES), activation='softmax') ]) model2.compile( optimizer=tf.keras.optimizers.Adam() , loss = 'sparse_categorical_crossentropy', metrics=['sparse_categorical_accuracy'] ) model2.summary()
Petals to the Metal - Flower Classification on TPU
11,756,240
submission = pd.concat([pd.Series(range(1, 28001), name='ImageId'), results], axis=1) submission.head()<save_to_csv>
if not SKIP_VALIDATION: history2 = model2.fit(get_training_dataset() , steps_per_epoch=STEPS_PER_EPOCH, epochs=EPOCHS, validation_data=get_validation_dataset() , callbacks = [lr_callback]) else: history2 = model2.fit(get_training_dataset() , steps_per_epoch=STEPS_PER_EPOCH, epochs=EPOCHS, callbacks = [lr_callback] )
Petals to the Metal - Flower Classification on TPU
11,756,240
submission.to_csv('cnn_mnist_augmentation.csv', index=False )<set_options>
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 = model2.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
11,756,240
%matplotlib inline PUNCT_TO_REMOVE = string.punctuation STOPWORDS = set(stopwords.words('english')) stemmer = PorterStemmer()<load_from_csv>
if not SKIP_VALIDATION: cm_probabilities = best_alpha*m1 +(1-best_alpha)*m2 cm_predictions = np.argmax(cm_probabilities, axis=-1) 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
11,756,240
df_train = pd.read_csv('.. /input/nlp-getting-started/train.csv') df_test = pd.read_csv('.. /input/nlp-getting-started/test.csv' )<string_transform>
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
11,756,240
<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(model2, 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
11,521,017
<SOS> metric: macrofscore Kaggle data source: petals-to-the-metal-flower-classification-on-tpu<prepare_x_and_y>
print('Tensorflow version ' + tf.__version__) !pip install -q efficientnet
Petals to the Metal - Flower Classification on TPU
11,521,017
X = df_train['text_processed'] y = df_train['target']<split>
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
11,521,017
X_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.1,random_state=42 )<train_model>
AUTO = tf.data.experimental.AUTOTUNE IMAGE_SIZE = [224, 224] EPOCHS = 30 FOLDS = 3 SEED = 777 BATCH_SIZE = 16 * strategy.num_replicas_in_sync
Petals to the Metal - Flower Classification on TPU
11,521,017
vectorizer=TfidfVectorizer(ngram_range=(1,3),min_df=3,strip_accents='unicode', use_idf=1,smooth_idf=1, sublinear_tf=1,max_features=None) vectorizer.fit(list(df_train['text_processed'])+list(df_test['text_processed'])) print('vocab length',len(vectorizer.vocabulary_))<categorify>
MIXED_PRECISION = False XLA_ACCELERATE = False if MIXED_PRECISION: if tpu: policy = tf.keras.mixed_precision.experimental.Policy('mixed_bfloat16') else: policy = tf.keras.mixed_precision.experimental.Policy('mixed_float16') mixed_precision.set_policy(policy) print('Mixed precision enabled') if XLA_ACCELERATE: tf.config.optimizer.set_jit(True) print('Accelerated Linear Algebra enabled' )
Petals to the Metal - Flower Classification on TPU
11,521,017
X_train_onehot = vectorizer.transform(X_train ).todense() X_val_onehot = vectorizer.transform(X_val ).todense()<train_model>
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 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) return image, label def get_training_dataset(dataset,do_aug=True): dataset = dataset.map(data_augment, num_parallel_calls=AUTO) if do_aug: dataset = dataset.map(transform, 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(dataset): 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): n = [int(re.compile(r"-([0-9]*)\." ).search(filename ).group(1)) for filename in filenames] return np.sum(n) NUM_TRAINING_IMAGES = int(count_data_items(TRAINING_FILENAMES)*(FOLDS-1.) /FOLDS) NUM_VALIDATION_IMAGES = int(count_data_items(TRAINING_FILENAMES)*(1./FOLDS)) 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,521,017
lr_clf = LogisticRegression(max_iter=150,penalty='l2',solver='lbfgs',random_state=0) lr_clf.fit(X_train_onehot, y_train) lr_pred = lr_clf.predict(X_val_onehot) print('accuracy score: ',accuracy_score(lr_pred,y_val)) print(classification_report(y_val, lr_pred))<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,521,017
logloss_lr = log_loss(y_val,lr_clf.predict_proba(X_val_onehot)) print('logloss_lr:',logloss_lr )<compute_train_metric>
train_dataset_all = load_dataset(list(pd.DataFrame({'TRAINING_FILENAMES': TRAINING_FILENAMES})['TRAINING_FILENAMES']), labeled = True) test_dataset_all = load_dataset(list(pd.DataFrame({'TEST_FILENAMES': TEST_FILENAMES})['TEST_FILENAMES']), labeled = True, ordered=True) train_dataset = load_dataset(list(pd.DataFrame({'TRAINING_FILENAMES_ONLY': TRAINING_FILENAMES_ONLY})['TRAINING_FILENAMES_ONLY']), labeled = True) val_dataset = load_dataset(list(pd.DataFrame({'VAL_FILENAMES_ONLY': VAL_FILENAMES_ONLY})['VAL_FILENAMES_ONLY']), labeled=True, ordered=True) train_all = get_training_dataset(train_dataset_all) test = get_test_dataset(test_dataset_all) test_images_ds = test.map(lambda image, idnum: image) train = get_training_dataset(train_dataset) val = get_validation_dataset(val_dataset) def Xception_model() : with strategy.scope() : rnet = Xception( input_shape=(IMAGE_SIZE[0], IMAGE_SIZE[1], 3), weights='imagenet', include_top=False ) rnet.trainable = True model = tf.keras.Sequential([ rnet, tf.keras.layers.GlobalAveragePooling2D() , tf.keras.layers.Dense(len(CLASSES), activation='softmax',dtype='float32') ]) model.compile( optimizer='adam', loss = 'sparse_categorical_crossentropy', metrics=['sparse_categorical_accuracy'] ) return model def VGG16_model() : with strategy.scope() : rnet = VGG16( input_shape=(IMAGE_SIZE[0], IMAGE_SIZE[1], 3), weights='imagenet', include_top=False ) rnet.trainable = True model = tf.keras.Sequential([ rnet, tf.keras.layers.GlobalAveragePooling2D() , tf.keras.layers.Dense(len(CLASSES), activation='softmax',dtype='float32') ]) model.compile( optimizer='adam', loss = 'sparse_categorical_crossentropy', metrics=['sparse_categorical_accuracy'] ) return model def DenseNet201_model() : with strategy.scope() : rnet = DenseNet201( input_shape=(IMAGE_SIZE[0], IMAGE_SIZE[1], 3), weights='imagenet', include_top=False ) rnet.trainable = True model = tf.keras.Sequential([ rnet, tf.keras.layers.GlobalAveragePooling2D() , tf.keras.layers.Dense(len(CLASSES), activation='softmax',dtype='float32') ]) model.compile( optimizer='adam', loss = 'sparse_categorical_crossentropy', metrics=['sparse_categorical_accuracy'] ) return model def InceptionV3_model() : with strategy.scope() : rnet = InceptionV3( input_shape=(IMAGE_SIZE[0], IMAGE_SIZE[1], 3), weights='imagenet', include_top=False ) rnet.trainable = True model = tf.keras.Sequential([ rnet, tf.keras.layers.GlobalAveragePooling2D() , tf.keras.layers.Dropout(0.2), tf.keras.layers.Dense(len(CLASSES), activation='softmax',dtype='float32') ]) model.compile( optimizer='adam', loss = 'sparse_categorical_crossentropy', metrics=['sparse_categorical_accuracy'] ) return model def EfficientNetB7_model() : with strategy.scope() : rnet = EfficientNetB7( input_shape=(IMAGE_SIZE[0], IMAGE_SIZE[1], 3), weights='imagenet', include_top=False ) rnet.trainable = True model = tf.keras.Sequential([ rnet, tf.keras.layers.GlobalAveragePooling2D() , tf.keras.layers.Dropout(0.2), tf.keras.layers.Dense(len(CLASSES), activation='softmax',dtype='float32') ]) model.compile( optimizer='adam', loss = 'sparse_categorical_crossentropy', metrics=['sparse_categorical_accuracy'] ) return model def ResNet152V2_model() : with strategy.scope() : rnet = ResNet152V2( input_shape=(IMAGE_SIZE[0], IMAGE_SIZE[1], 3), weights='imagenet', include_top=False ) rnet.trainable = True model = tf.keras.Sequential([ rnet, tf.keras.layers.GlobalAveragePooling2D() , tf.keras.layers.Dropout(0.2), tf.keras.layers.Dense(len(CLASSES), activation='softmax',dtype='float32') ]) model.compile( optimizer='adam', loss = 'sparse_categorical_crossentropy', metrics=['sparse_categorical_accuracy'] ) return model def MobileNetV2_model() : with strategy.scope() : rnet = MobileNetV2( input_shape=(IMAGE_SIZE[0], IMAGE_SIZE[1], 3), weights='imagenet', include_top=False ) rnet.trainable = True model = tf.keras.Sequential([ rnet, tf.keras.layers.GlobalAveragePooling2D() , tf.keras.layers.Dropout(0.2), tf.keras.layers.Dense(len(CLASSES), activation='softmax',dtype='float32') ]) model.compile( optimizer='adam', loss = 'sparse_categorical_crossentropy', metrics=['sparse_categorical_accuracy'] ) return model def InceptionResNetV2_model() : with strategy.scope() : rnet = InceptionResNetV2( input_shape=(IMAGE_SIZE[0], IMAGE_SIZE[1], 3), weights='imagenet', include_top=False ) rnet.trainable = True model = tf.keras.Sequential([ rnet, tf.keras.layers.GlobalAveragePooling2D() , tf.keras.layers.Dropout(0.2), tf.keras.layers.Dense(len(CLASSES), activation='softmax',dtype='float32') ]) model.compile( optimizer='adam', loss = 'sparse_categorical_crossentropy', metrics=['sparse_categorical_accuracy'] ) return model models = {'Xception' : Xception_model, 'VGG16' : VGG16_model, 'DenseNet201' : DenseNet201_model, 'InceptionV3' : InceptionV3_model, 'InceptionResNetV2' : InceptionResNetV2_model } historys = {} predictions = {} predictions_val = {} predictions_prob = {} times = {} MODELS_NUMBER = 5
Petals to the Metal - Flower Classification on TPU
11,521,017
mnb_clf = MultinomialNB() mnb_clf.fit(X_train_onehot, y_train) mnb_pred = mnb_clf.predict(X_val_onehot) print('accuracy score: ',accuracy_score(mnb_pred,y_val)) print(classification_report(y_val, mnb_pred))<compute_test_metric>
df = pd.DataFrame(predictions) pred = [] for i in range(0, 7382): if df.loc[i,:].unique().shape[0] < MODELS_NUMBER : pred.append(stats.mode(df.loc[i,:].values)[0][0]) else : pred.append(df.loc[i,'InceptionResNetV2']) df = pd.DataFrame(predictions_val) pred_val = [] for i in range(0, 3712): if df.loc[i,:].unique().shape[0] < MODELS_NUMBER : pred_val.append(stats.mode(df.loc[i,:].values)[0][0]) else : pred_val.append(df.loc[i,'InceptionResNetV2']) avg_prob = predictions_prob['Xception'] + predictions_prob['VGG16'] + predictions_prob['DenseNet201'] + predictions_prob['InceptionV3'] + predictions_prob['InceptionResNetV2'] pred_avg = pd.DataFrame(np.argmax(avg_prob, axis=-1))
Petals to the Metal - Flower Classification on TPU
11,521,017
<predict_on_test><EOS>
test_ids_ds = test.map(lambda image, idnum: idnum ).unbatch() test_ids = next(iter(test_ids_ds.batch(NUM_TEST_IMAGES)) ).numpy().astype('U') np.savetxt('submission_vote.csv', np.rec.fromarrays([test_ids, pred]), fmt=['%s', '%d'], delimiter=',', header='id,label', comments='') np.savetxt('submission.csv', np.rec.fromarrays([test_ids, np.argmax(avg_prob, axis=-1)]), fmt=['%s', '%d'], delimiter=',', header='id,label', comments='' )
Petals to the Metal - Flower Classification on TPU
11,593,914
<SOS> metric: macrofscore Kaggle data source: petals-to-the-metal-flower-classification-on-tpu<compute_test_metric>
!pip install -q efficientnet
Petals to the Metal - Flower Classification on TPU
11,593,914
logloss_rf = log_loss(y_val,rf_clf.predict_proba(X_val_onehot)) print('logloss_rf:',logloss_rf )<train_model>
import numpy as np import pandas as pd import re import os import efficientnet.tfkeras as efn import tensorflow as tf from tensorflow.keras.layers import Input, Dense from tensorflow.keras.layers import GlobalAveragePooling2D from tensorflow.keras.models import Sequential from tensorflow.keras.callbacks import LearningRateScheduler from kaggle_datasets import KaggleDatasets from sklearn.metrics import confusion_matrix, f1_score from sklearn.metrics import precision_score, recall_score import seaborn as sea import matplotlib.pyplot as plt
Petals to the Metal - Flower Classification on TPU
11,593,914
xgb_clf = xgb.XGBClassifier(n_estimators=100,n_jobs=-1,max_depth=15, min_child_weight=3,objective='binary:logistic' ,colsample_bytree=0.4) xgb_clf.fit(X_train_onehot, y_train) xgb_predictions = xgb_clf.predict(X_val_onehot) print('accuracy score: ',accuracy_score(xgb_predictions,y_val)) print(classification_report(y_val, xgb_predictions))<compute_test_metric>
sea.set_style("darkgrid") np.random.seed(3) tf.random.set_seed(6 )
Petals to the Metal - Flower Classification on TPU
11,593,914
logloss_xgb = log_loss(y_val,xgb_clf.predict_proba(X_val_onehot)) print('logloss_rf:',logloss_xgb )<choose_model_class>
gcs_path = KaggleDatasets().get_gcs_path("tpu-getting-started") data_path = os.path.join(gcs_path, "tfrecords-jpeg-512x512/") train_path = os.path.join(gcs_path, "tfrecords-jpeg-512x512/train/") val_path = os.path.join(gcs_path, "tfrecords-jpeg-512x512/val/") test_path = os.path.join(gcs_path, "tfrecords-jpeg-512x512/test/" )
Petals to the Metal - Flower Classification on TPU
11,593,914
model = Sequential() model.add(Dense(512, activation='relu', input_dim=np.shape(X_train_onehot)[1], kernel_regularizer=regularizers.l2(0.01), activity_regularizer=regularizers.l1(0.01))) model.add(BatchNormalization()) model.add(Dropout(0.5)) model.add(Dense(256, activation='relu')) model.add(BatchNormalization()) model.add(Dropout(0.6)) model.add(Dense(64, activation='relu')) model.add(BatchNormalization()) model.add(Dropout(0.5)) model.add(Dense(1, activation='sigmoid')) adam = Adam(lr=1e-4, beta_1=0.9, beta_2=0.999, epsilon=10**-8, decay=0.0001, amsgrad=False) model.compile(optimizer= adam, loss='binary_crossentropy', metrics=['accuracy']) print(model.summary()) hist = model.fit(X_train_onehot, y_train,validation_data =(X_val_onehot,y_val), epochs=20, batch_size=16 )<predict_on_test>
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,593,914
dnn_pred = model.predict_classes(X_val_onehot )<compute_test_metric>
def read_record(example): features = { "image": tf.io.FixedLenFeature([], tf.string), "class": tf.io.FixedLenFeature([], tf.int64), } example = tf.io.parse_single_example(example, features) image = tf.image.decode_jpeg(example["image"], channels=3) image = tf.cast(image, tf.float32)/ 255.0 image = tf.reshape(image, [512,512,3]) label = tf.cast(example["class"], tf.int32) return image, label def read_record_test(example): features = { "image": tf.io.FixedLenFeature([], tf.string), "id": tf.io.FixedLenFeature([], tf.string), } example = tf.io.parse_single_example(example, features) image = tf.image.decode_jpeg(example["image"], channels=3) image = tf.cast(image, tf.float32)/ 255.0 image = tf.reshape(image, [512,512,3]) image_id = example["id"] return image, image_id
Petals to the Metal - Flower Classification on TPU
11,593,914
print('accuracy score: ',accuracy_score(dnn_pred,y_val)) print(classification_report(y_val, dnn_pred))<compute_test_metric>
AUTO = tf.data.experimental.AUTOTUNE def get_size(filenames): data_size = 0 for i in range(len(filenames)) : count = re.search(r"-[0-9][0-9][0-9]\.", filenames[i] ).group() data_size = data_size + int(count[1:4]) return data_size def prepare_dataset(flag, order = False): filenames = tf.io.gfile.glob(os.path.join(data_path, flag)+"/*.tfrec") data_size = get_size(filenames) dataset = tf.data.TFRecordDataset(filenames, num_parallel_reads=AUTO) ignore_order = tf.data.Options() if order == False: ignore_order.experimental_deterministic = False else: ignore_order.experimental_deterministic = True dataset = dataset.with_options(ignore_order) if flag == "test": dataset = dataset.map(read_record_test, num_parallel_calls=AUTO) else: dataset = dataset.map(read_record, num_parallel_calls=AUTO) return dataset, data_size train_dataset, train_size = prepare_dataset("train") val_dataset, val_size = prepare_dataset("val") test_dataset, test_size = prepare_dataset("test") print("Size of Training Dataset\t: ", train_size) print("Size of Validation Dataset\t: ", val_size) print("Size of Test Dataset\t\t: ", test_size )
Petals to the Metal - Flower Classification on TPU
11,593,914
logloss_dnn = log_loss(y_val,model.predict_proba(X_val_onehot)) print('logloss_dnn:',logloss_dnn )<predict_on_test>
def augment(image, label): cont_low = 0.8 cont_high = 1.2 cont_factor = tf.random.uniform([], minval=cont_low, maxval=cont_high, dtype=tf.float32) trn_image = tf.image.adjust_contrast(image, cont_factor) return trn_image, label
Petals to the Metal - Flower Classification on TPU
11,593,914
lr_predictions_val = lr_clf.predict_proba(X_val_onehot) mnb_predictions_val = mnb_clf.predict_proba(X_val_onehot) xgb_predictions_val = xgb_clf.predict_proba(X_val_onehot) <define_variables>
batch_size = 16 * tpu_strategy.num_replicas_in_sync train_dataset = train_dataset.map(augment, num_parallel_calls = AUTO) train_dataset = train_dataset.repeat().shuffle(3000)\ .batch(batch_size ).prefetch(AUTO) val_dataset = val_dataset.batch(batch_size ).prefetch(AUTO) test_dataset = test_dataset.batch(batch_size ).prefetch(AUTO )
Petals to the Metal - Flower Classification on TPU
11,593,914
predictions_val = 1/3*lr_predictions_val[:,1]+1/3*mnb_predictions_val[:,1] \ +1/3*xgb_predictions_val[:,1] predictions_val = np.where(predictions_val>0.5, 1, 0 )<compute_test_metric>
with tpu_strategy.scope() : base_model = efn.EfficientNetB5(include_top=False, input_shape=(512,512,3), weights='imagenet') base_model.trainable = True model = Sequential(name="Flower_Detector") model.add(base_model) model.add(GlobalAveragePooling2D(name="GAP")) model.add(Dense(104, activation="softmax", name="Probs")) model.compile(optimizer=tf.keras.optimizers.Adam() , loss="sparse_categorical_crossentropy", metrics=["sparse_categorical_accuracy"]) model.summary()
Petals to the Metal - Flower Classification on TPU
11,593,914
print('accuracy score: ',accuracy_score(predictions_val,y_val)) print(classification_report(y_val, predictions_val))<load_from_csv>
step_per_epoch = train_size // batch_size history = model.fit(train_dataset, validation_data=val_dataset, steps_per_epoch=step_per_epoch, epochs=epoch, callbacks=[lrs] )
Petals to the Metal - Flower Classification on TPU
11,593,914
df_test = pd.read_csv('.. /input/nlp-getting-started/test.csv' )<feature_engineering>
val_dataset, val_size = prepare_dataset("val", True) val_dataset = val_dataset.batch(batch_size ).prefetch(AUTO) val_image_dataset = val_dataset.map(lambda image,label: image) val_label_dataset = val_dataset.map(lambda image,label: label ).unbatch() val_labels = next(iter(val_label_dataset.batch(val_size)) ).numpy() val_probs = model.predict(val_image_dataset) val_preds = np.argmax(val_probs, axis=-1 )
Petals to the Metal - Flower Classification on TPU
11,593,914
df_test['text_processed'] = df_test['text'].apply(text_preprocessing )<categorify>
con_mat = confusion_matrix(val_labels, val_preds, labels=range(len(classes))) prec = precision_score(val_labels, val_preds, labels=range(len(classes)) , average='macro') rec = recall_score(val_labels, val_preds, labels=range(len(classes)) , average='macro') f1 = f1_score(val_labels, val_preds, labels=range(len(classes)) , average='macro') plt.figure(figsize=(10,10)) ax = plt.gca() ax.matshow(con_mat, cmap='Greens') ax.set_xticks(range(len(classes))) ax.set_xticklabels(classes, fontdict={'fontsize': 6}) plt.setp(ax.get_xticklabels() , rotation=65, ha="left", rotation_mode="anchor") ax.set_yticks(range(len(classes))) ax.set_yticklabels(classes, fontdict={'fontsize': 6}) plt.setp(ax.get_yticklabels() , rotation=25, ha="right", rotation_mode="anchor") plt.show() print('Precision \t: {:.4f}'.format(prec)) print('Recall \t\t: {:.4f}'.format(rec)) print('F1 score \t: {:.4f}'.format(f1))
Petals to the Metal - Flower Classification on TPU
11,593,914
X_test = df_test['text_processed'] X_test_onehot = vectorizer.transform(X_test ).todense()<predict_on_test>
test_dataset, test_size = prepare_dataset("test", True) test_dataset = test_dataset.batch(batch_size ).prefetch(AUTO) test_image_dataset = test_dataset.map(lambda image,idnum: image) test_id_dataset = test_dataset.map(lambda image,idnum: idnum ).unbatch() test_ids = next(iter(test_id_dataset.batch(test_size)) ).numpy().astype('U') test_probs = model.predict(test_image_dataset) test_preds = np.argmax(test_probs, axis=-1 )
Petals to the Metal - Flower Classification on TPU
11,414,583
lr_predictions = lr_clf.predict_proba(X_test_onehot) mnb_predictions = mnb_clf.predict_proba(X_test_onehot) xgb_predictions = xgb_clf.predict_proba(X_test_onehot) <define_variables>
!pip install -q efficientnet
Petals to the Metal - Flower Classification on TPU
11,414,583
predictions = 1/3*lr_predictions[:,1]+1/3*mnb_predictions[:,1]+1/3*xgb_predictions[:,1]<prepare_output>
print("Tensorflow version " + tf.__version__ )
Petals to the Metal - Flower Classification on TPU
11,414,583
predictions = np.where(predictions>0.5, 1, 0 )<save_to_csv>
AUTO = tf.data.experimental.AUTOTUNE 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) GCS_DS_PATH = KaggleDatasets().get_gcs_path() IMAGE_SIZE = [512, 512] EPOCHS = 50 BATCH_SIZE = 16 * strategy.num_replicas_in_sync 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,414,583
df_submission = pd.read_csv('.. /input/nlp-getting-started/sample_submission.csv') df_submission['target'] = predictions df_submission.to_csv('submission.csv',index=False )<set_options>
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,414,583
pd.set_option('display.max_rows', 1000) seed =45 plt.style.use('fivethirtyeight' )<load_from_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 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) 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 def count_data_items(filenames): n = [int(re.compile(r"-([0-9]*)\." ).search(filename ).group(1)) for filename in filenames] return np.sum(n) 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 // 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,414,583
train = pd.read_csv('/kaggle/input/titanic/train.csv') test = pd.read_csv('/kaggle/input/titanic/test.csv' )<feature_engineering>
with strategy.scope() : enet = efn.EfficientNetB7( input_shape=(812, 812, 3), weights='imagenet', 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,414,583
train.loc[train['PassengerId'] == 631, 'Age'] = 48 train.loc[train['PassengerId'] == 69, ['SibSp', 'Parch']] = [0,0] test.loc[test['PassengerId'] == 1106, ['SibSp', 'Parch']] = [0,0]<sort_values>
scheduler = tf.keras.callbacks.ReduceLROnPlateau(patience=3, verbose=1) history = model.fit( get_training_dataset() , steps_per_epoch=STEPS_PER_EPOCH, epochs=EPOCHS, callbacks=[scheduler], validation_data=get_validation_dataset() )
Petals to the Metal - Flower Classification on TPU
11,414,583
<categorify><EOS>
test_ds = get_test_dataset(ordered=True) print('Computing predictions...') test_images_ds = test_ds.map(lambda image, idnum: image) probabilities = model.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
11,225,265
<SOS> metric: macrofscore Kaggle data source: petals-to-the-metal-flower-classification-on-tpu<drop_column>
!pip install efficientnet --quiet sns.set()
Petals to the Metal - Flower Classification on TPU
11,225,265
<concatenate>
flower_categories = [ '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('Number of flower categories:', len(flower_categories))
Petals to the Metal - Flower Classification on TPU
11,225,265
df = pd.concat(( train.loc[:,'Pclass':'Embarked'], test.loc[:,'Pclass':'Embarked'])).reset_index(drop=True) <load_from_csv>
image_size =(224,224) data_gcs = KaggleDatasets().get_gcs_path('tpu-getting-started') ext_gcs = KaggleDatasets().get_gcs_path('tf-flower-photo-tfrec') data_dir_by_size = { (512, 512): '/tfrecords-jpeg-512x512', (331, 331): '/tfrecords-jpeg-331x331', (224, 224): '/tfrecords-jpeg-224x224', (192, 192): '/tfrecords-jpeg-192x192' } subdir = data_dir_by_size[image_size] train_file_names = tf.io.gfile.glob(data_gcs + subdir+ '/train'+ '/*tfrec') val_file_names = tf.io.gfile.glob(data_gcs + subdir + '/val' + '/*tfrec') test_file_names = tf.io.gfile.glob(data_gcs + subdir + '/test' + '/*tfrec') imagenet_files = tf.io.gfile.glob(ext_gcs + '/imagenet' + subdir + '/*.tfrec') inaturelist_files = tf.io.gfile.glob(ext_gcs + '/inaturalist' + subdir + '/*.tfrec') openimage_files = tf.io.gfile.glob(ext_gcs + '/openimage' + subdir + '/*.tfrec') oxford_files = tf.io.gfile.glob(ext_gcs + '/oxford_102' + subdir + '/*.tfrec') tensorflow_files = tf.io.gfile.glob(ext_gcs + '/tf_flowers' + subdir + '/*.tfrec') train_file_names = train_file_names + imagenet_files + inaturelist_files + \ openimage_files + oxford_files + tensorflow_files
Petals to the Metal - Flower Classification on TPU
11,225,265
%pip install autoviz AV = AutoViz_Class() report_2 = AV.AutoViz("/kaggle/input/titanic/train.csv" )<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): example = tf.io.parse_single_example( serialized = example, features = { 'image' : tf.io.FixedLenFeature([], tf.string), 'class' : tf.io.FixedLenFeature([], tf.int64) } ) image = decode_image(example['image']) label = tf.cast(example['class'], tf.int32) return image, label def read_unlabeled_tfrecord(example): example = tf.io.parse_single_example( serialized=example, features={ 'image': tf.io.FixedLenFeature([], tf.string), 'id': tf.io.FixedLenFeature([], tf.string), } ) image = decode_image(example['image']) idnum = example['id'] return image, idnum def load_dataset(filenames, labeled = True, ordered= False): ignore_order = tf.data.Options() ignore_order.experimental_deterministic = ordered dataset = tf.data.TFRecordDataset( filenames, num_parallel_reads = tf.data.experimental.AUTOTUNE) dataset = dataset.with_options(ignore_order) dataset = dataset.map( read_labeled_tfrecord if labeled else read_unlabeled_tfrecord, num_parallel_calls=tf.data.experimental.AUTOTUNE) return dataset def count_data_items(filenames): return np.sum([ int(re.compile(r"-([0-9]*)\." ).search(filename ).group(1)) for filename in filenames]) train_dataset = load_dataset(train_file_names, labeled=True, ordered=False) val_dataset = load_dataset(val_file_names, labeled=True, ordered=False) test_dataset = load_dataset(test_file_names, labeled=False, ordered=True) num_training_samples = count_data_items(train_file_names) num_validation_samples = count_data_items(val_file_names) num_testing_samples = count_data_items(test_file_names)
Petals to the Metal - Flower Classification on TPU
11,225,265
def basic_details(df): b = pd.DataFrame() b['Missing value, %'] = round(df.isnull().sum() /df.shape[0]*100) b['N unique value'] = df.nunique() b['dtype'] = df.dtypes return b basic_details(df )<categorify>
print('Train samples:', num_training_samples, end=', ') print('Val samples:', num_validation_samples, end=', ') print('Test samples:', num_testing_samples )
Petals to the Metal - Flower Classification on TPU
11,225,265
df['Title'] = df.Name.str.extract('([A-Za-z]+)\.', expand=False) df['Title'] = df['Title'].replace(['Lady', 'Countess','Capt', 'Col', 'Don', 'Dr', 'Major', 'Rev', 'Sir', 'Jonkheer', 'Dona'], 'Rare') df['Title'] = df['Title'].replace('Mlle', 'Miss') df['Title'] = df['Title'].replace('Ms', 'Miss') df['Title'] = df['Title'].replace('Mme', 'Mrs') title_mapping = {"Mr": 1, "Miss": 2, "Mrs": 3, "Master": 4, "Rare": 5} df['Title'] = df['Title'].map(title_mapping) df['Title'] = df['Title'].fillna(0) df = df.drop(['Name'], axis=1) df["Sex"][df["Sex"] == "male"] = 0 df["Sex"][df["Sex"] == "female"] = 1 df["Sex"] = df["Sex"].astype(int) df['Age'] = df.groupby('Pclass')['Age'].transform(lambda x: x.fillna(x.median())) df["Age"] = df["Age"].astype(int) df['Age_cat'] = pd.qcut(df['Age'],q=[0,.16,.33,.49,.66,.83, 1], labels=False, precision=1) tickets = [] for i in list(df.Ticket): if not i.isdigit() : tickets.append(i.replace(".","" ).replace("/","" ).strip().split(" ")[0]) else: tickets.append("x") df["Ticket"] = tickets df = pd.get_dummies(df, columns= ["Ticket"], prefix = "T") df['Fare'] = df.groupby("Pclass")['Fare'].transform(lambda x: x.fillna(x.median())) df['Zero_Fare'] = df['Fare'].map(lambda x: 1 if x == 0 else(0)) def fare_category(fr): if fr <= 7.91: return 1 elif fr <= 14.454 and fr > 7.91: return 2 elif fr <= 31 and fr > 14.454: return 3 return 4 df['Fare_cat'] = df['Fare'].apply(fare_category) df['Cabin'] = df['Cabin'].fillna('U') df['Cabin'] = df['Cabin'].map(lambda x: re.compile("([a-zA-Z]+)" ).search(x ).group()) cabin_category = {'A':9, 'B':8, 'C':7, 'D':6, 'E':5, 'F':4, 'G':3, 'T':2, 'U':1} df['Cabin'] = df['Cabin'].map(cabin_category) df["Embarked"] = df["Embarked"].fillna("C") df["Embarked"][df["Embarked"] == "S"] = 1 df["Embarked"][df["Embarked"] == "C"] = 2 df["Embarked"][df["Embarked"] == "Q"] = 3 df["Embarked"] = df["Embarked"].astype(int) df['FamilySize'] = df['SibSp'] + df['Parch'] + 1 df['FamilySize_cat'] = df['FamilySize'].map(lambda x: 1 if x == 1 else(2 if 5 > x >= 2 else(3 if 8 > x >= 5 else 4) )) df['Alone'] = [1 if i == 1 else 0 for i in df['FamilySize']] dummy_col=['Title', 'Sex', 'Age_cat', 'SibSp', 'Parch', 'Fare_cat', 'Cabin', 'Embarked', 'Pclass', 'FamilySize_cat'] dummy = pd.get_dummies(df[dummy_col], columns=dummy_col, drop_first=False) df = pd.concat([dummy, df], axis = 1) df['FareCat_Sex'] = df['Fare_cat']*df['Sex'] df['Pcl_Sex'] = df['Pclass']*df['Sex'] df['Pcl_Title'] = df['Pclass']*df['Title'] df['Age_cat_Sex'] = df['Age_cat']*df['Sex'] df['Age_cat_Pclass'] = df['Age_cat']*df['Pclass'] df['Title_Sex'] = df['Title']*df['Sex'] df['Age_Fare'] = df['Age_cat']*df['Fare_cat'] df['SmallF'] = df['FamilySize'].map(lambda s: 1 if s == 2 else 0) df['MedF'] = df['FamilySize'].map(lambda s: 1 if 3 <= s <= 4 else 0) df['LargeF'] = df['FamilySize'].map(lambda s: 1 if s >= 5 else 0) df['Senior'] = df['Age'].map(lambda s:1 if s>70 else 0) <feature_engineering>
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,225,265
def descrictive_stat_feat(df): df = pd.DataFrame(df) dcol= [c for c in df.columns if df[c].nunique() >=10] d_median = df[dcol].median(axis=0) d_mean = df[dcol].mean(axis=0) q1 = df[dcol].apply(np.float32 ).quantile(0.25) q3 = df[dcol].apply(np.float32 ).quantile(0.75) for c in dcol: df[c+str('_median_range')] =(df[c].astype(np.float32 ).values > d_median[c] ).astype(np.int8) df[c+str('_mean_range')] =(df[c].astype(np.float32 ).values > d_mean[c] ).astype(np.int8) df[c+str('_q1')] =(df[c].astype(np.float32 ).values < q1[c] ).astype(np.int8) df[c+str('_q3')] =(df[c].astype(np.float32 ).values > q3[c] ).astype(np.int8) return df df = descrictive_stat_feat(df )<feature_engineering>
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,225,265
def basic_details(df): b = pd.DataFrame() b['Missing value'] = df.isnull().sum() b['N unique value'] = df.nunique() b['dtype'] = df.dtypes return b basic_details(df )<prepare_x_and_y>
batch_size = 16 * strategy.num_replicas_in_sync epochs = 25 batched_train_dataset = train_dataset.map(transform) batched_train_dataset = batched_train_dataset.repeat() batched_train_dataset = batched_train_dataset.shuffle(buffer_size = 2048) batched_train_dataset = batched_train_dataset.batch(batch_size) batched_train_dataset = batched_train_dataset.prefetch(tf.data.experimental.AUTOTUNE) batched_val_dataset = val_dataset.batch(batch_size) batched_val_dataset = batched_val_dataset.cache() batched_val_dataset = batched_val_dataset.prefetch(tf.data.experimental.AUTOTUNE) batched_test_dataset = test_dataset.batch(batch_size) batched_test_dataset = batched_test_dataset.prefetch(tf.data.experimental.AUTOTUNE) early_stopping = tf.keras.callbacks.EarlyStopping(monitor ='val_loss', patience= 3) save_checkpoints = tf.keras.callbacks.ModelCheckpoint('/kaggle/working/weights.{epoch:02d}-{val_loss:.2f}.hdf5', save_freq='epoch', period=4) 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_DECAY =.8 def lr_schedule(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_DECAY**(epoch - LR_RAMPUP_EPOCHS - LR_SUSTAIN_EPOCHS)+ LR_MIN return lr lr_callback = tf.keras.callbacks.LearningRateScheduler(lr_schedule, verbose = True )
Petals to the Metal - Flower Classification on TPU
11,225,265
X_train = df[:train.shape[0]] X_test_fin = df[train.shape[0]:] y = train.Survived X_train['Y'] = y df = X_train df.head(20) X = df.drop('Y', axis=1) y = df.Y<import_modules>
def get_model() : with strategy.scope() : feature_extractor = efficientnet.EfficientNetB7( weights = 'noisy-student', include_top = False, input_shape=[*image_size, 3]) feature_extractor.trainable = True model = tf.keras.Sequential([ feature_extractor, tf.keras.layers.GlobalAveragePooling2D() , tf.keras.layers.Dense(len(flower_categories), activation='softmax', dtype='float32') ]) model.compile(optimizer='adam', loss = 'sparse_categorical_crossentropy', metrics=['sparse_categorical_accuracy'] ) return model
Petals to the Metal - Flower Classification on TPU
11,225,265
from keras.models import Sequential from keras.layers import Dense, Activation, Dropout import keras from keras.optimizers import SGD import graphviz import eli5 from eli5.sklearn import PermutationImportance<split>
history = model.fit( batched_train_dataset, steps_per_epoch=num_training_samples // batch_size, epochs=epochs, callbacks=[lr_callback, early_stopping, save_checkpoints], validation_data=batched_val_dataset, verbose=2 )
Petals to the Metal - Flower Classification on TPU
11,225,265
<train_model><EOS>
print("Creating submission") test_image_dataset = batched_test_dataset.map(lambda image,idnum: image) predictions = np.argmax(model.predict(test_image_dataset), axis = -1) test_ids_dataset = batched_test_dataset.map(lambda image, idnum: idnum ).unbatch() test_ids = next(iter(test_ids_dataset.batch(num_testing_samples)) ).numpy().astype('U') np.savetxt('submission.csv', np.rec.fromarrays([test_ids, predictions]), fmt=['%s', '%d'], delimiter=',', header='id,label', comments='') print('Done!' )
Petals to the Metal - Flower Classification on TPU
11,281,017
<SOS> metric: macrofscore Kaggle data source: petals-to-the-metal-flower-classification-on-tpu<save_to_csv>
!pip install -U git+https://github.com/qubvel/efficientnet >> /dev/null
Petals to the Metal - Flower Classification on TPU
11,281,017
y_pred = sq.predict(X_test_fin) y_final =(y_pred > 0.5 ).astype(int ).reshape(X_test_fin.shape[0]) sub = pd.DataFrame() sub['PassengerId'] = test['PassengerId'] sub['Survived'] = y_final sub['Survived'] = sub.apply(lambda r: leaks[int(r['PassengerId'])] if int(r['PassengerId'])in leaks else r['Survived'], axis=1) sub.to_csv('submission.csv', index=False) print("Your submission was successfully saved!") sub.head() <import_modules>
AUTO = tf.data.experimental.AUTOTUNE
Petals to the Metal - Flower Classification on TPU
11,281,017
import keras from keras.models import Sequential from keras.layers import Dense, Dropout, Flatten from keras.layers import Conv2D, MaxPooling2D from keras.utils import to_categorical from keras.preprocessing import image import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split from keras.utils import to_categorical from tqdm import tqdm<load_from_csv>
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
11,281,017
train=pd.read_csv('.. /input/train.csv') test=pd.read_csv('.. /input/test.csv' )<prepare_x_and_y>
MIXED_PRECISION = True XLA_ACCELERATE = True if MIXED_PRECISION: if tpu: policy = tf.keras.mixed_precision.experimental.Policy('mixed_bfloat16') else: policy = tf.keras.mixed_precision.experimental.Policy('mixed_float16') mixed_precision.set_policy(policy) print('Mixed precision enabled') if XLA_ACCELERATE: tf.config.optimizer.set_jit(True) print('Accelerated Linear Algebra enabled' )
Petals to the Metal - Flower Classification on TPU
11,281,017
features = [c for c in train.columns if c not in ['label']] y=train['label'] X = train.drop(labels = ["label"],axis = 1) X = X.values.reshape(-1,28,28,1) test = test.values.reshape(-1,28,28,1) <categorify>
IMAGE_SIZES = [[512, 512], [331, 331], [224, 224], [192, 192]] IMAGE_SIZE = IMAGE_SIZES[2] BATCH_SIZE = 32 * strategy.num_replicas_in_sync print('Using IMAGE_SIZE', IMAGE_SIZE, 'and BATCH_SIZE', BATCH_SIZE )
Petals to the Metal - Flower Classification on TPU
11,281,017
y = to_categorical(y )<feature_engineering>
use_external = True BASE_PATH = KaggleDatasets().get_gcs_path('tpu-getting-started') EXT_PATH = KaggleDatasets().get_gcs_path('tf-flower-photo-tfrec') def get_path(image_size=IMAGE_SIZE): return f'{BASE_PATH}/tfrecords-jpeg-{image_size[0]}x{image_size[1]}' def get_ext_path(folder, image_size=IMAGE_SIZE): return f'{EXT_PATH}/{folder}/tfrecords-jpeg-{image_size[0]}x{image_size[1]}' TRAINING_FILES = tf.io.gfile.glob(get_path() + '/train/*.tfrec') VALIDATION_FILES = tf.io.gfile.glob(get_path() + '/val/*.tfrec') TEST_FILES = tf.io.gfile.glob(get_path() + '/test/*.tfrec') if use_external: INATURALIST = tf.io.gfile.glob(get_ext_path('inaturalist_no_test')+ '/*.tfrec') TRAINING_FILES += INATURALIST OXFORD = tf.io.gfile.glob(get_ext_path('oxford_102_no_test')+ '/*.tfrec') TRAINING_FILES += OXFORD TFFLOWERS = tf.io.gfile.glob(get_ext_path('tf_flowers_no_test')+ '/*.tfrec') TRAINING_FILES += TFFLOWERS print('Loaded Training:', len(TRAINING_FILES), 'files, Validation:', len(VALIDATION_FILES), 'files, Test:', len(TEST_FILES), 'files' )
Petals to the Metal - Flower Classification on TPU
11,281,017
X = X / 255.0 test = test / 255.0 <split>
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(len(CLASSES))
Petals to the Metal - Flower Classification on TPU
11,281,017
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42, test_size=0.1 )<choose_model_class>
class DS() : def __init__(self, files, training=True, shuffle=False, augment=False, batch_size=16, repeat=False): self.files = files self.augment = augment self.ds = tf.data.TFRecordDataset(files, num_parallel_reads = AUTO) self.ds = self.ds.map(self.read_with_label if training else self.read_without_label) if self.augment: self.ds = self.ds.map(self.augment_image) if shuffle: options = tf.data.Options() options.experimental_deterministic = False self.ds = self.ds.with_options(options) self.ds = self.ds.shuffle(2048) if repeat: self.ds = self.ds.repeat() self.ds = self.ds.batch(batch_size) self.ds = self.ds.prefetch(AUTO) def data(self): return self.ds def read_with_label(self, example): example = tf.io.parse_single_example(example, { 'image': tf.io.FixedLenFeature([], tf.string), 'class': tf.io.FixedLenFeature([], tf.int64), }) return self.decode_image(example['image']), tf.cast(example['class'], tf.int32) def read_without_label(self, example): example = tf.io.parse_single_example(example, { 'image': tf.io.FixedLenFeature([], tf.string), 'id': tf.io.FixedLenFeature([], tf.string), }) return self.decode_image(example['image']), example['id'] def decode_image(self, img): img = tf.io.decode_jpeg(img, channels=3) img = tf.cast(img, tf.float32)/ 255.0 return tf.reshape(img, [*IMAGE_SIZE, 3]) def augment_image(self, img, label): return Augmentor.process(img, IMAGE_SIZE[0]), label def count(self): n = [int(re.compile(r"-([0-9]*)\." ).search(filename ).group(1)) for filename in self.files] return np.sum(n)
Petals to the Metal - Flower Classification on TPU
11,281,017
model = Sequential() model.add(Conv2D(64, kernel_size=(3, 3), padding='same',activation='relu',input_shape=(28,28,1))) model.add(Conv2D(64,(3, 3), padding='same', activation='relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Dropout(0.25)) model.add(Conv2D(64, 5, padding='same', activation='relu')) model.add(Conv2D(64, 5, padding='same', activation='relu')) model.add(MaxPooling2D(( 2, 2))) model.add(Dropout(0.5)) model.add(Flatten()) model.add(Dense(256, activation='relu')) model.add(Dropout(0.5)) model.add(Dense(10, activation='softmax'))<choose_model_class>
items = 0 batches = 0 times = { 'batches': list() , 'items': list() , 'batch_speed': list() , 'item_speed': list() , } def loop(items, batches, times): train_ds = DS(TRAINING_FILES, augment=True, batch_size=128 ).data() start = time.time() for element in train_ds: so_far = time.time() - start batches += 1 items += len(element[0]) times['batches'].append(batches) times['items'].append(items) times['batch_speed'].append(( batches+1)/so_far) times['item_speed'].append(( items+1)/so_far) print(items, so_far,(items)/so_far) print(batches, items, so_far,(batches)/so_far,(items)/so_far) gc.collect() def show_graph(size): plt.figure(figsize=(12,6)) plt.plot(times['batches'], times['batch_speed'], color='red') plt.plot(times['items'], times['item_speed'], color='blue', linestyle='--') plt.legend() plt.title('Batch size' + str(size)) plt.show()
Petals to the Metal - Flower Classification on TPU
11,281,017
model.compile(loss='categorical_crossentropy',optimizer='Adam',metrics=['accuracy']) <train_model>
def test_dataset() : print('Training images') show_images(DS(TRAINING_FILES, augment=True, batch_size=128 ).data()) print('Validation image') show_images(DS(VALIDATION_FILES, batch_size=128 ).data()) print('Testing images') show_images(DS(TEST_FILES, training=False, batch_size=128 ).data()) print('Testing Augmented images') show_images(DS(TEST_FILES, training=False, augment=True, batch_size=128 ).data()) def show_images(ds, rows=3, columns=6): plt.figure(figsize=(12, 6)) count = 0 for i, examples in enumerate(ds.take(1)) : images = examples[0] labels = examples[1] for j, image in enumerate(images): if count == rows * columns: break plt.subplot(rows, columns, count+1, xticks=[], yticks=[]) plt.imshow(image) if labels[0].dtype == tf.string: plt.xlabel(labels[j].numpy().decode("utf-8")) else: plt.xlabel(CLASSES[labels[j]]) count += 1 plt.tight_layout() plt.show() gc.collect()
Petals to the Metal - Flower Classification on TPU
11,281,017
datagen = ImageDataGenerator( rotation_range=40, width_shift_range=0.2, height_shift_range=0.2, shear_range=0.2, zoom_range=0.2, horizontal_flip=True, fill_mode='nearest') datagen.fit(X_train )<train_model>
EFNS = [ efn.EfficientNetB0, efn.EfficientNetB1, efn.EfficientNetB2, efn.EfficientNetB3, efn.EfficientNetB4, efn.EfficientNetB5, efn.EfficientNetB6, efn.EfficientNetB7, ] def create_efficientnet(index, weight='imagenet'): pretrained_model = EFNS[index]( weights = weight, 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(1024, activation='relu', kernel_regularizer=tf.keras.regularizers.l2(0.01)) , tf.keras.layers.BatchNormalization() , tf.keras.layers.Dropout(0.5), tf.keras.layers.Dense(len(CLASSES), activation='softmax'), ], name='efn' + str(index)) return model def create_densenet() : pretrained_model = tf.keras.applications.DenseNet201( weights = 'imagenet', 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(1024, activation='relu', kernel_regularizer=tf.keras.regularizers.l2(0.01)) , tf.keras.layers.BatchNormalization() , tf.keras.layers.Dropout(0.5), tf.keras.layers.Dense(len(CLASSES), activation='softmax'), ], name='densenet') return model def create_cnn() : model = tf.keras.Sequential([ tf.keras.layers.Conv2D(16, kernel_size=3, strides=2, padding='same', activation='relu', input_shape=[*IMAGE_SIZE, 3]), tf.keras.layers.GlobalAveragePooling2D() , tf.keras.layers.Dense(len(CLASSES), activation='softmax') ], name='simple') return model
Petals to the Metal - Flower Classification on TPU
11,281,017
batch_size = 80 results = model.fit_generator(datagen.flow(X_train, y_train, batch_size = batch_size), epochs=50, steps_per_epoch=X_train.shape[0] // batch_size, validation_data=(X_test, y_test))<compute_test_metric>
def compile_models(models): for x in models: models[x].compile( optimizer = tf.keras.optimizers.Adam(learning_rate=1e-3), loss = tf.keras.losses.SparseCategoricalCrossentropy() , metrics = ['sparse_categorical_accuracy'], ) models[x].summary() print('') models = {} with strategy.scope() : start = time.time() models['efn7'] = create_efficientnet(7) print(f'Created efn7 in {(time.time() - start):.4f}s') start = time.time() models['efn6'] = create_efficientnet(6) print(f'Created efn6 in {(time.time() - start):.4f}s') start = time.time() models['efn4-noisy'] = create_efficientnet(4, 'noisy-student') print(f'Created efn4 in {(time.time() - start):.4f}s') start = time.time() models['densenet'] = create_densenet() print(f'Created densenet in {(time.time() - start):.4f}s') compile_models(models )
Petals to the Metal - Flower Classification on TPU
11,281,017
final_loss, final_acc = model.evaluate(X_test, y_test, verbose=0) print("Final loss: {0:.4f}, final accuracy: {1:.4f}".format(final_loss, final_acc))<save_to_csv>
train_ds = DS(TRAINING_FILES, augment=True, shuffle=True, batch_size=BATCH_SIZE, repeat=True) val_ds = DS(VALIDATION_FILES, batch_size=BATCH_SIZE) val_aug_ds = DS(VALIDATION_FILES, augment=True, batch_size=BATCH_SIZE) test_ds = DS(TEST_FILES, training=False, batch_size=BATCH_SIZE) print(f'Training: {train_ds.count() } images, Validation: {val_ds.count() }, Test: {test_ds.count() } images' )
Petals to the Metal - Flower Classification on TPU
11,281,017
prediction = model.predict(test) prediction = np.argmax(prediction,axis = 1) output=pd.DataFrame({"ImageId": list(range(1,len(prediction)+1)) , "Label": prediction}) output.to_csv("output.csv", index=False, header=True )<import_modules>
lr_start = 0.00005 lr_max = 0.0000125 * strategy.num_replicas_in_sync lr_min = 0.0000001 lr_ramp_ep = 5 lr_sus_ep = 0 lr_decay = 0.8 def lrfn(epoch): if epoch < lr_ramp_ep: lr =(lr_max - lr_start)/ lr_ramp_ep * epoch + lr_start elif epoch < lr_ramp_ep + lr_sus_ep: lr = lr_max else: lr =(lr_max - lr_min)* lr_decay**(epoch - lr_ramp_ep - lr_sus_ep)+ lr_min return lr lr_callback = tf.keras.callbacks.LearningRateScheduler(lrfn, verbose=True) count = range(100) plt.figure(figsize=(12, 6)) plt.subplot(1, 3, 1) plt.plot(count, [lrfn(x)for x in count]) cosine_decay_learning_rate = tf.keras.experimental.CosineDecayRestarts( 0.001, 0.8, t_mul=2.0, m_mul=1.0, alpha=0.0, name=None )
Petals to the Metal - Flower Classification on TPU