kernel_id
int64 24.2k
23.3M
| prompt
stringlengths 8
1.85M
| completetion
stringlengths 1
182k
| comp_name
stringlengths 5
57
|
---|---|---|---|
14,144,790 | %%time
module_url = 'https://tfhub.dev/google/universal-sentence-encoder-large/4'
embed = hub.KerasLayer(module_url, trainable=False, name='USE_embedding' )<choose_model_class> | from tensorflow.keras.applications.vgg16 import VGG16
from tensorflow.keras.applications.vgg19 import VGG19
from tensorflow.keras.applications.inception_v3 import InceptionV3
from tensorflow.keras.applications.inception_resnet_v2 import InceptionResNetV2
from tensorflow.keras.applications.densenet import DenseNet121, DenseNet169, DenseNet201
from tensorflow.keras.applications.xception import Xception
from tensorflow.keras.applications.resnet50 import ResNet50
from tensorflow.keras.applications.resnet_v2 import ResNet50V2, ResNet101V2, ResNet152V2
from tensorflow.keras.applications.nasnet import NASNetLarge
from efficientnet.tfkeras import EfficientNetB7, EfficientNetL2, EfficientNetB0, EfficientNetB1 | Petals to the Metal - Flower Classification on TPU |
14,144,790 | def build_model(embed):
model = Sequential([
Input(shape=[], dtype=tf.string),
embed,
Dense(128, activation='relu'),
BatchNormalization() ,
Dropout(0.5),
Dense(64, activation='relu'),
BatchNormalization() ,
Dropout(0.5),
Dense(1, activation='sigmoid')
])
model.compile(Adam(lr=0.0001), loss='binary_crossentropy', metrics=['accuracy'])
return model<train_model> | %matplotlib inline
print("Tensorflow version " + tf.__version__ ) | Petals to the Metal - Flower Classification on TPU |
14,144,790 | checkpoint = ModelCheckpoint('model.h5', monitor='val_loss', save_best_only=True)
train_history = model.fit(
train_data, train_labels,
validation_split=0.2,
epochs=20,
callbacks=[checkpoint],
batch_size=32
)<predict_on_test> | AUTO = tf.data.experimental.AUTOTUNE | Petals to the Metal - Flower Classification on TPU |
14,144,790 | model.load_weights('model.h5')
test_pred = model.predict(test_data )<save_to_csv> | GCS_DS_PATH = KaggleDatasets().get_gcs_path('tpu-getting-started')
MORE_IMAGES_GCS_DS_PATH = KaggleDatasets().get_gcs_path('tf-flower-photo-tfrec' ) | Petals to the Metal - Flower Classification on TPU |
14,144,790 | submission['target'] = test_pred.round().astype(int)
submission.to_csv('submission.csv', index=False )<import_modules> | IMAGE_SIZE = [512, 512]
EPOCHS = 20
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')
MOREIMAGES_PATH_SELECT = {
192: '/tfrecords-jpeg-192x192',
224: '/tfrecords-jpeg-224x224',
331: '/tfrecords-jpeg-331x331',
512: '/tfrecords-jpeg-512x512'
}
MOREIMAGES_PATH = MOREIMAGES_PATH_SELECT[IMAGE_SIZE[0]]
IMAGENET_FILES = tf.io.gfile.glob(MORE_IMAGES_GCS_DS_PATH + '/imagenet' + MOREIMAGES_PATH + '/*.tfrec')
INATURELIST_FILES = tf.io.gfile.glob(MORE_IMAGES_GCS_DS_PATH + '/inaturalist' + MOREIMAGES_PATH + '/*.tfrec')
OPENIMAGE_FILES = tf.io.gfile.glob(MORE_IMAGES_GCS_DS_PATH + '/openimage' + MOREIMAGES_PATH + '/*.tfrec')
TRAINING_FILENAMES = TRAINING_FILENAMES + VALIDATION_FILENAMES + IMAGENET_FILES + INATURELIST_FILES + OPENIMAGE_FILES
SEED = 2020
NUM_TRAINING_IMAGES = 12753
NUM_TEST_IMAGES = 7382
STEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE | Petals to the Metal - Flower Classification on TPU |
14,144,790 | import numpy as np
import pandas as pd
import tensorflow as tf
from IPython.display import clear_output
from sklearn.model_selection import train_test_split<import_modules> | 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):
flag = random.randint(1,3)
coef_1 = random.randint(70, 90)* 0.01
coef_2 = random.randint(70, 90)* 0.01
if flag == 1:
image = tf.image.random_flip_left_right(image, seed=SEED)
elif flag == 2:
image = tf.image.random_flip_up_down(image, seed=SEED)
else:
image = tf.image.random_crop(image, [int(IMAGE_SIZE[0]*coef_1), int(IMAGE_SIZE[0]*coef_2), 3],seed=SEED)
return image, label
def get_training_dataset() :
dataset = load_dataset(TRAINING_FILENAMES, labeled=True)
dataset = dataset.map(data_augment, num_parallel_calls=AUTO)
dataset = dataset.repeat()
dataset = dataset.shuffle(2048)
dataset = dataset.batch(BATCH_SIZE)
dataset = dataset.prefetch(AUTO)
return dataset
def get_validation_dataset() :
dataset = load_dataset(VALIDATION_FILENAMES, labeled=True, ordered=False)
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 |
14,144,790 | print(tf.__version__ )<load_from_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 =.75
def lrfn(epoch):
if epoch < LR_RAMPUP_EPOCHS:
lr =(LR_MAX - LR_START)/ LR_RAMPUP_EPOCHS * epoch + LR_START
elif epoch < LR_RAMPUP_EPOCHS + LR_SUSTAIN_EPOCHS:
lr = LR_MAX
else:
lr =(LR_MAX - LR_MIN)* LR_EXP_DECAY**(epoch - LR_RAMPUP_EPOCHS - LR_SUSTAIN_EPOCHS)+ LR_MIN
return lr
lr_callback = tf.keras.callbacks.LearningRateScheduler(lrfn, verbose=True)
rng = [i for i in range(EPOCHS)]
y = [lrfn(x)for x in rng]
plt.plot(rng, y)
print("Learning rate schedule: {:.3g} to {:.3g} to {:.3g}".format(y[0], max(y), y[-1])) | Petals to the Metal - Flower Classification on TPU |
14,144,790 | train_data = pd.read_csv('/kaggle/input/titanic/train.csv')
test_data = pd.read_csv("/kaggle/input/titanic/test.csv")
train_data.head(100 )<feature_engineering> | def get_model(use_model):
base_model = use_model(weights='imagenet',
include_top=False, pooling='avg',
input_shape=(*IMAGE_SIZE, 3))
x = base_model.output
predictions = Dense(104, activation='softmax' )(x)
return Model(inputs=base_model.input, outputs=predictions)
with strategy.scope() :
model = get_model(DenseNet201)
model.compile(
optimizer='nadam',
loss = 'sparse_categorical_crossentropy',
metrics=['sparse_categorical_accuracy']
)
| Petals to the Metal - Flower Classification on TPU |
14,144,790 | def clean_data(df):
df['Age'].fillna(0, inplace = True)
df['Embarked'].fillna('S', inplace = True)
df["Fare"] = df["Fare"].fillna(df["Fare"].median())
df['Family_Size'] = df['SibSp'] + df['Parch'] + 1
df['Title'] = df.Name.str.extract('([A-Za-z]+)\.', expand=False)
df['Title'] = df['Title'].replace(['Lady', 'Countess','Capt', 'Col','Don',\
'Major', 'Rev', 'Sir', 'Jonkheer', 'Dona', 'Dr'], 'Other')
df['Title'] = df['Title'].replace('Mlle', 'Miss')
df['Title'] = df['Title'].replace('Ms', 'Miss')
df['Title'] = df['Title'].replace('Mme', 'Mrs')
df['Title'].fillna('Unknown', inplace = True)
df['Title'] = df['Title'].astype(str)
df['Cabin'].fillna('U', inplace = True)
df['Deck'] = df["Cabin"].str.slice(0,1)
df['Last_Name'] = df['Name'].apply(lambda x: str.split(x, ",")[0])
Age_Title_Group = df.groupby('Title')['Age'].mean()
df['Title_Age'] = df['Age']
Titles = df['Title'].unique()
for i in range(len(Titles)) :
df.loc[(df['Age']==0)&(df['Title']== Titles[i]), 'Title_Age'] = Age_Title_Group[Titles[i]]
df['Age'] = df['Title_Age'].astype(int)
return df<drop_column> | history = model.fit(get_training_dataset() ,
steps_per_epoch=STEPS_PER_EPOCH,
epochs=EPOCHS,
callbacks=[lr_callback, ModelCheckpoint(filepath='my_ef_net_b7.h5', monitor='val_loss',
save_best_only=True)],
validation_data=get_validation_dataset() ,
workers = 3)
plt.plot(history.history['sparse_categorical_accuracy'],
label='Оценка точности на обучающем наборе')
plt.plot(history.history['val_sparse_categorical_accuracy'],
label='Оценка точности на проверочном наборе')
plt.xlabel('Эпоха обучения')
plt.ylabel('Оценка точности')
plt.legend()
plt.show() | Petals to the Metal - Flower Classification on TPU |
14,144,790 | train_data = clean_data(train_data)
test_data = clean_data(test_data )<groupby> | model = tf.keras.models.load_model('my_ef_net_b7.h5' ) | Petals to the Metal - Flower Classification on TPU |
14,144,790 | <drop_column><EOS> | test_ds = get_test_dataset(ordered=True)
print('Вычисляем предсказания...')
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('Создание файла submission.csv...')
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 |
14,009,408 | <SOS> metric: macrofscore Kaggle data source: petals-to-the-metal-flower-classification-on-tpu<split> | !pip install -q efficientnet | Petals to the Metal - Flower Classification on TPU |
14,009,408 | train_data, val_data = train_test_split(train_data, test_size=0.2)
print(len(train_data), 'train examples')
print(len(val_data), 'validation examples')
print(len(test_data), 'test examples' )<create_dataframe> | %matplotlib inline
print("Tensorflow version " + tf.__version__ ) | Petals to the Metal - Flower Classification on TPU |
14,009,408 | def df_to_dataset(df, shuffle, test, n_epochs =None):
def input_fn() :
dataframe = df.copy()
NUM_EXAMPLES = len(dataframe)
if test:
ds = tf.data.Dataset.from_tensor_slices(dict(dataframe))
else:
labels = dataframe.pop('Survived')
ds = tf.data.Dataset.from_tensor_slices(( dict(dataframe), labels))
if shuffle:
ds.shuffle(buffer_size=NUM_EXAMPLES)
ds = ds.repeat(n_epochs)
ds = ds.batch(NUM_EXAMPLES)
return ds
return input_fn<create_dataframe> | GCS_DS_PATH = KaggleDatasets().get_gcs_path("tpu-getting-started" ) | Petals to the Metal - Flower Classification on TPU |
14,009,408 | train_ds = df_to_dataset(train_data, shuffle=True, test=False)
val_ds = df_to_dataset(val_data, shuffle=False, test=False, n_epochs=1)
test_ds = df_to_dataset(test_data, shuffle=False, test=True, n_epochs=1 )<train_model> | IMAGE_SIZE = [512, 512]
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]]
VALIDATION_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/val/*.tfrec')
TEST_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/test/*.tfrec')
SEED = 2020 | Petals to the Metal - Flower Classification on TPU |
14,009,408 | n_batches = 1
est = tf.estimator.BoostedTreesClassifier(feature_columns,
n_batches_per_layer=n_batches)
est.train(train_ds, max_steps=100)
result = est.evaluate(val_ds)
clear_output()
print(pd.Series(result))<predict_on_test> | 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 get_validation_dataset() :
dataset = load_dataset(VALIDATION_FILENAMES, labeled=True, ordered=True)
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_VALIDATION_IMAGES = count_data_items(VALIDATION_FILENAMES)
NUM_TEST_IMAGES = count_data_items(TEST_FILENAMES)
print('Dataset: {} validation images, {} unlabeled test images'.format(NUM_VALIDATION_IMAGES, NUM_TEST_IMAGES)) | Petals to the Metal - Flower Classification on TPU |
14,009,408 | predictions = est.predict(test_ds)
probs = pd.Series([pred['probabilities'][1] for pred in predictions])
print(probs)
predictions =(probs >= 0.5 ).astype(int )<create_dataframe> | def get_model(use_model):
base_model = use_model(weights='imagenet',
include_top=False, pooling='avg',
input_shape=(*IMAGE_SIZE, 3))
x = base_model.output
predictions = Dense(104, activation='softmax' )(x)
model = Model(inputs=base_model.input, outputs=predictions)
model.compile(
optimizer='nadam',
loss = 'sparse_categorical_crossentropy',
metrics=['sparse_categorical_accuracy']
)
return model
with strategy.scope() :
model1 = get_model(EfficientNetB7)
model1.load_weights("/kaggle/input/more-data-with-efficientnetb7/my_ef_net_b7.h5" ) | Petals to the Metal - Flower Classification on TPU |
14,009,408 | predictions_dataframe = test_data[["PassengerId"]]
predictions_dataframe["Survived"] = predictions<save_to_csv> | def get_model(use_model):
base_model = use_model(weights='imagenet',
include_top=False, pooling='avg',
input_shape=(*IMAGE_SIZE, 3))
x = base_model.output
predictions = Dense(104, activation='softmax' )(x)
model = Model(inputs=base_model.input, outputs=predictions)
model.compile(
optimizer='nadam',
loss = 'sparse_categorical_crossentropy',
metrics=['sparse_categorical_accuracy']
)
return model
with strategy.scope() :
model2 = get_model(VGG19)
model2.load_weights("/kaggle/input/start-with-pre-train/my_ef_net_b7.h5" ) | Petals to the Metal - Flower Classification on TPU |
14,009,408 | predictions_dataframe.to_csv("my_submission.csv",index=False )<load_from_csv> | val_dataset = get_validation_dataset()
images_ds = val_dataset.map(lambda image, label: image)
labels_ds = val_dataset.map(lambda image, label: label ).unbatch()
val_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):
val_probabilities = alpha*m1+(1-alpha)*m2
val_predictions = np.argmax(val_probabilities, axis=-1)
scores.append(f1_score(val_labels, val_predictions, labels=range(104), average='macro'))
best_alpha = np.argmax(scores)/100
print('Best alpha: ' + str(best_alpha)) | Petals to the Metal - Flower Classification on TPU |
14,009,408 | <count_missing_values><EOS> | test_ds = get_test_dataset(ordered=True)
best_alpha = 0.48
print('Вычисляем предсказания...')
test_images_ds = test_ds.map(lambda image, idnum: image)
probabilities1 = model1.predict(test_images_ds)
probabilities2 = model2.predict(test_images_ds)
probabilities = best_alpha * probabilities1 +(1 - best_alpha)* probabilities2
predictions = np.argmax(probabilities, axis=-1)
print(predictions)
print('Создание файла submission.csv...')
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 |
13,709,597 | <SOS> metric: macrofscore Kaggle data source: petals-to-the-metal-flower-classification-on-tpu<count_missing_values> | !pip install efficientnet | Petals to the Metal - Flower Classification on TPU |
13,709,597 | Total = Total.drop(['Ticket','Cabin'], axis = 1)
fare_mode = Total['Fare'].mode().iat[0]
Total['Fare'].fillna(fare_mode,inplace = True)
embarked_mode = Total['Embarked'].mode().iat[0]
Total['Embarked'].fillna(embarked_mode, inplace = True)
for column in Total:
if Total[column].isnull().sum() != 0:
print('Missing values in',column,':', Total[column].isnull().sum() )<categorify> | import random, re, math, os
import numpy as np
import pandas as pd
import tensorflow as tf
import matplotlib.pyplot as plt
import tensorflow_addons as tfa
from kaggle_datasets import KaggleDatasets
from tensorflow.keras.mixed_precision import experimental as mixed_precision
import tensorflow.keras.backend as K
import efficientnet.tfkeras as efn
from sklearn.metrics import f1_score, precision_score, recall_score, confusion_matrix
import datetime
import tqdm
import json
from collections import Counter
import gc | Petals to the Metal - Flower Classification on TPU |
13,709,597 | sex_dummy = pd.get_dummies(Total['Sex'])
Total = Total.drop('Sex', axis = 1)
Total = pd.concat([Total, sex_dummy], axis = 1)
embark_dummy = pd.get_dummies(Total['Embarked'])
Total = Total.drop('Embarked', axis = 1)
Total = pd.concat([Total, embark_dummy], axis = 1)
Total<drop_column> | IMAGE_SIZE = [512, 512]
EPOCHS = 16
BATCH_SIZE = 16 * strategy.num_replicas_in_sync
SEED = 100 | Petals to the Metal - Flower Classification on TPU |
13,709,597 | title = lambda x: x.split(',')[1].split('.')[0].strip()
Total['Title']=Total['Name'].map(title)
Total = Total.drop('Name', axis = 1)
Total<categorify> | GCS_DS_PATH = KaggleDatasets().get_gcs_path('tpu-getting-started')
GCS_PATH_SELECT = {
192: GCS_DS_PATH + '/tfrecords-jpeg-192x192',
224: GCS_DS_PATH + '/tfrecords-jpeg-224x224',
331: GCS_DS_PATH + '/tfrecords-jpeg-331x331',
512: GCS_DS_PATH + '/tfrecords-jpeg-512x512'
}
GCS_PATH = GCS_PATH_SELECT[IMAGE_SIZE[0]]
TRAINING_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/train/*.tfrec')
VALIDATION_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/val/*.tfrec')
TEST_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/test/*.tfrec' ) | Petals to the Metal - Flower Classification on TPU |
13,709,597 | title_dummy = pd.get_dummies(Total['Title'])
title_dummy
title_dummy['Mil'] = title_dummy['Capt']+title_dummy['Col']+title_dummy['Major']
title_dummy = title_dummy.drop(['Capt','Col','Major'], axis = 1)
title_dummy['Senior Male Honorific'] = title_dummy['Don']+title_dummy['Sir']
title_dummy = title_dummy.drop(['Don','Sir'], axis = 1)
title_dummy['Senior Female Honorific'] = title_dummy['Dona']+title_dummy['Mme']+title_dummy['Lady']
title_dummy = title_dummy.drop(['Dona','Mme','Lady'], axis = 1)
title_dummy['Ms+Mlle'] = title_dummy['Ms']+title_dummy['Mlle']
title_dummy = title_dummy.drop(['Ms','Mlle'], axis = 1)
title_dummy['Fancy'] = title_dummy['Jonkheer']+title_dummy['the Countess']
title_dummy = title_dummy.drop(['Jonkheer','the Countess'], axis = 1)
Total = Total.drop('Title', axis = 1)
Total = pd.concat([Total, title_dummy], axis = 1)
Total<filter> | 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 |
13,709,597 | Age_Total = Total
Age_Total = Age_Total.dropna()
Age_Total
def nans(df): return df[df.isnull().any(axis=1)]
Age_Total_Predict = nans(Total)
Age_Total_Predict<drop_column> | 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 |
13,709,597 | col = list(Age_Total.columns)
col.remove('Age')
col.remove('Survived')
Age_Total[col]<normalization> | def batch_to_numpy_images_and_labels(data):
images, labels = data
numpy_images = images.numpy()
numpy_labels = labels.numpy()
if numpy_labels.dtype == object:
numpy_labels = [None for _ in enumerate(numpy_images)]
return numpy_images, numpy_labels
def title_from_label_and_target_(label, correct_label):
if correct_label is None:
return CLASSES[label], True
correct =(label == correct_label)
return "{} [{}{}{}]".format(CLASSES[label], 'OK' if correct else 'NO', u"\u2192" if not correct else '',
CLASSES[correct_label] if not correct else ''), correct
def display_one_flower(image, title, subplot, red = False, titlesize = 16):
plt.subplot(*subplot)
plt.axis('off')
plt.imshow(image)
if len(title)> 0:
plt.title(title, fontsize = int(titlesize)if not red else int(titlesize / 1.2), color = 'red' if red else 'black', fontdict={'verticalalignment':'center'}, pad=int(titlesize/1.5))
return(subplot[0], subplot[1], subplot[2] + 1)
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()
def dataset_to_numpy_util(dataset, N):
dataset = dataset.unbatch().batch(N)
for images, labels in dataset:
numpy_images = images.numpy()
numpy_labels = labels.numpy()
break;
return numpy_images, numpy_labels
def title_from_label_and_target(label, correct_label):
label = np.argmax(label, axis = -1)
correct =(label == correct_label)
return "{} [{}{}{}]".format(CLASSES[label], str(correct), ', should be ' if not correct else '',
CLASSES[correct_label] if not correct else ''), correct
def display_one_flower_eval(image, title, subplot, red = False):
plt.subplot(subplot)
plt.axis('off')
plt.imshow(image)
plt.title(title, fontsize = 14, color = 'red' if red else 'black')
return subplot + 1
def display_9_images_with_predictions(images, predictions, labels):
subplot = 331
plt.figure(figsize =(13,13))
for i, image in enumerate(images):
title, correct = title_from_label_and_target(predictions[i], labels[i])
subplot = display_one_flower_eval(image, title, subplot, not correct)
if i >= 8:
break;
plt.tight_layout()
plt.subplots_adjust(wspace = 0.1, hspace = 0.1)
plt.show() | Petals to the Metal - Flower Classification on TPU |
13,709,597 | x = Age_Total[col]
x_test = Age_Total_Predict[col]
y_train = Age_Total['Age']
x_train = StandardScaler().fit(x ).transform(x)
x_test = StandardScaler().fit(x_test ).transform(x_test )<train_on_grid> | 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 | Petals to the Metal - Flower Classification on TPU |
13,709,597 | lasso = LassoCV(alphas = [0.01, 0.05, 0.1, 0.15,0.5] ).fit(x_train, y_train)
alpha = 0.1
lasso_tuned = LassoCV(alphas = [0.8*alpha, 0.9*alpha, alpha, 1.1*alpha, 1.2*alpha] ).fit(x_train, y_train )<train_on_grid> | 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_labeled_id_tfrecord(example):
LABELED_ID_TFREC_FORMAT = {
"image": tf.io.FixedLenFeature([], tf.string),
"class": tf.io.FixedLenFeature([], tf.int64),
"id": tf.io.FixedLenFeature([], tf.string),
}
example = tf.io.parse_single_example(example, LABELED_ID_TFREC_FORMAT)
image = decode_image(example['image'])
label = tf.cast(example['class'], tf.int32)
idnum = example['id']
return image, label, idnum | Petals to the Metal - Flower Classification on TPU |
13,709,597 | svm_age = svm.SVR(kernel = 'rbf')
svm_age.fit(x_train, y_train )<train_on_grid> | 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 |
13,709,597 | ridge = Ridge()
parameters = {'alpha': [1e-15, 1e-10, 1e-8, 1e-4, 1e-3, 1e-2, 1, 5, 10, 20]}
ridge_age = GridSearchCV(ridge, parameters, scoring = 'neg_root_mean_squared_error', cv=5)
ridge_age.fit(x_train, y_train)
print(ridge_age.best_params_)
print(-ridge_age.best_score_ )<compute_train_metric> | def load_dataset(filenames, labeled = True, ordered = False):
ignore_order = tf.data.Options()
if not ordered:
ignore_order.experimental_deterministic = False
dataset = tf.data.TFRecordDataset(filenames, num_parallel_reads = AUTO)
dataset = dataset.with_options(ignore_order)
dataset = dataset.map(read_labeled_id_tfrecord if labeled else read_unlabeled_tfrecord, num_parallel_calls=AUTO)
return dataset | Petals to the Metal - Flower Classification on TPU |
13,709,597 | print('The average R squared score for the lasso model is:', -cross_val_score(lasso_tuned, x_train, y_train, scoring ='neg_root_mean_squared_error' ).mean())
print('The average R squared score for the svm model is:', -cross_val_score(svm_age, x_train, y_train, scoring ='neg_root_mean_squared_error' ).mean())
print('The average R squared score for the ridge model is:', -ridge_age.best_score_)
<predict_on_test> | def get_training_dataset() :
train = load_dataset(TRAINING_FILENAMES, labeled = True)
train = train.map(lambda image, label, idnum: [image, label])
train = train.repeat()
train = train.shuffle(2048)
train = train.batch(BATCH_SIZE)
train = train.prefetch(AUTO)
return train
def get_training_dataset_preview(ordered = True):
train = load_dataset(TRAINING_FILENAMES, labeled = True, ordered = ordered)
train = train.batch(BATCH_SIZE)
train = train.cache()
train = train.prefetch(AUTO)
return train | Petals to the Metal - Flower Classification on TPU |
13,709,597 | predicted_ages = pd.DataFrame(lasso_tuned.predict(x_test), columns=['Age'])
Age_Total_Predict.drop('Age',axis = 1)
Age_Total_Predict = Age_Total_Predict.assign(Age = lasso_tuned.predict(x_test ).round())
Age_Total_Predict['PassengerId'] = Age_Total_Predict.index
Age_Total_Predict = Age_Total_Predict.reset_index(drop=True)
Age_Total_Predict<feature_engineering> | def get_validation_dataset(ordered = False):
validation = load_dataset(VALIDATION_FILENAMES, labeled = True, ordered = ordered)
validation = validation.map(lambda image, label, idnum: [image, label])
validation = validation.batch(BATCH_SIZE)
validation = validation.cache()
validation = validation.prefetch(AUTO)
return validation | Petals to the Metal - Flower Classification on TPU |
13,709,597 | Age_Total['PassengerId'] = Age_Total.index
Age_Total = Age_Total.reset_index(drop=True)
Total_Processed = pd.concat([Age_Total_Predict,Age_Total])
Total_Processed.set_index('PassengerId', inplace = True)
Total_Processed = Total_Processed.sort_index()
fix_neg = lambda x: x + 11.148738330664404 if x < 0 else x
Total_Processed['Age'] = Total_Processed['Age'].apply(fix_neg)
Total_Processed<split> | def get_test_dataset(ordered = False):
test = load_dataset(TEST_FILENAMES, labeled = False, ordered = ordered)
test = test.batch(BATCH_SIZE)
test = test.prefetch(AUTO)
return test | Petals to the Metal - Flower Classification on TPU |
13,709,597 | Train_Processed = Total_Processed[:len(train)]
Test_Processed = Total_Processed[len(train):]<prepare_x_and_y> | 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 |
13,709,597 | col = list(Train_Processed.columns)
col.remove('Survived')
x_train = Train_Processed[col]
y_train = Train_Processed['Survived']
y_train = y_train.astype('int')
x_final = Test_Processed[col]
x_train = preprocessing.StandardScaler().fit(x_train ).transform(x_train)
x_final= preprocessing.StandardScaler().fit(x_final ).transform(x_final )<train_on_grid> | train_dataset_aug = get_training_dataset()
display_batch_of_images(next(iter(train_dataset_aug.unbatch().batch(20))))
display_batch_of_images(next(iter(train_dataset_aug.unbatch().batch(20))))
display_batch_of_images(next(iter(train_dataset_aug.unbatch().batch(20)))) | Petals to the Metal - Flower Classification on TPU |
13,709,597 | k_score = []
k_range = range(1,16)
for k in k_range:
neigh = KNeighborsClassifier(n_neighbors = k ).fit(x_train,y_train)
score = -cross_val_score(neigh, x_train, y_train, scoring ='neg_root_mean_squared_error' ).mean()
k_score.append(score)
Scores = pd.DataFrame(k_score, columns = ['Score'])
Scores.index += 1
Scores.sort_values('Score' )<save_to_csv> | validation_dataset_aug = get_validation_dataset()
display_batch_of_images(next(iter(validation_dataset_aug.unbatch().batch(20))))
display_batch_of_images(next(iter(validation_dataset_aug.unbatch().batch(20))))
display_batch_of_images(next(iter(validation_dataset_aug.unbatch().batch(20)))) | Petals to the Metal - Flower Classification on TPU |
13,709,597 | neigh = KNeighborsClassifier(n_neighbors = 8 ).fit(x_train,y_train)
y_KNN = pd.DataFrame(neigh.predict(x_final), columns = ['Survived'])
y_KNN = y_KNN.assign(PassengerId = Test_Processed.index)
cols = y_KNN.columns.tolist()
cols = cols[-1:] + cols[:-1]
y_KNN = y_KNN[cols]
filename = 'Titanic Predictions KNN.csv'
y_KNN.to_csv(filename,index=False)
print('Saved file: ' + filename )<compute_train_metric> | test_dataset_aug = get_test_dataset()
display_batch_of_images(next(iter(test_dataset_aug.unbatch().batch(20))))
display_batch_of_images(next(iter(test_dataset_aug.unbatch().batch(20))))
display_batch_of_images(next(iter(test_dataset_aug.unbatch().batch(20)))) | Petals to the Metal - Flower Classification on TPU |
13,709,597 | svm_lin = svm.SVC(kernel='linear' ).fit(x_train, y_train)
print('The average R squared score for the svm_lin is:', cross_val_score(svm_lin, x_train, y_train, scoring ='accuracy' ).mean())
svm_rbf = svm.SVC(kernel='rbf' ).fit(x_train, y_train)
print('The average R squared score for the svm_rbf is:', cross_val_score(svm_rbf, x_train, y_train, scoring ='accuracy' ).mean() )<train_on_grid> | def lrfn(epoch):
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
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 |
13,709,597 | gammas = [0.01,0.1, 1, 10, 100]
for gamma in gammas:
svm_rbf = svm.SVC(kernel='rbf' ).fit(x_train, y_train)
print('The average R squared score for the svm_rbf with a gamma of',gamma,' is:', cross_val_score(svm_rbf, x_train, y_train, scoring ='accuracy' ).mean() )<compute_train_metric> | with strategy.scope() :
enet = efn.EfficientNetB7(
input_shape =(512, 512, 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() ,
loss = 'sparse_categorical_crossentropy',
metrics = ['sparse_categorical_accuracy']
)
model.summary()
model.save('ML_finalproject.h5' ) | Petals to the Metal - Flower Classification on TPU |
13,709,597 | cs = [0.65,0.67]
for c in cs:
svm_rbf = svm.SVC(kernel='rbf', C=c ).fit(x_train, y_train)
print('The average R squared score for the svm_rbf with a C of',c,' is:', cross_val_score(svm_rbf, x_train, y_train, scoring ='accuracy' ).mean() )<save_to_csv> | gc.enable()
def get_training_dataset_raw() :
dataset = load_dataset(TRAINING_FILENAMES, labeled = True, ordered = False)
return dataset
raw_training_dataset = get_training_dataset_raw()
label_counter = Counter()
for images, labels, id in raw_training_dataset:
label_counter.update([labels.numpy() ])
del raw_training_dataset
TARGET_NUM_PER_CLASS = 122
def get_weight_for_class(class_id):
counting = label_counter[class_id]
weight = TARGET_NUM_PER_CLASS / counting
return weight
weight_per_class = {class_id: get_weight_for_class(class_id)for class_id in range(104)} | Petals to the Metal - Flower Classification on TPU |
13,709,597 | svm_rbf = svm.SVC(kernel='rbf' ).fit(x_train, y_train)
y_SVM = pd.DataFrame(svm_rbf.predict(x_final), columns = ['Survived'])
y_SVM = y_SVM.assign(PassengerId = Test_Processed.index)
cols = y_SVM.columns.tolist()
cols = cols[-1:] + cols[:-1]
y_SVM = y_SVM[cols]
filename = 'Titanic Predictions SVM.csv'
y_SVM.to_csv(filename,index=False)
print('Saved file: ' + filename )<compute_test_metric> | history = model.fit(
get_training_dataset() ,
steps_per_epoch = STEPS_PER_EPOCH,
epochs = EPOCHS,
callbacks = [lr_callback],
validation_data = get_validation_dataset() ,
class_weight = weight_per_class
) | Petals to the Metal - Flower Classification on TPU |
13,709,597 | print('The average accuracy score for the SVM model is:', cross_val_score(svm_rbf, x_train, y_train, scoring ='accuracy' ).mean())
<install_modules> | cmdataset = get_validation_dataset(ordered = True)
images_ds = cmdataset.map(lambda image, label: image)
labels_ds = cmdataset.map(lambda image, label: label ).unbatch()
cm_correct_labels = next(iter(labels_ds.batch(NUM_VALIDATION_IMAGES)) ).numpy()
cm_probabilities = model.predict(images_ds)
cm_predictions = np.argmax(cm_probabilities, axis = -1)
print("Correct labels: ", cm_correct_labels.shape, cm_correct_labels)
print("Predicted labels: ", cm_predictions.shape, cm_predictions ) | Petals to the Metal - Flower Classification on TPU |
13,709,597 | !pip install category_encoders<install_modules> | 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')
cmat =(cmat.T / cmat.sum(axis = 1)).T
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 |
13,709,597 | <import_modules><EOS> | test_ds = get_test_dataset(ordered = True)
test_images_ds = test_ds.map(lambda image, idnum: image)
probabilities = model.predict(test_images_ds)
predictions = np.argmax(probabilities, axis = -1)
print(predictions)
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')
test = pd.DataFrame({"id": test_ids, "label": predictions})
print(test.head)
test.to_csv("submission.csv",index = False ) | Petals to the Metal - Flower Classification on TPU |
13,589,735 | <SOS> metric: macrofscore Kaggle data source: petals-to-the-metal-flower-classification-on-tpu<set_options> | !pip install -q efficientnet | Petals to the Metal - Flower Classification on TPU |
13,589,735 | %matplotlib inline
warnings.filterwarnings('ignore' )<load_from_csv> | %matplotlib inline
print("Tensorflow version " + tf.__version__ ) | Petals to the Metal - Flower Classification on TPU |
13,589,735 | train = pd.read_csv(".. /input/train.csv")
test = pd.read_csv(".. /input/test.csv")
train.describe(include="all" )<count_missing_values> | GCS_DS_PATH = KaggleDatasets().get_gcs_path("tpu-getting-started" ) | Petals to the Metal - Flower Classification on TPU |
13,589,735 | print(pd.isnull(train ).sum() )<count_missing_values> | IMAGE_SIZE = [512, 512]
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]]
VALIDATION_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/val/*.tfrec')
TEST_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/test/*.tfrec')
SEED = 2020 | Petals to the Metal - Flower Classification on TPU |
13,589,735 | print(pd.isnull(test ).sum() )<feature_engineering> | def decode_image(image_data):
image = tf.image.decode_jpeg(image_data, channels=3)
image = tf.cast(image, tf.float32)/ 255.0
image = tf.reshape(image, [*IMAGE_SIZE, 3])
return image
def read_labeled_tfrecord(example):
LABELED_TFREC_FORMAT = {
"image": tf.io.FixedLenFeature([], tf.string),
"class": tf.io.FixedLenFeature([], tf.int64),
}
example = tf.io.parse_single_example(example, LABELED_TFREC_FORMAT)
image = decode_image(example['image'])
label = tf.cast(example['class'], tf.int32)
return image, label
def read_unlabeled_tfrecord(example):
UNLABELED_TFREC_FORMAT = {
"image": tf.io.FixedLenFeature([], tf.string),
"id": tf.io.FixedLenFeature([], tf.string),
}
example = tf.io.parse_single_example(example, UNLABELED_TFREC_FORMAT)
image = decode_image(example['image'])
idnum = example['id']
return image, idnum
def load_dataset(filenames, labeled=True, ordered=False):
ignore_order = tf.data.Options()
if not ordered:
ignore_order.experimental_deterministic = False
dataset = tf.data.TFRecordDataset(filenames, num_parallel_reads=AUTO)
dataset = dataset.with_options(ignore_order)
dataset = dataset.map(read_labeled_tfrecord if labeled else read_unlabeled_tfrecord, num_parallel_calls=AUTO)
return dataset
def get_validation_dataset() :
dataset = load_dataset(VALIDATION_FILENAMES, labeled=True, ordered=True)
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_VALIDATION_IMAGES = count_data_items(VALIDATION_FILENAMES)
NUM_TEST_IMAGES = count_data_items(TEST_FILENAMES)
print('Dataset: {} validation images, {} unlabeled test images'.format(NUM_VALIDATION_IMAGES, NUM_TEST_IMAGES)) | Petals to the Metal - Flower Classification on TPU |
13,589,735 | train['family'] = train['SibSp'] + train['Parch']+1
test['family'] = test['SibSp'] + test['Parch']+1<feature_engineering> | def get_model(use_model):
base_model = use_model(weights='imagenet',
include_top=False, pooling='avg',
input_shape=(*IMAGE_SIZE, 3))
x = base_model.output
predictions = Dense(104, activation='softmax' )(x)
model = Model(inputs=base_model.input, outputs=predictions)
model.compile(
optimizer='nadam',
loss = 'sparse_categorical_crossentropy',
metrics=['sparse_categorical_accuracy']
)
return model
with strategy.scope() :
model1 = get_model(EfficientNetB1)
model1.load_weights("/kaggle/input/first-start-with-pre-train/my_ef_net_b1.h5" ) | Petals to the Metal - Flower Classification on TPU |
13,589,735 | train['Fare_log'] = train['Fare'].apply(lambda x: np.log(x+1))
test['Fare'] = test['Fare'].fillna(test['Fare'].mean())
test['Fare_log'] = test['Fare'].apply(lambda x: np.log(x+1))<feature_engineering> | def get_model(use_model):
base_model = use_model(weights='noisy-student',
include_top=False, pooling='avg',
input_shape=(*IMAGE_SIZE, 3))
x = base_model.output
predictions = Dense(104, activation='softmax' )(x)
model = Model(inputs=base_model.input, outputs=predictions)
model.compile(
optimizer='nadam',
loss = 'sparse_categorical_crossentropy',
metrics=['sparse_categorical_accuracy']
)
return model
with strategy.scope() :
model2 = get_model(EfficientNetB1)
model2.load_weights("/kaggle/input/last-start-with-pre-train/my_ef_net_b1.h5" ) | Petals to the Metal - Flower Classification on TPU |
13,589,735 | <feature_engineering><EOS> | test_ds = get_test_dataset(ordered=True)
best_alpha = 0.51
print('Вычисляем предсказания...')
test_images_ds = test_ds.map(lambda image, idnum: image)
probabilities1 = model1.predict(test_images_ds)
probabilities2 = model2.predict(test_images_ds)
probabilities = best_alpha * probabilities1 +(1 - best_alpha)* probabilities2
predictions = np.argmax(probabilities, axis=-1)
print(predictions)
print('Создание файла submission.csv...')
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 |
13,080,498 | <SOS> metric: macrofscore Kaggle data source: petals-to-the-metal-flower-classification-on-tpu<feature_engineering> | !pip install -q efficientnet | Petals to the Metal - Flower Classification on TPU |
13,080,498 | train['nick'] = train['Name'].apply(lambda x: x.split('.')[0].split(', ')[-1])
test['nick'] = test['Name'].apply(lambda x: x.split('.')[0].split(', ')[-1])
pd.concat([train['nick'], test['nick']] ).value_counts()<categorify> | from tensorflow.keras.applications.vgg16 import VGG16
from tensorflow.keras.applications.vgg19 import VGG19
from tensorflow.keras.applications.inception_v3 import InceptionV3
from tensorflow.keras.applications.inception_resnet_v2 import InceptionResNetV2
from tensorflow.keras.applications.densenet import DenseNet121, DenseNet169, DenseNet201
from tensorflow.keras.applications.xception import Xception
from tensorflow.keras.applications.resnet50 import ResNet50
from tensorflow.keras.applications.resnet_v2 import ResNet50V2, ResNet101V2, ResNet152V2
from tensorflow.keras.applications.nasnet import NASNetLarge
from efficientnet.tfkeras import EfficientNetB7, EfficientNetL2, EfficientNetB0 | Petals to the Metal - Flower Classification on TPU |
13,080,498 | train['nick'] = train['nick'].replace(['Lady', 'Capt', 'Col','Don', 'Dr', 'Major', 'Rev', 'Jonkheer', 'Dona', 'Sir', 'the Countess'], 'rare' ).replace(['Ms', 'Mme', 'Mlle'],'Miss')
test['nick'] = test['nick'].replace(['Lady', 'Capt', 'Col','Don', 'Dr', 'Major', 'Rev', 'Jonkheer', 'Dona', 'Sir', 'the Countess'], 'rare' ).replace(['Ms', 'Mme', 'Mlle'],'Miss' )<feature_engineering> | %matplotlib inline
print("Tensorflow version " + tf.__version__ ) | Petals to the Metal - Flower Classification on TPU |
13,080,498 | train['Embarked'] = train['Embarked'].fillna('S' )<categorify> | GCS_DS_PATH = KaggleDatasets().get_gcs_path("tpu-getting-started")
MORE_IMAGES_GCS_DS_PATH = KaggleDatasets().get_gcs_path('tf-flower-photo-tfrec' ) | Petals to the Metal - Flower Classification on TPU |
13,080,498 | list_cols = ['Sex', 'Embarked', 'cabin_ini', 'nick']
target_columns = ['Pclass', 'Sex', 'Age', 'SibSp', 'Parch', 'Embarked','family', 'Fare_log', 'cabin_ini', 'ticket_id', 'nick']
ce_ohe = ce.OneHotEncoder(cols=list_cols)
train_onehot = ce_ohe.fit_transform(train[target_columns] )<split> | IMAGE_SIZE = [512, 512]
EPOCHS = 30
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]]
MOREIMAGES_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')
IMAGENET_FILES = tf.io.gfile.glob(MORE_IMAGES_GCS_DS_PATH + '/imagenet' + MOREIMAGES_PATH + '/*.tfrec')
INATURELIST_FILES = tf.io.gfile.glob(MORE_IMAGES_GCS_DS_PATH + '/inaturalist' + MOREIMAGES_PATH + '/*.tfrec')
OPENIMAGE_FILES = tf.io.gfile.glob(MORE_IMAGES_GCS_DS_PATH + '/openimage' + MOREIMAGES_PATH + '/*.tfrec')
TRAINING_FILENAMES = TRAINING_FILENAMES + IMAGENET_FILES + INATURELIST_FILES + OPENIMAGE_FILES
SEED = 2020 | Petals to the Metal - Flower Classification on TPU |
13,080,498 | target = train["Survived"]
x_train, x_val, y_train, y_val = train_test_split(train_onehot, target, test_size = 0.2, random_state = 0 )<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)
dataset = dataset.with_options(ignore_order)
dataset = dataset.map(read_labeled_tfrecord if labeled else read_unlabeled_tfrecord)
return dataset
def data_augment(image, label):
image = tf.image.random_flip_left_right(image, seed=SEED)
return image, label
def get_training_dataset() :
dataset = load_dataset(TRAINING_FILENAMES, labeled=True)
dataset = dataset.map(data_augment)
dataset = dataset.repeat()
dataset = dataset.shuffle(2048)
dataset = dataset.batch(BATCH_SIZE)
dataset = dataset.prefetch(-1)
return dataset
def get_validation_dataset() :
dataset = load_dataset(tf.io.gfile.glob(GCS_DS_PATH + f'/tfrecords-jpeg-{IMAGE_SIZE[0]}x{IMAGE_SIZE[0]}/val/*.tfrec'), labeled=True, ordered=False)
dataset = dataset.batch(BATCH_SIZE)
dataset = dataset.cache()
dataset = dataset.prefetch(-1)
return dataset
def get_test_dataset(ordered=False):
dataset = load_dataset(tf.io.gfile.glob(GCS_DS_PATH + f'/tfrecords-jpeg-{IMAGE_SIZE[0]}x{IMAGE_SIZE[0]}/test/*.tfrec'), labeled=False, ordered=ordered)
dataset = dataset.batch(BATCH_SIZE)
dataset = dataset.prefetch(-1)
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 |
13,080,498 | gbk = GradientBoostingClassifier()
gbk.fit(x_train, y_train)
y_pred = gbk.predict(x_val)
acc_gbk = round(accuracy_score(y_pred, y_val)* 100, 2)
print(acc_gbk )<train_model> | LR_START = 0.00001
LR_MAX = 0.0001
LR_MIN = 0.00001
LR_RAMPUP_EPOCHS = 8
LR_SUSTAIN_EPOCHS = 0
LR_EXP_DECAY =.8
def lrfn(epoch):
if epoch < LR_RAMPUP_EPOCHS:
lr =(LR_MAX - LR_START)/ LR_RAMPUP_EPOCHS * epoch + LR_START
elif epoch < LR_RAMPUP_EPOCHS + LR_SUSTAIN_EPOCHS:
lr = LR_MAX
else:
lr =(LR_MAX - LR_MIN)* LR_EXP_DECAY**(epoch - LR_RAMPUP_EPOCHS - LR_SUSTAIN_EPOCHS)+ LR_MIN
return lr
lr_callback = tf.keras.callbacks.LearningRateScheduler(lrfn, verbose=True)
rng = [i for i in range(EPOCHS)]
y = [lrfn(x)for x in rng]
plt.plot(rng, y)
print("Learning rate schedule: {:.3g} to {:.3g} to {:.3g}".format(y[0], max(y), y[-1])) | Petals to the Metal - Flower Classification on TPU |
13,080,498 | gbk = GradientBoostingClassifier()
gbk.fit(x_train, y_train)
y_pred = gbk.predict(x_val)
acc_gbk = round(accuracy_score(y_pred, y_val)* 100, 2)
print(acc_gbk )<compute_train_metric> | def get_model(use_model):
base_model = use_model(weights='imagenet', include_top=False, pooling='avg', input_shape=(*IMAGE_SIZE, 3))
x = base_model.output
predictions = Dense(104, activation='softmax' )(x)
return Model(inputs=base_model.input, outputs=predictions)
with strategy.scope() :
model = get_model(InceptionV3)
model.compile(
optimizer='nadam',
loss = 'sparse_categorical_crossentropy',
metrics=['sparse_categorical_accuracy']
)
| Petals to the Metal - Flower Classification on TPU |
13,080,498 | rfc = RandomForestClassifier()
rfc.fit(x_train, y_train)
y_pred = rfc.predict(x_val)
acc_rfc = round(accuracy_score(y_pred, y_val)* 100, 2)
print(acc_rfc )<train_model> | history = model.fit(get_training_dataset() ,
steps_per_epoch=STEPS_PER_EPOCH,
epochs=EPOCHS,
callbacks=[lr_callback, ModelCheckpoint(filepath='my_ef_net_b7.h5', monitor='val_loss',
save_best_only=True)],
validation_data=get_validation_dataset() ,
workers = 3 ) | Petals to the Metal - Flower Classification on TPU |
13,080,498 | mlp = MLPClassifier(max_iter=1000, hidden_layer_sizes=(100,),
activation='relu', solver='sgd', learning_rate_init=0.01)
mlp.fit(x_train, y_train)
y_pred = mlp.predict(x_val)
acc_rfc = round(accuracy_score(y_pred, y_val)* 100, 2)
print(acc_rfc )<predict_on_test> | model = tf.keras.models.load_model('my_ef_net_b7.h5' ) | Petals to the Metal - Flower Classification on TPU |
13,080,498 | <save_to_csv><EOS> | test_ds = get_test_dataset(ordered=True)
print('Вычисляем предсказания...')
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('Создание файла submission.csv...')
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 |
13,367,476 | <SOS> metric: macrofscore Kaggle data source: petals-to-the-metal-flower-classification-on-tpu<define_variables> | !pip install -q efficientnet | Petals to the Metal - Flower Classification on TPU |
13,367,476 | def seed_everything(seed):
random.seed(seed)
os.environ["PYTHONHASHSEED"] = str(seed)
np.random.seed(seed )<define_variables> | %matplotlib inline
print("Tensorflow version " + tf.__version__ ) | Petals to the Metal - Flower Classification on TPU |
13,367,476 | SEED = 2020
seed_everything(SEED )<define_variables> | GCS_DS_PATH = KaggleDatasets().get_gcs_path("tpu-getting-started" ) | Petals to the Metal - Flower Classification on TPU |
13,367,476 | TRAIN_FILE_PATH = '/kaggle/input/nlp-getting-started/train.csv'
TEST_FILE_PATH = '/kaggle/input/nlp-getting-started/test.csv'
SUBMISSION_FILE_PATH = '/kaggle/input/nlp-getting-started/sample_submission.csv'<load_from_csv> | IMAGE_SIZE = [512, 512]
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]]
VALIDATION_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/val/*.tfrec')
TEST_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/test/*.tfrec')
SEED = 2020 | Petals to the Metal - Flower Classification on TPU |
13,367,476 | train_df = pd.read_csv(TRAIN_FILE_PATH)
test_df = pd.read_csv(TEST_FILE_PATH )<feature_engineering> | def decode_image(image_data):
image = tf.image.decode_jpeg(image_data, channels=3)
image = tf.cast(image, tf.float32)/ 255.0
image = tf.reshape(image, [*IMAGE_SIZE, 3])
return image
def read_labeled_tfrecord(example):
LABELED_TFREC_FORMAT = {
"image": tf.io.FixedLenFeature([], tf.string),
"class": tf.io.FixedLenFeature([], tf.int64),
}
example = tf.io.parse_single_example(example, LABELED_TFREC_FORMAT)
image = decode_image(example['image'])
label = tf.cast(example['class'], tf.int32)
return image, label
def read_unlabeled_tfrecord(example):
UNLABELED_TFREC_FORMAT = {
"image": tf.io.FixedLenFeature([], tf.string),
"id": tf.io.FixedLenFeature([], tf.string),
}
example = tf.io.parse_single_example(example, UNLABELED_TFREC_FORMAT)
image = decode_image(example['image'])
idnum = example['id']
return image, idnum
def load_dataset(filenames, labeled=True, ordered=False):
ignore_order = tf.data.Options()
if not ordered:
ignore_order.experimental_deterministic = False
dataset = tf.data.TFRecordDataset(filenames, num_parallel_reads=AUTO)
dataset = dataset.with_options(ignore_order)
dataset = dataset.map(read_labeled_tfrecord if labeled else read_unlabeled_tfrecord, num_parallel_calls=AUTO)
return dataset
def get_validation_dataset() :
dataset = load_dataset(VALIDATION_FILENAMES, labeled=True, ordered=True)
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_VALIDATION_IMAGES = count_data_items(VALIDATION_FILENAMES)
NUM_TEST_IMAGES = count_data_items(TEST_FILENAMES)
print('Dataset: {} validation images, {} unlabeled test images'.format(NUM_VALIDATION_IMAGES, NUM_TEST_IMAGES)) | Petals to the Metal - Flower Classification on TPU |
13,367,476 | ids_with_target_error = [328,443,513,2619,3640,3900,4342,5781,6552,6554,6570,6701,6702,6729,6861,7226]
train_df.at[train_df['id'].isin(ids_with_target_error),'target'] = 0
train_df[train_df['id'].isin(ids_with_target_error)]<drop_column> | def get_model(use_model):
base_model = use_model(weights='imagenet',
include_top=False, pooling='avg',
input_shape=(*IMAGE_SIZE, 3))
x = base_model.output
predictions = Dense(104, activation='softmax' )(x)
model = Model(inputs=base_model.input, outputs=predictions)
model.compile(
optimizer='nadam',
loss = 'sparse_categorical_crossentropy',
metrics=['sparse_categorical_accuracy']
)
return model
with strategy.scope() :
model1 = get_model(DenseNet201)
model1.load_weights("/kaggle/input/more-data-with-densenet220011/my_ef_net_b7.h5" ) | Petals to the Metal - Flower Classification on TPU |
13,367,476 | def clean_tweets(tweet):
tweet = ''.join([x for x in tweet if x in string.printable])
tweet = re.sub(r"http\S+", "", tweet)
return tweet<feature_engineering> | def get_model(use_model):
base_model = use_model(weights='imagenet',
include_top=False, pooling='avg',
input_shape=(*IMAGE_SIZE, 3))
x = base_model.output
predictions = Dense(104, activation='softmax' )(x)
model = Model(inputs=base_model.input, outputs=predictions)
model.compile(
optimizer='nadam',
loss = 'sparse_categorical_crossentropy',
metrics=['sparse_categorical_accuracy']
)
return model
with strategy.scope() :
model2 = get_model(EfficientNetB1)
model2.load_weights("/kaggle/input/fork-of-more-data-with-effnetb1/my_ef_net_b7.h5" ) | Petals to the Metal - Flower Classification on TPU |
13,367,476 | train_df["text"] = train_df["text"].apply(lambda x: clean_tweets(x))
test_df["text"] = test_df["text"].apply(lambda x: clean_tweets(x))<drop_column> | val_dataset = get_validation_dataset()
images_ds = val_dataset.map(lambda image, label: image)
labels_ds = val_dataset.map(lambda image, label: label ).unbatch()
val_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):
val_probabilities = alpha*m1+(1-alpha)*m2
val_predictions = np.argmax(val_probabilities, axis=-1)
scores.append(f1_score(val_labels, val_predictions, labels=range(104), average='macro'))
best_alpha = np.argmax(scores)/100
print('Best alpha: ' + str(best_alpha)) | Petals to the Metal - Flower Classification on TPU |
13,367,476 | <feature_engineering><EOS> | test_ds = get_test_dataset(ordered=True)
print('Вычисляем предсказания...')
test_images_ds = test_ds.map(lambda image, idnum: image)
probabilities1 = model1.predict(test_images_ds)
probabilities2 = model2.predict(test_images_ds)
probabilities = best_alpha * probabilities1 +(1 - best_alpha)* probabilities2
predictions = np.argmax(probabilities, axis=-1)
print(predictions)
print('Создание файла submission.csv...')
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 |
13,341,122 | <SOS> metric: macrofscore Kaggle data source: petals-to-the-metal-flower-classification-on-tpu<define_variables> | print("Tensorflow version " + tf.__version__ ) | Petals to the Metal - Flower Classification on TPU |
13,341,122 | def remove_punctuations(text):
punctuations = '@
for p in punctuations:
text = text.replace(p, f' {p} ')
text = text.replace('...', '...')
if '...' not in text:
text = text.replace('.. ', '...')
return text<feature_engineering> | try:
tpu = tf.distribute.cluster_resolver.TPUClusterResolver()
print('Running on TPU ', tpu.master())
except ValueError:
tpu = None
if tpu:
tf.config.experimental_connect_to_cluster(tpu)
tf.tpu.experimental.initialize_tpu_system(tpu)
strategy = tf.distribute.experimental.TPUStrategy(tpu)
else:
strategy = tf.distribute.get_strategy()
print("REPLICAS: ", strategy.num_replicas_in_sync ) | Petals to the Metal - Flower Classification on TPU |
13,341,122 | train_df["text"] = train_df["text"].apply(lambda x: remove_punctuations(x))
test_df["text"] = test_df["text"].apply(lambda x: remove_punctuations(x))<define_variables> | GCS_DS_PATH = KaggleDatasets().get_gcs_path('tpu-getting-started')
print(GCS_DS_PATH ) | Petals to the Metal - Flower Classification on TPU |
13,341,122 | abbreviations = {
"$" : " dollar ",
"€" : " euro ",
"4ao" : "for adults only",
"a.m" : "before midday",
"a3" : "anytime anywhere anyplace",
"aamof" : "as a matter of fact",
"acct" : "account",
"adih" : "another day in hell",
"afaic" : "as far as i am concerned",
"afaict" : "as far as i can tell",
"afaik" : "as far as i know",
"afair" : "as far as i remember",
"afk" : "away from keyboard",
"app" : "application",
"approx" : "approximately",
"apps" : "applications",
"asap" : "as soon as possible",
"asl" : "age, sex, location",
"atk" : "at the keyboard",
"ave." : "avenue",
"aymm" : "are you my mother",
"ayor" : "at your own risk",
"b&b" : "bed and breakfast",
"b+b" : "bed and breakfast",
"b.c" : "before christ",
"b2b" : "business to business",
"b2c" : "business to customer",
"b4" : "before",
"b4n" : "bye for now",
"b@u" : "back at you",
"bae" : "before anyone else",
"bak" : "back at keyboard",
"bbbg" : "bye bye be good",
"bbc" : "british broadcasting corporation",
"bbias" : "be back in a second",
"bbl" : "be back later",
"bbs" : "be back soon",
"be4" : "before",
"bfn" : "bye for now",
"blvd" : "boulevard",
"bout" : "about",
"brb" : "be right back",
"bros" : "brothers",
"brt" : "be right there",
"bsaaw" : "big smile and a wink",
"btw" : "by the way",
"bwl" : "bursting with laughter",
"c/o" : "care of",
"cet" : "central european time",
"cf" : "compare",
"cia" : "central intelligence agency",
"csl" : "can not stop laughing",
"cu" : "see you",
"cul8r" : "see you later",
"cv" : "curriculum vitae",
"cwot" : "complete waste of time",
"cya" : "see you",
"cyt" : "see you tomorrow",
"dae" : "does anyone else",
"dbmib" : "do not bother me i am busy",
"diy" : "do it yourself",
"dm" : "direct message",
"dwh" : "during work hours",
"e123" : "easy as one two three",
"eet" : "eastern european time",
"eg" : "example",
"embm" : "early morning business meeting",
"encl" : "enclosed",
"encl." : "enclosed",
"etc" : "and so on",
"faq" : "frequently asked questions",
"fawc" : "for anyone who cares",
"fb" : "facebook",
"fc" : "fingers crossed",
"fig" : "figure",
"fimh" : "forever in my heart",
"ft." : "feet",
"ft" : "featuring",
"ftl" : "for the loss",
"ftw" : "for the win",
"fwiw" : "for what it is worth",
"fyi" : "for your information",
"g9" : "genius",
"gahoy" : "get a hold of yourself",
"gal" : "get a life",
"gcse" : "general certificate of secondary education",
"gfn" : "gone for now",
"gg" : "good game",
"gl" : "good luck",
"glhf" : "good luck have fun",
"gmt" : "greenwich mean time",
"gmta" : "great minds think alike",
"gn" : "good night",
"g.o.a.t" : "greatest of all time",
"goat" : "greatest of all time",
"goi" : "get over it",
"gps" : "global positioning system",
"gr8" : "great",
"gratz" : "congratulations",
"gyal" : "girl",
"h&c" : "hot and cold",
"hp" : "horsepower",
"hr" : "hour",
"hrh" : "his royal highness",
"ht" : "height",
"ibrb" : "i will be right back",
"ic" : "i see",
"icq" : "i seek you",
"icymi" : "in case you missed it",
"idc" : "i do not care",
"idgadf" : "i do not give a damn fuck",
"idgaf" : "i do not give a fuck",
"idk" : "i do not know",
"ie" : "that is",
"i.e" : "that is",
"ifyp" : "i feel your pain",
"IG" : "instagram",
"iirc" : "if i remember correctly",
"ilu" : "i love you",
"ily" : "i love you",
"imho" : "in my humble opinion",
"imo" : "in my opinion",
"imu" : "i miss you",
"iow" : "in other words",
"irl" : "in real life",
"j4f" : "just for fun",
"jic" : "just in case",
"jk" : "just kidding",
"jsyk" : "just so you know",
"l8r" : "later",
"lb" : "pound",
"lbs" : "pounds",
"ldr" : "long distance relationship",
"lmao" : "laugh my ass off",
"lmfao" : "laugh my fucking ass off",
"lol" : "laughing out loud",
"ltd" : "limited",
"ltns" : "long time no see",
"m8" : "mate",
"mf" : "motherfucker",
"mfs" : "motherfuckers",
"mfw" : "my face when",
"mofo" : "motherfucker",
"mph" : "miles per hour",
"mr" : "mister",
"mrw" : "my reaction when",
"ms" : "miss",
"mte" : "my thoughts exactly",
"nagi" : "not a good idea",
"nbc" : "national broadcasting company",
"nbd" : "not big deal",
"nfs" : "not for sale",
"ngl" : "not going to lie",
"nhs" : "national health service",
"nrn" : "no reply necessary",
"nsfl" : "not safe for life",
"nsfw" : "not safe for work",
"nth" : "nice to have",
"nvr" : "never",
"nyc" : "new york city",
"oc" : "original content",
"og" : "original",
"ohp" : "overhead projector",
"oic" : "oh i see",
"omdb" : "over my dead body",
"omg" : "oh my god",
"omw" : "on my way",
"p.a" : "per annum",
"p.m" : "after midday",
"pm" : "prime minister",
"poc" : "people of color",
"pov" : "point of view",
"pp" : "pages",
"ppl" : "people",
"prw" : "parents are watching",
"ps" : "postscript",
"pt" : "point",
"ptb" : "please text back",
"pto" : "please turn over",
"qpsa" : "what happens",
"ratchet" : "rude",
"rbtl" : "read between the lines",
"rlrt" : "real life retweet",
"rofl" : "rolling on the floor laughing",
"roflol" : "rolling on the floor laughing out loud",
"rotflmao" : "rolling on the floor laughing my ass off",
"rt" : "retweet",
"ruok" : "are you ok",
"sfw" : "safe for work",
"sk8" : "skate",
"smh" : "shake my head",
"sq" : "square",
"srsly" : "seriously",
"ssdd" : "same stuff different day",
"tbh" : "to be honest",
"tbs" : "tablespooful",
"tbsp" : "tablespooful",
"tfw" : "that feeling when",
"thks" : "thank you",
"tho" : "though",
"thx" : "thank you",
"tia" : "thanks in advance",
"til" : "today i learned",
"tl;dr" : "too long i did not read",
"tldr" : "too long i did not read",
"tmb" : "tweet me back",
"tntl" : "trying not to laugh",
"ttyl" : "talk to you later",
"u" : "you",
"u2" : "you too",
"u4e" : "yours for ever",
"utc" : "coordinated universal time",
"w/" : "with",
"w/o" : "without",
"w8" : "wait",
"wassup" : "what is up",
"wb" : "welcome back",
"wtf" : "what the fuck",
"wtg" : "way to go",
"wtpa" : "where the party at",
"wuf" : "where are you from",
"wuzup" : "what is up",
"wywh" : "wish you were here",
"yd" : "yard",
"ygtr" : "you got that right",
"ynk" : "you never know",
"zzz" : "sleeping bored and tired"
}<categorify> | IMAGE_SIZE = [512, 512]
GCS_PATH = GCS_DS_PATH + '/tfrecords-jpeg-512x512'
AUTO = tf.data.experimental.AUTOTUNE
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')
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']
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 | Petals to the Metal - Flower Classification on TPU |
13,341,122 | def convert_abbrev(word):
return abbreviations[word.lower() ] if word.lower() in abbreviations.keys() else word<string_transform> | BATCH_SIZE = 16 * strategy.num_replicas_in_sync
ds_train = get_training_dataset()
ds_valid = get_validation_dataset()
ds_test = get_test_dataset()
print("Training:", ds_train)
print("Validation:", ds_valid)
print("Test:", ds_test ) | Petals to the Metal - Flower Classification on TPU |
13,341,122 | def convert_abbrev_in_text(text):
tokens = word_tokenize(text)
tokens = [convert_abbrev(word)for word in tokens]
text = ' '.join(tokens)
return text<feature_engineering> | np.set_printoptions(threshold=10, linewidth=80)
print("Training data shapes:")
for image, label in ds_train.take(3):
print(image.numpy().shape, label.numpy().shape)
print("Training data label examples:", label.numpy() ) | Petals to the Metal - Flower Classification on TPU |
13,341,122 | train_df["text"] = train_df["text"].apply(lambda x: convert_abbrev_in_text(x))
test_df["text"] = test_df["text"].apply(lambda x: convert_abbrev_in_text(x))<categorify> | print("Test data shapes:")
for image, idnum in ds_test.take(3):
print(image.numpy().shape, idnum.numpy().shape)
print("Test data IDs:", idnum.numpy().astype('U')) | Petals to the Metal - Flower Classification on TPU |
13,341,122 | def fast_encode(texts, tokenizer, chunk_size=256, maxlen=512):
tokenizer.enable_truncation(max_length=maxlen)
tokenizer.enable_padding(max_length=maxlen)
all_ids = []
for i in tqdm(range(0, len(texts), chunk_size)) :
text_chunk = texts[i:i+chunk_size].tolist()
encs = tokenizer.encode_batch(text_chunk)
all_ids.extend([enc.ids for enc in encs])
return np.array(all_ids )<choose_model_class> | def batch_to_numpy_images_and_labels(data):
images, labels = data
numpy_images = images.numpy()
numpy_labels = labels.numpy()
if numpy_labels.dtype == object:
numpy_labels = [None for _ in enumerate(numpy_images)]
return numpy_images, numpy_labels
def title_from_label_and_target(label, correct_label):
if correct_label is None:
return CLASSES[label], True
correct =(label == correct_label)
return "{} [{}{}{}]".format(CLASSES[label], 'OK' if correct else 'NO', u"\u2192" if not correct else '',
CLASSES[correct_label] if not correct else ''), correct
def display_one_flower(image, title, subplot, red=False, titlesize=16):
plt.subplot(*subplot)
plt.axis('off')
plt.imshow(image)
if len(title)> 0:
plt.title(title, fontsize=int(titlesize)if not red else int(titlesize/1.2), color='red' if red else 'black', fontdict={'verticalalignment':'center'}, pad=int(titlesize/1.5))
return(subplot[0], subplot[1], subplot[2]+1)
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()
def display_training_curves(training, validation, title, subplot):
if subplot%10==1:
plt.subplots(figsize=(10,10), facecolor='
plt.tight_layout()
ax = plt.subplot(subplot)
ax.set_facecolor('
ax.plot(training)
ax.plot(validation)
ax.set_title('model '+ title)
ax.set_ylabel(title)
ax.set_xlabel('epoch')
ax.legend(['train', 'valid.'] ) | Petals to the Metal - Flower Classification on TPU |
13,341,122 | def build_model(transformer, loss='binary_crossentropy', max_len=512):
input_word_ids = Input(shape=(max_len,), dtype=tf.int32, name="input_word_ids")
sequence_output = transformer(input_word_ids)[0]
cls_token = sequence_output[:, 0, :]
x = tf.keras.layers.Dropout(0.35 )(cls_token)
out = Dense(1, activation='sigmoid' )(x)
model = Model(inputs=input_word_ids, outputs=out)
model.compile(Adam(lr=3e-5), loss=loss, metrics=[tf.keras.metrics.AUC() ])
return model<string_transform> | ds_iter = iter(ds_train.unbatch().batch(20)) | Petals to the Metal - Flower Classification on TPU |
13,341,122 | nltk.download('punkt')
stemmer = nltk.stem.porter.PorterStemmer()
remove_punctuation_map = dict(( ord(char), None)for char in string.punctuation)
def stem_tokens(tokens):
return [stemmer.stem(item)for item in tokens]
def normalize(text):
return stem_tokens(nltk.word_tokenize(text.lower().translate(remove_punctuation_map)))
vectorizer = TfidfVectorizer(tokenizer=normalize, stop_words='english')
def cosine_sim(text1, text2):
tfidf = vectorizer.fit_transform([text1, text2])
return(( tfidf * tfidf.T ).A)[0,1]<choose_model_class> | one_batch = next(ds_iter)
display_batch_of_images(one_batch ) | Petals to the Metal - Flower Classification on TPU |
13,341,122 | 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 )<compute_test_metric> | !pip install -q efficientnet
| Petals to the Metal - Flower Classification on TPU |
13,341,122 | def metric(y_true, y_pred):
acc = accuracy_score(y_true, y_pred)
f1 = f1_score(y_true, y_pred, average='macro')
return acc, f1<load_pretrained> | 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 |
13,341,122 | tokenizer = BertTokenizer.from_pretrained('bert-base-cased')
save_path = '/kaggle/working/distilbert_base_uncased/'
if not os.path.exists(save_path):
os.makedirs(save_path)
tokenizer.save_pretrained(save_path)
fast_tokenizer = BertWordPieceTokenizer('distilbert_base_uncased/vocab.txt', lowercase=False)
fast_tokenizer<init_hyperparams> | EPOCHS=100 | Petals to the Metal - Flower Classification on TPU |
13,341,122 | MAX_SEQ_LENGTH = 512
LEARNING_RATE = 3e-5
NUM_EPOCHS = 30<split> | model1.compile(
optimizer=tf.keras.optimizers.SGD(learning_rate=0.1, momentum=0.9),
loss = 'sparse_categorical_crossentropy',
metrics=['sparse_categorical_accuracy']
)
model1.summary() | Petals to the Metal - Flower Classification on TPU |
13,341,122 | train_df, valid_df = train_test_split(train_df, test_size=0.2 )<prepare_x_and_y> | def exponential_lr(epoch,
start_lr = 0.00001, min_lr = 0.00001, max_lr = 0.00005,
rampup_epochs = 5, sustain_epochs = 0,
exp_decay = 0.8):
def lr(epoch, start_lr, min_lr, max_lr, rampup_epochs, sustain_epochs, exp_decay):
if epoch < rampup_epochs:
lr =(( max_lr - start_lr)/
rampup_epochs * epoch + start_lr)
elif epoch < rampup_epochs + sustain_epochs:
lr = max_lr
else:
lr =(( max_lr - min_lr)*
exp_decay**(epoch - rampup_epochs - sustain_epochs)+
min_lr)
return lr
return lr(epoch,
start_lr,
min_lr,
max_lr,
rampup_epochs,
sustain_epochs,
exp_decay)
lr_callback = tf.keras.callbacks.LearningRateScheduler(exponential_lr, verbose=True)
rng = [i for i in range(EPOCHS)]
y = [exponential_lr(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 |
13,341,122 | x_train = fast_encode(train_df.text.astype(str), fast_tokenizer, maxlen=MAX_SEQ_LENGTH)
x_valid = fast_encode(valid_df.text.astype(str), fast_tokenizer, maxlen=MAX_SEQ_LENGTH)
x_test = fast_encode(test_df.text.astype(str), fast_tokenizer, maxlen=MAX_SEQ_LENGTH)
y_train = train_df.target.values
y_valid = valid_df.target.values<define_variables> | EPOCHS = 21
STEPS_PER_EPOCH = NUM_TRAINING_IMAGES//256
history = model1.fit(
ds_train,
validation_data=ds_valid,
epochs=EPOCHS,
steps_per_epoch=STEPS_PER_EPOCH,
callbacks=[lr_callback],
) | Petals to the Metal - Flower Classification on TPU |
13,341,122 | train_dataset =(
tf.data.Dataset
.from_tensor_slices(( x_train, y_train))
.repeat()
.shuffle(2048)
.batch(64)
.prefetch(AUTO)
)
valid_dataset =(
tf.data.Dataset
.from_tensor_slices(( x_valid, y_valid))
.batch(64)
.cache()
.prefetch(AUTO)
)
test_dataset = [(
tf.data.Dataset
.from_tensor_slices(x_test)
.batch(64)
)]<compute_train_metric> | cmdataset = get_validation_dataset(ordered=True)
images_ds = cmdataset.map(lambda image, label: image)
labels_ds = cmdataset.map(lambda image, label: label ).unbatch()
cm_correct_labels = next(iter(labels_ds.batch(NUM_VALIDATION_IMAGES)) ).numpy()
cm_probabilities = model1.predict(images_ds)
cm_predictions = np.argmax(cm_probabilities, axis=-1)
labels = range(len(CLASSES))
cmat = confusion_matrix(
cm_correct_labels,
cm_predictions,
labels=labels,
)
cmat =(cmat.T / cmat.sum(axis=1)).T | Petals to the Metal - Flower Classification on TPU |
13,341,122 | def focal_loss(gamma=2., alpha=.2):
def focal_loss_fixed(y_true, y_pred):
pt_1 = tf.where(tf.equal(y_true, 1), y_pred, tf.ones_like(y_pred))
pt_0 = tf.where(tf.equal(y_true, 0), y_pred, tf.zeros_like(y_pred))
return -K.mean(alpha * K.pow(1.- pt_1, gamma)* K.log(pt_1)) - K.mean(( 1 - alpha)* K.pow(pt_0, gamma)* K.log(1.- pt_0))
return focal_loss_fixed<load_pretrained> | score = f1_score(
cm_correct_labels,
cm_predictions,
labels=labels,
average='macro',
)
precision = precision_score(
cm_correct_labels,
cm_predictions,
labels=labels,
average='macro',
)
recall = recall_score(
cm_correct_labels,
cm_predictions,
labels=labels,
average='macro',
)
display_confusion_matrix(cmat, score, precision, recall ) | Petals to the Metal - Flower Classification on TPU |
13,341,122 | with strategy.scope() :
transformer_layer = TFBertModel.from_pretrained('bert-base-cased')
model = build_model(transformer_layer, loss=focal_loss(gamma=1.5), max_len=512)
model.summary()<choose_model_class> | dataset = get_validation_dataset()
dataset = dataset.unbatch().batch(20)
batch = iter(dataset ) | Petals to the Metal - Flower Classification on TPU |
13,341,122 | def build_lrfn(lr_start=0.000001, lr_max=0.000004,
lr_min=0.0000001, lr_rampup_epochs=7,
lr_sustain_epochs=0, lr_exp_decay=.87):
lr_max = lr_max * strategy.num_replicas_in_sync
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
return lrfn<train_model> | images, labels = next(batch)
probabilities = model1.predict(images)
predictions = np.argmax(probabilities, axis=-1)
display_batch_of_images(( images, labels), predictions ) | Petals to the Metal - Flower Classification on TPU |
13,341,122 | lrfn = build_lrfn()
lr_schedule = tf.keras.callbacks.LearningRateScheduler(lrfn, verbose=1)
train_history = model.fit(
train_dataset,
steps_per_epoch=110,
validation_data=valid_dataset,
callbacks=[lr_schedule],
epochs=6
)<load_from_csv> | test_ds = get_test_dataset(ordered=True)
print('Computing predictions...')
test_images_ds = test_ds.map(lambda image, idnum: image)
probabilities = model1.predict(test_images_ds)
predictions = np.argmax(probabilities, axis=-1)
print(predictions ) | Petals to the Metal - Flower Classification on TPU |
13,341,122 | <prepare_output><EOS> | 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='',
)
!head submission.csv | Petals to the Metal - Flower Classification on TPU |
12,686,034 | <SOS> metric: macrofscore Kaggle data source: petals-to-the-metal-flower-classification-on-tpu<prepare_output> | !pip install -q efficientnet | Petals to the Metal - Flower Classification on TPU |
12,686,034 | sample['target'] = preds<save_to_csv> | from tensorflow.keras.applications.vgg16 import VGG16
from tensorflow.keras.applications.vgg19 import VGG19
from tensorflow.keras.applications.inception_v3 import InceptionV3
from tensorflow.keras.applications.inception_resnet_v2 import InceptionResNetV2
from tensorflow.keras.applications.densenet import DenseNet121, DenseNet169, DenseNet201
from tensorflow.keras.applications.xception import Xception
from tensorflow.keras.applications.resnet50 import ResNet50
from tensorflow.keras.applications.resnet_v2 import ResNet50V2, ResNet101V2, ResNet152V2
from tensorflow.keras.applications.nasnet import NASNetLarge
from efficientnet.tfkeras import EfficientNetB7, EfficientNetL2, EfficientNetB0, EfficientNetB1 | Petals to the Metal - Flower Classification on TPU |
12,686,034 | sample.to_csv('submission.csv', index=False )<load_from_csv> | %matplotlib inline
print("Tensorflow version " + tf.__version__ ) | Petals to the Metal - Flower Classification on TPU |
12,686,034 | df = pd.read_csv('.. /input/44352/training_solutions_rev1.csv')
df_train, df_test = train_test_split(df, test_size=.2)
df_train.shape, df_test.shape<prepare_x_and_y> | GCS_DS_PATH = KaggleDatasets().get_gcs_path() | Petals to the Metal - Flower Classification on TPU |
12,686,034 | %matplotlib inline
ORIG_SHAPE =(424,424)
CROP_SIZE =(256,256)
IMG_SHAPE =(64,64)
def get_image(path, x1,y1, shape, crop_size):
x = plt.imread(path)
x = x[x1:x1+crop_size[0], y1:y1+crop_size[1]]
x = resize(x, shape)
x = x/255.
return x
def get_all_images(dataframe, shape=IMG_SHAPE, crop_size=CROP_SIZE):
x1 =(ORIG_SHAPE[0]-CROP_SIZE[0])//2
y1 =(ORIG_SHAPE[1]-CROP_SIZE[1])//2
sel = dataframe.values
ids = sel[:,0].astype(int ).astype(str)
y_batch = sel[:,1:]
x_batch = []
for i in tqdm(ids):
x = get_image('.. /input/44352/images_training_rev1/'+i+'.jpg', x1,y1, shape=shape, crop_size=crop_size)
x_batch.append(x)
x_batch = np.array(x_batch)
return x_batch, y_batch
X_train, y_train = get_all_images(df_train)
X_test, y_test = get_all_images(df_test )<choose_model_class> | IMAGE_SIZE = [512, 512]
EPOCHS = 30
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')
SEED = 2020 | Petals to the Metal - Flower Classification on TPU |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.