kernel_id
int64 24.2k
23.3M
| prompt
stringlengths 8
1.85M
| completetion
stringlengths 1
182k
| comp_name
stringlengths 5
57
|
---|---|---|---|
11,220,203 | dataset[['BsmtExposure','SalePrice']].fillna('No' ).groupby('BsmtExposure' ).agg(['mean','median','min','max','count'] )<data_type_conversions> | display_batch_of_images(next(train_batch))
| Petals to the Metal - Flower Classification on TPU |
11,220,203 | dataset['BsmtExposure']=dataset['BsmtExposure'].fillna('No')
test['BsmtExposure']=test['BsmtExposure'].fillna('No' )<sort_values> | display_batch_of_images(next(test_batch))
| Petals to the Metal - Flower Classification on TPU |
11,220,203 | cols_null=dataset.isna().sum(axis=0)
cols_null=cols_null[cols_null>0]
cols_null.sort_values(ascending=False )<groupby> | 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,220,203 | dataset[['BsmtFinType1','SalePrice']].fillna('O' ).groupby('BsmtFinType1' ).agg(['mean','median','min','max','count'] )<data_type_conversions> | 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,220,203 | dataset['BsmtFinType1']=dataset['BsmtFinType1'].fillna('Unf')
test['BsmtFinType1']=test['BsmtFinType1'].fillna('Unf' )<sort_values> | def onehot(image,label):
CLASSES = len(classes)
return image,tf.one_hot(label,CLASSES ) | Petals to the Metal - Flower Classification on TPU |
11,220,203 | cols_null=dataset.isna().sum(axis=0)
cols_null=cols_null[cols_null>0]
cols_null.sort_values(ascending=False )<create_dataframe> | def mixup(image, label, PROBABILITY = 1.0):
DIM = IMAGE_SIZE[0]
CLASSES = 104
imgs = []; labs = []
for j in range(AUG_BATCH):
P = tf.cast(tf.random.uniform([],0,1)<=PROBABILITY, tf.float32)
k = tf.cast(tf.random.uniform([],0,AUG_BATCH),tf.int32)
a = tf.random.uniform([],0,1)*P
img1 = image[j,]
img2 = image[k,]
imgs.append(( 1-a)*img1 + a*img2)
if len(label.shape)==1:
lab1 = tf.one_hot(label[j],CLASSES)
lab2 = tf.one_hot(label[k],CLASSES)
else:
lab1 = label[j,]
lab2 = label[k,]
labs.append(( 1-a)*lab1 + a*lab2)
image2 = tf.reshape(tf.stack(imgs),(AUG_BATCH,DIM,DIM,3))
label2 = tf.reshape(tf.stack(labs),(AUG_BATCH,CLASSES))
return image2,label2 | Petals to the Metal - Flower Classification on TPU |
11,220,203 | dataset[['BsmtCond','SalePrice']].fillna('O' ).groupby('BsmtCond' ).agg(['mean','median','min','max','count'] )<data_type_conversions> | test_dataset = get_train_ds(TEST_FILENAMES, cutmix_aug = False, tta_aug = False, labeled = False,
shuffle = True, repeat = False)
test_dataset = test_dataset.unbatch().batch(20)
test_batch = iter(test_dataset ) | Petals to the Metal - Flower Classification on TPU |
11,220,203 | dataset['BsmtCond']=dataset['BsmtCond'].fillna('TA')
test['BsmtCond']=test['BsmtCond'].fillna('TA' )<sort_values> | def cutmix(image, label, PROBABILITY = 1.0):
DIM = IMAGE_SIZE[0]
CLASSES = 104
imgs = []; labs = []
for j in range(AUG_BATCH):
P = tf.cast(tf.random.uniform([],0,1)<=PROBABILITY, tf.int32)
k = tf.cast(tf.random.uniform([],0,AUG_BATCH),tf.int32)
x = tf.cast(tf.random.uniform([],0,DIM),tf.int32)
y = tf.cast(tf.random.uniform([],0,DIM),tf.int32)
b = tf.random.uniform([],0,1)
WIDTH = tf.cast(DIM * tf.math.sqrt(1-b),tf.int32)* P
ya = tf.math.maximum(0,y-WIDTH//2)
yb = tf.math.minimum(DIM,y+WIDTH//2)
xa = tf.math.maximum(0,x-WIDTH//2)
xb = tf.math.minimum(DIM,x+WIDTH//2)
one = image[j,ya:yb,0:xa,:]
two = image[k,ya:yb,xa:xb,:]
three = image[j,ya:yb,xb:DIM,:]
middle = tf.concat([one,two,three],axis=1)
img = tf.concat([image[j,0:ya,:,:],middle,image[j,yb:DIM,:,:]],axis=0)
imgs.append(img)
a = tf.cast(WIDTH*WIDTH/DIM/DIM,tf.float32)
if len(label.shape)==1:
lab1 = tf.one_hot(label[j],CLASSES)
lab2 = tf.one_hot(label[k],CLASSES)
else:
lab1 = label[j,]
lab2 = label[k,]
labs.append(( 1-a)*lab1 + a*lab2)
image2 = tf.reshape(tf.stack(imgs),(AUG_BATCH,DIM,DIM,3))
label2 = tf.reshape(tf.stack(labs),(AUG_BATCH,CLASSES))
return image2,label2 | Petals to the Metal - Flower Classification on TPU |
11,220,203 | cols_null=dataset.isna().sum(axis=0)
cols_null=cols_null[cols_null>0]
cols_null.sort_values(ascending=False )<create_dataframe> | def mixup_and_cutmix(image,label):
CLASSES = len(classes)
DIM = IMAGE_SIZE[0]
SWITCH = 1/2
CUTMIX_PROB = 2/3
MIXUP_PROB = 2/3
image2, label2 = cutmix(image, label, CUTMIX_PROB)
image3, label3 = mixup(image, label, MIXUP_PROB)
imgs = []; labs = []
for j in range(BATCH_SIZE):
P = tf.cast(tf.random.uniform([],0,1)<=SWITCH, tf.float32)
imgs.append(P*image2[j,]+(1-P)*image3[j,])
labs.append(P*label2[j,]+(1-P)*label3[j,])
image4 = tf.reshape(tf.stack(imgs),(BATCH_SIZE,DIM,DIM,3))
label4 = tf.reshape(tf.stack(labs),(BATCH_SIZE,CLASSES))
return image4,label4 | Petals to the Metal - Flower Classification on TPU |
11,220,203 | dataset[['BsmtQual','SalePrice']].fillna('O' ).groupby('BsmtQual' ).agg(['mean','median','min','max','count'] )<data_type_conversions> | EPOCHS = 20
STEPS_PER_EPOCH = count_data_items(TRAINING_FILENAMES)// BATCH_SIZE
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)
rng = [i for i in range(EPOCHS)]
y = [lr_schedule(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,220,203 | dataset['BsmtQual']=dataset['BsmtQual'].fillna('Gd')
test['BsmtQual']=test['BsmtQual'].fillna('Gd' )<sort_values> | !pip install -q efficientnet
def get_DenseNet201() :
CLASSES = len(classes)
with strategy.scope() :
dnet = DenseNet201(
input_shape =(IMAGE_SIZE[0], IMAGE_SIZE[1], 3),
weights = 'imagenet',
include_top = False
)
dnet.trainable = True
model = tf.keras.Sequential([
dnet,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(CLASSES, activation = 'softmax',dtype = 'float32')
])
model.compile(
optimizer='adam',
loss = 'categorical_crossentropy',
metrics=['categorical_accuracy']
)
return model
def get_Xception() :
CLASSES = len(classes)
with strategy.scope() :
xception = Xception(
input_shape =(IMAGE_SIZE[0], IMAGE_SIZE[1], 3),
weights = 'imagenet',
include_top = False
)
xception.trainable = True
model = tf.keras.Sequential([
xception,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(CLASSES, activation = 'softmax',dtype = 'float32')
])
model.compile(
optimizer='adam',
loss = 'categorical_crossentropy',
metrics=['categorical_accuracy']
)
return model
def get_InceptionV3() :
CLASSES = len(classes)
with strategy.scope() :
inception = InceptionV3(
input_shape =(IMAGE_SIZE[0], IMAGE_SIZE[1], 3),
weights = 'imagenet',
include_top = False
)
inception.trainable = True
model = tf.keras.Sequential([
inception,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(CLASSES, activation = 'softmax',dtype = 'float32')
])
model.compile(
optimizer='adam',
loss = 'categorical_crossentropy',
metrics=['categorical_accuracy']
)
return model
def get_EfficientNetB4() :
CLASSES = len(classes)
with strategy.scope() :
efficient = efn.EfficientNetB4(
input_shape =(IMAGE_SIZE[0], IMAGE_SIZE[1], 3),
weights = 'noisy-student',
include_top = False
)
efficient.trainable = True
model = tf.keras.Sequential([
efficient,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(CLASSES, activation = 'softmax',dtype = 'float32')
])
model.compile(
optimizer='adam',
loss = 'categorical_crossentropy',
metrics=['categorical_accuracy']
)
return model
def get_EfficientNetB5() :
CLASSES = len(classes)
with strategy.scope() :
efficient = efn.EfficientNetB5(
input_shape =(IMAGE_SIZE[0], IMAGE_SIZE[1], 3),
weights = 'noisy-student',
include_top = False
)
efficient.trainable = True
model = tf.keras.Sequential([
efficient,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(CLASSES, activation = 'softmax',dtype = 'float32')
])
model.compile(
optimizer='adam',
loss = 'categorical_crossentropy',
metrics=['categorical_accuracy']
)
return model
def get_EfficientNetB6() :
CLASSES = len(classes)
with strategy.scope() :
efficient = efn.EfficientNetB6(
input_shape =(IMAGE_SIZE[0], IMAGE_SIZE[1], 3),
weights = 'imagenet',
include_top = False
)
efficient.trainable = True
model = tf.keras.Sequential([
efficient,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(CLASSES, activation = 'softmax',dtype = 'float32')
])
model.compile(
optimizer='adam',
loss = 'categorical_crossentropy',
metrics=['categorical_accuracy']
)
return model
def get_EfficientNetB7() :
CLASSES = len(classes)
with strategy.scope() :
efficient = efn.EfficientNetB7(
input_shape =(IMAGE_SIZE[0], IMAGE_SIZE[1], 3),
weights = 'noisy-student',
include_top = False
)
efficient.trainable = True
model = tf.keras.Sequential([
efficient,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(CLASSES, activation = 'softmax',dtype = 'float32')
])
model.compile(
optimizer='adam',
loss = 'categorical_crossentropy',
metrics=['categorical_accuracy']
)
return model
def get_InceptionResNetV2() :
CLASSES = len(classes)
with strategy.scope() :
inception_res = InceptionResNetV2(
input_shape =(IMAGE_SIZE[0], IMAGE_SIZE[1], 3),
weights = 'imagenet',
include_top = False
)
inception_res.trainable = True
model = tf.keras.Sequential([
inception_res,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(CLASSES, activation = 'softmax',dtype = 'float32')
])
model.compile(
optimizer='adam',
loss = 'categorical_crossentropy',
metrics=['categorical_accuracy']
)
return model | Petals to the Metal - Flower Classification on TPU |
11,220,203 | cols_null=dataset.isna().sum(axis=0)
cols_null=cols_null[cols_null>0]
cols_null.sort_values(ascending=False )<feature_engineering> | histories = []
models = []
kfold = KFold(FOLDS, shuffle = True, random_state = SEED)
for f,(train_index, val_index)in enumerate(kfold.split(TRAINING_FILENAMES)) :
print() ; print('-'*25)
print(f"Training fold {f + 1} with EfficientNetB6")
print('-'*25)
print('Getting training data...')
print('')
train_ds = get_train_ds(list(pd.DataFrame({'TRAINING_FILENAMES': TRAINING_FILENAMES} ).loc[train_index]['TRAINING_FILENAMES']),
cutmix_aug = True, tta_aug = False, labeled = True, shuffle = True, repeat = True)
print('Geting validation data...')
print('')
val_ds = get_val_ds(list(pd.DataFrame({'TRAINING_FILENAMES': TRAINING_FILENAMES} ).loc[val_index]['TRAINING_FILENAMES']),
labeled = True, shuffle = True, return_image_names = False)
model = get_EfficientNetB6()
history = model.fit(train_ds,
steps_per_epoch = STEPS_PER_EPOCH,
epochs = EPOCHS,
callbacks = [lr_callback],
validation_data = val_ds,
verbose = 2)
models.append(model)
histories.append(history ) | Petals to the Metal - Flower Classification on TPU |
11,220,203 | test['MasVnrArea']=test['MasVnrArea'].fillna(test['MasVnrArea'].median())
dataset['MasVnrArea']=dataset['MasVnrArea'].fillna(dataset['MasVnrArea'].median() )<count_values> | def get_test_dataset(filenames, shuffle = False, repeat = True, labeled = False, tta_aug = True, return_image_names = True):
ds = tf.data.TFRecordDataset(filenames, num_parallel_reads=AUTO)
ds = ds.cache()
if repeat:
ds = ds.repeat()
if shuffle:
ds = ds.shuffle(1024*8)
opt = tf.data.Options()
opt.experimental_deterministic = False
ds = ds.with_options(opt)
if labeled:
ds = ds.map(read_labeled_tfrecord, num_parallel_calls=AUTO)
else:
ds = ds.map(lambda example: read_unlabeled_tfrecord(example, return_image_names),
num_parallel_calls=AUTO)
if tta_aug:
ds = ds.map(data_augment, num_parallel_calls = AUTO)
ds = ds.map(transform, num_parallel_calls=AUTO)
ds = ds.batch(BATCH_SIZE)
ds = ds.prefetch(AUTO)
return ds | Petals to the Metal - Flower Classification on TPU |
11,220,203 | dataset['MasVnrType'].value_counts()<data_type_conversions> | def average_tta_preds(tta_preds):
average_preds = np.zeros(( ct_test, 104))
for fold in range(FOLDS):
average_preds += tta_preds[(fold)*ct_test:(fold + 1)*ct_test] / FOLDS
return average_preds | Petals to the Metal - Flower Classification on TPU |
11,220,203 | dataset['MasVnrType']=dataset['MasVnrType'].fillna('None')
test['MasVnrType']=test['MasVnrType'].fillna('None' )<groupby> | test_ds = get_test_dataset(TEST_FILENAMES, tta_aug = True, labeled = False,
repeat = True, return_image_names = True)
test_images_ds = test_ds.map(lambda image, idnum: image)
ct_test = count_data_items(TEST_FILENAMES)
STEPS = TTA * ct_test/BATCH_SIZE
print('Getting TTA predictions...')
pred0 = models[0].predict(test_images_ds,steps = STEPS,verbose = 2)[:TTA*ct_test,]
pred1 = models[1].predict(test_images_ds,steps = STEPS,verbose = 2)[:TTA*ct_test,]
pred2 = models[2].predict(test_images_ds,steps = STEPS,verbose = 2)[:TTA*ct_test,]
print('')
print('Averaging TTA predictions...')
average_pred0 = average_tta_preds(pred0)
average_pred1 = average_tta_preds(pred1)
average_pred2 = average_tta_preds(pred1)
print('')
print('Merging predictions from models...')
final_preds = np.zeros(( ct_test, 104))
final_preds += average_pred0
final_preds += average_pred1
final_preds += average_pred2
final_preds = np.argmax(final_preds, axis = 1)
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')
print('Done' ) | Petals to the Metal - Flower Classification on TPU |
11,220,203 | dataset[['Electrical','SalePrice']].groupby('Electrical' ).agg(['mean','median','min','max','count'] )<data_type_conversions> | submission = pd.DataFrame()
submission['id'] = test_ids
submission['label'] = final_preds
print(submission.shape)
submission.head(10 ) | Petals to the Metal - Flower Classification on TPU |
11,220,203 | <filter><EOS> | submission.to_csv('submission.csv', index = False)
print('Submission saved' ) | Petals to the Metal - Flower Classification on TPU |
10,878,259 | <SOS> metric: macrofscore Kaggle data source: petals-to-the-metal-flower-classification-on-tpu<drop_column> | print("Tensorflow version " + tf.__version__)
AUTO = tf.data.experimental.AUTOTUNE | Petals to the Metal - Flower Classification on TPU |
10,878,259 | dataset=dataset.reset_index(drop=True )<filter> | try:
tpu = tf.distribute.cluster_resolver.TPUClusterResolver()
print('Running on TPU ', tpu.master())
except ValueError:
tpu = None
if tpu:
tf.config.experimental_connect_to_cluster(tpu)
tf.tpu.experimental.initialize_tpu_system(tpu)
strategy = tf.distribute.experimental.TPUStrategy(tpu)
else:
strategy = tf.distribute.get_strategy()
print("REPLICAS: ", strategy.num_replicas_in_sync ) | Petals to the Metal - Flower Classification on TPU |
10,878,259 | dataset=dataset.loc[dataset['LotArea']<dataset['LotArea'].quantile(0.995),:]
dataset=dataset.reset_index(drop=True )<filter> | def data_augment(image, label):
image = tf.image.random_flip_left_right(image)
image = tf.image.random_saturation(image, 0, 2)
return image, label | Petals to the Metal - Flower Classification on TPU |
10,878,259 | dataset=dataset.loc[dataset['MasVnrArea']<=dataset['MasVnrArea'].quantile(0.999),:]
dataset=dataset.reset_index(drop=True )<filter> | GCS_DS_PATH = KaggleDatasets().get_gcs_path()
IMAGE_SIZE = [512, 512]
BATCH_SIZE = 16 * strategy.num_replicas_in_sync
NUM_TRAINING_IMAGES = 12753
NUM_TEST_IMAGES = 7382
STEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE
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 get_training_dataset() :
dataset = load_dataset(tf.io.gfile.glob(GCS_DS_PATH + '/tfrecords-jpeg-512x512/train/*.tfrec'), labeled=True)
dataset = dataset.map(data_augment, num_parallel_calls = AUTO)
dataset = dataset.repeat()
dataset = dataset.shuffle(2048)
dataset = dataset.batch(BATCH_SIZE)
return dataset
def get_validation_dataset() :
dataset = load_dataset(tf.io.gfile.glob(GCS_DS_PATH + '/tfrecords-jpeg-512x512/val/*.tfrec'), labeled=True, ordered=False)
dataset = dataset.batch(BATCH_SIZE)
dataset = dataset.cache()
return dataset
def get_test_dataset(ordered=False):
dataset = load_dataset(tf.io.gfile.glob(GCS_DS_PATH + '/tfrecords-jpeg-512x512/test/*.tfrec'), labeled=False, ordered=ordered)
dataset = dataset.batch(BATCH_SIZE)
return dataset
training_dataset = get_training_dataset()
validation_dataset = get_validation_dataset()
| Petals to the Metal - Flower Classification on TPU |
10,878,259 | dataset=dataset.loc[dataset['BsmtFinSF2']<=dataset['BsmtFinSF2'].quantile(0.9991),:]
dataset=dataset.reset_index(drop=True )<filter> | with strategy.scope() :
pretrained_model = 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'),
tf.keras.layers.Dense(512, activation='relu'),
tf.keras.layers.Dense(104, activation='softmax')
])
LEARNING_RATE = 3e-5 * strategy.num_replicas_in_sync
optimizer = optimizers.Adam(lr=LEARNING_RATE)
model.compile(optimizer=optimizer, loss='sparse_categorical_crossentropy', metrics=['sparse_categorical_accuracy'])
EPOCHS = 35
ES_PATIENCE = 6
LR_START = 0.00000001
LR_MIN = 0.000001
LR_MAX = LEARNING_RATE
LR_RAMPUP_EPOCHS = 3
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
rng = [i for i in range(EPOCHS)]
y = [lrfn(x)for x in rng]
es = EarlyStopping(monitor='val_loss', mode='min', patience=ES_PATIENCE, restore_best_weights=True, verbose=1)
lr_callback = LearningRateScheduler(lrfn, verbose=1)
callback_list = [es, lr_callback]
historical = model.fit(x=get_training_dataset() ,
steps_per_epoch=STEPS_PER_EPOCH,
validation_data=get_validation_dataset() ,
callbacks=callback_list,
epochs=EPOCHS,
verbose=2 ).history | Petals to the Metal - Flower Classification on TPU |
10,878,259 | dataset=dataset.loc[dataset['EnclosedPorch']<=dataset['EnclosedPorch'].quantile(0.997),:]
dataset=dataset.reset_index(drop=True )<sort_values> | 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 ) | Petals to the Metal - Flower Classification on TPU |
10,878,259 | <import_modules><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='' ) | Petals to the Metal - Flower Classification on TPU |
11,290,882 | <SOS> metric: macrofscore Kaggle data source: petals-to-the-metal-flower-classification-on-tpu<data_type_conversions> | !pip install -q efficientnet
| Petals to the Metal - Flower Classification on TPU |
11,290,882 | def _check_numberic(data):
return pd.to_numeric(data[data.notna() ], errors='coerce' ).notnull().all()<import_modules> | 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,290,882 | from sklearn.preprocessing import LabelEncoder<count_missing_values> | np.set_printoptions(threshold=15, linewidth=80)
IMAGE_SIZE = [512, 512]
AUTO = tf.data.experimental.AUTOTUNE
EPOCHS = 12
BATCH_SIZE = 32 * strategy.num_replicas_in_sync | Petals to the Metal - Flower Classification on TPU |
11,290,882 | test.isna().sum()<concatenate> | GCS_DS_PATH = KaggleDatasets().get_gcs_path('tpu-getting-started')
GCS_PATH = GCS_DS_PATH + f'/tfrecords-jpeg-{IMAGE_SIZE[0]}x{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')
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,290,882 | newdata=pd.concat([dataset,test],axis=0 )<count_missing_values> | 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_confusion_matrix(cmat, score, precision, recall):
plt.figure(figsize=(15,15))
ax = plt.gca()
ax.matshow(cmat, cmap='Reds')
ax.set_xticks(range(len(CLASSES)))
ax.set_xticklabels(CLASSES, fontdict={'fontsize': 7})
plt.setp(ax.get_xticklabels() , rotation=45, ha="left", rotation_mode="anchor")
ax.set_yticks(range(len(CLASSES)))
ax.set_yticklabels(CLASSES, fontdict={'fontsize': 7})
plt.setp(ax.get_yticklabels() , rotation=45, ha="right", rotation_mode="anchor")
titlestring = ""
if score is not None:
titlestring += 'f1 = {:.3f} '.format(score)
if precision is not None:
titlestring += '
precision = {:.3f} '.format(precision)
if recall is not None:
titlestring += '
recall = {:.3f} '.format(recall)
if len(titlestring)> 0:
ax.text(101, 1, titlestring, fontdict={'fontsize': 18, 'horizontalalignment':'right', 'verticalalignment':'top', 'color':'
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.'])
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 ) | Petals to the Metal - Flower Classification on TPU |
11,290,882 | newdata.SalePrice.isna().sum()<drop_column> | training_dataset = get_training_dataset()
validation_dataset = get_validation_dataset()
testing_dataset = get_test_dataset() | Petals to the Metal - Flower Classification on TPU |
11,290,882 | newdata=newdata.reset_index(drop=True )<drop_column> | print(f"Training dataset info: {training_dataset}")
print(f"Validation dataset info: {validation_dataset}")
print(f"Test set info: {testing_dataset}" ) | Petals to the Metal - Flower Classification on TPU |
11,290,882 | del newdata['3SsnPorch']
del newdata['Condition2']
del newdata['GarageCars']
del newdata['LowQualFinSF']
del newdata['MiscVal']
del newdata['RoofMatl']
del newdata['Street']
del newdata['Utilities']<feature_engineering> | display_batch_of_images(next(iter(training_dataset.unbatch().batch(12)))) | Petals to the Metal - Flower Classification on TPU |
11,290,882 | newdata['HalfBath']=[1 if val>0 else 0 for val in newdata['HalfBath']]
newdata['PoolArea']=[1 if val>0 else 0 for val in newdata['PoolArea']]<count_missing_values> | with strategy.scope() :
B7_base = efn.EfficientNetB7(weights='imagenet', include_top=False, input_shape=[*IMAGE_SIZE, 3])
B7_base.trainable = True
set_trainable = False
for layer in B7_base.layers:
if layer == B7_base.layers[-96]:
set_trainable = True
if set_trainable:
layer.trainable = True
else:
layer.trainable = False
model = tf.keras.Sequential([
B7_base,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dropout(0.15),
tf.keras.layers.Dense(720, activation = 'relu'),
tf.keras.layers.Dropout(0.15),
tf.keras.layers.Dense(len(CLASSES), activation='softmax')
])
model.compile(
optimizer = tf.keras.optimizers.Adam(learning_rate=0.0005, beta_1=0.9, beta_2=0.999, amsgrad=False),
loss = 'sparse_categorical_crossentropy',
metrics=['sparse_categorical_accuracy'] ,
)
model.summary() | Petals to the Metal - Flower Classification on TPU |
11,290,882 | nacols=newdata.isna().sum()<filter> | NUM_TRAINING_IMAGES = count_data_items(TRAINING_FILENAMES)
STEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE
print(NUM_TRAINING_IMAGES)
print(STEPS_PER_EPOCH)
print(EPOCHS ) | Petals to the Metal - Flower Classification on TPU |
11,290,882 | nacols[nacols>0]<feature_engineering> | history2 = model.fit(training_dataset,
validation_data=validation_dataset,
epochs=EPOCHS,
steps_per_epoch=STEPS_PER_EPOCH ) | Petals to the Metal - Flower Classification on TPU |
11,290,882 | newdata['BsmtFinSF1']=newdata['BsmtFinSF1'].fillna(newdata['BsmtFinSF1'].median())
newdata['BsmtFinSF2']=newdata['BsmtFinSF2'].fillna(newdata['BsmtFinSF2'].median())
newdata['BsmtFullBath']=newdata['BsmtFullBath'].fillna(newdata['BsmtFullBath'].median())
newdata['BsmtHalfBath']=newdata['BsmtHalfBath'].fillna(newdata['BsmtHalfBath'].median())
newdata['BsmtUnfSF']=newdata['BsmtUnfSF'].fillna(newdata['BsmtUnfSF'].median())
newdata['GarageArea']=newdata['GarageArea'].fillna(newdata['GarageArea'].median())
newdata['TotalBsmtSF']=newdata['TotalBsmtSF'].fillna(newdata['TotalBsmtSF'].median() )<count_values> | model.save('model_9383' ) | Petals to the Metal - Flower Classification on TPU |
11,290,882 | col='Exterior1st'
newdata[col]=newdata[col].fillna(newdata[col].value_counts().idxmax())
col='Exterior2nd'
newdata[col]=newdata[col].fillna(newdata[col].value_counts().idxmax())
col='Functional'
newdata[col]=newdata[col].fillna(newdata[col].value_counts().idxmax())
col='KitchenQual'
newdata[col]=newdata[col].fillna(newdata[col].value_counts().idxmax())
col='MSZoning'
newdata[col]=newdata[col].fillna(newdata[col].value_counts().idxmax())
col='SaleType'
newdata[col]=newdata[col].fillna(newdata[col].value_counts().idxmax() )<count_missing_values> | 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 ) | Petals to the Metal - Flower Classification on TPU |
11,290,882 | <filter><EOS> | print('Generating submission.csv file...')
NUM_TEST_IMAGES = count_data_items(TEST_FILENAMES)
test_ids_ds = test_ds.map(lambda image, idnum: idnum ).unbatch()
test_ids = next(iter(test_ids_ds.batch(NUM_TEST_IMAGES)) ).numpy().astype('U')
np.savetxt(
'submission.csv',
np.rec.fromarrays([test_ids, predictions]),
fmt=['%s', '%d'],
delimiter=',',
header='id,label',
comments='',
) | Petals to the Metal - Flower Classification on TPU |
10,764,604 | <SOS> metric: macrofscore Kaggle data source: petals-to-the-metal-flower-classification-on-tpu<categorify> | print("TF version " + tf.__version__)
AUTO = tf.data.experimental.AUTOTUNE | Petals to the Metal - Flower Classification on TPU |
10,764,604 | le=LabelEncoder()
for col in newdata.columns:
if not _check_numberic(newdata[col]):
le.fit(newdata[col])
newdata[col]=le.transform(newdata[col] )<filter> | try:
tpu = tf.distribute.cluster_resolver.TPUClusterResolver()
print('Running on TPU ', tpu.master())
except ValueError:
tpu = None
if tpu:
tf.config.experimental_connect_to_cluster(tpu)
tf.tpu.experimental.initialize_tpu_system(tpu)
strategy = tf.distribute.experimental.TPUStrategy(tpu)
else:
strategy = tf.distribute.get_strategy()
print("REPLICAS: ", strategy.num_replicas_in_sync ) | Petals to the Metal - Flower Classification on TPU |
10,764,604 | test_data=newdata.loc[newdata.SalePrice.isna() ,:]<filter> | IMAGE_SIZE = [224, 224]
EPOCHS = 35
BATCH_SIZE = 16 * strategy.num_replicas_in_sync
SEED = 752
SKIP_VALIDATION = False
TTA_NUM = 5
random.seed(SEED)
np.random.seed(SEED)
tf.random.set_seed(SEED ) | Petals to the Metal - Flower Classification on TPU |
10,764,604 | train_data=newdata.loc[newdata.SalePrice.notna() ,:]<compute_test_metric> | GCS_DS_PATH = KaggleDatasets().get_gcs_path('tpu-getting-started')
GCS_DS_PATH_EXT = KaggleDatasets().get_gcs_path('tf-flower-photo-tfrec')
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]]
GCS_PATH_SELECT_EXT = {
192: '/tfrecords-jpeg-192x192',
224: '/tfrecords-jpeg-224x224',
331: '/tfrecords-jpeg-331x331',
512: '/tfrecords-jpeg-512x512'
}
GCS_PATH_EXT = GCS_PATH_SELECT_EXT[IMAGE_SIZE[0]]
IMAGENET_FILES = tf.io.gfile.glob(GCS_DS_PATH_EXT + '/imagenet' + GCS_PATH_EXT + '/*.tfrec')
INATURELIST_FILES = tf.io.gfile.glob(GCS_DS_PATH_EXT + '/inaturalist' + GCS_PATH_EXT + '/*.tfrec')
OPENIMAGE_FILES = tf.io.gfile.glob(GCS_DS_PATH_EXT + '/openimage' + GCS_PATH_EXT + '/*.tfrec')
OXFORD_FILES = tf.io.gfile.glob(GCS_DS_PATH_EXT + '/oxford_102' + GCS_PATH_EXT + '/*.tfrec')
TENSORFLOW_FILES = tf.io.gfile.glob(GCS_DS_PATH_EXT + '/tf_flowers' + GCS_PATH_EXT + '/*.tfrec')
ADDITIONAL_TRAINING_FILENAMES = IMAGENET_FILES + INATURELIST_FILES + OPENIMAGE_FILES + OXFORD_FILES + TENSORFLOW_FILES
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']
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')
TRAINING_FILENAMES = TRAINING_FILENAMES + ADDITIONAL_TRAINING_FILENAMES | Petals to the Metal - Flower Classification on TPU |
10,764,604 | def rmsle(y, y_pred):
assert len(y)== len(y_pred)
terms_to_sum = [(math.log(y_pred[i] + 1)- math.log(y[i] + 1)) ** 2.0 for i,pred in enumerate(y_pred)]
return(sum(terms_to_sum)*(1.0/len(y)))** 0.5<import_modules> | np.set_printoptions(threshold=15, linewidth=80)
def batch_to_numpy_images_and_labels(data):
images, labels = data
numpy_images = images.numpy()
numpy_labels = labels.numpy()
if numpy_labels.dtype == object:
numpy_labels = [None for _ in enumerate(numpy_images)]
return numpy_images, numpy_labels
def title_from_label_and_target(label, correct_label):
if correct_label is None:
return CLASSES[label], True
correct =(label == correct_label)
return "{} [{}{}{}]".format(CLASSES[label], 'OK' if correct else 'NO', u"\u2192" if not correct else '',
CLASSES[correct_label] if not correct else ''), correct
def 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_confusion_matrix(cmat, score, precision, recall):
plt.figure(figsize=(15,15))
ax = plt.gca()
ax.matshow(cmat, cmap='Reds')
ax.set_xticks(range(len(CLASSES)))
ax.set_xticklabels(CLASSES, fontdict={'fontsize': 7})
plt.setp(ax.get_xticklabels() , rotation=45, ha="left", rotation_mode="anchor")
ax.set_yticks(range(len(CLASSES)))
ax.set_yticklabels(CLASSES, fontdict={'fontsize': 7})
plt.setp(ax.get_yticklabels() , rotation=45, ha="right", rotation_mode="anchor")
titlestring = ""
if score is not None:
titlestring += 'f1 = {:.3f} '.format(score)
if precision is not None:
titlestring += '
precision = {:.3f} '.format(precision)
if recall is not None:
titlestring += '
recall = {:.3f} '.format(recall)
if len(titlestring)> 0:
ax.text(101, 1, titlestring, fontdict={'fontsize': 18, 'horizontalalignment':'right', 'verticalalignment':'top', 'color':'
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 |
10,764,604 | from sklearn.model_selection import train_test_split<import_modules> | 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 |
10,764,604 | from sklearn.model_selection import train_test_split<drop_column> | 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, seed=SEED)
image = random_blockout(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 |
10,764,604 | features.remove('Id')
features.remove('SalePrice' )<prepare_x_and_y> | if SKIP_VALIDATION:
TRAINING_FILENAMES = TRAINING_FILENAMES + VALIDATION_FILENAMES | Petals to the Metal - Flower Classification on TPU |
10,764,604 | train=train_data[features].values
train_y=train_data['SalePrice']<normalization> | 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 |
10,764,604 | sc= RobustScaler()
sc.fit(train)
train=sc.transform(train )<import_modules> | 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 |
10,764,604 | from sklearn.model_selection import train_test_split<import_modules> | display_batch_of_images(next(train_batch)) | Petals to the Metal - Flower Classification on TPU |
10,764,604 | from sklearn.model_selection import train_test_split<split> | test_dataset = get_test_dataset()
test_dataset = test_dataset.unbatch().batch(20)
test_batch = iter(test_dataset ) | Petals to the Metal - Flower Classification on TPU |
10,764,604 | x_train,x_test,y_train,y_test=train_test_split(train,train_y,test_size=0.2 )<train_model> | display_batch_of_images(next(test_batch)) | Petals to the Metal - Flower Classification on TPU |
10,764,604 | rf = RandomForestRegressor(n_estimators = 120, random_state = 42 )<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 |
10,764,604 | rf.fit(x_train, y_train )<predict_on_test> | !pip install -q efficientnet
| Petals to the Metal - Flower Classification on TPU |
10,764,604 | predictions=rf.predict(x_test)
rmsle(y_test.to_list() ,predictions )<import_modules> | 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')
])
model1.compile(
optimizer=tf.keras.optimizers.Adam() ,
loss = 'sparse_categorical_crossentropy',
metrics=['sparse_categorical_accuracy']
)
model1.summary() | Petals to the Metal - Flower Classification on TPU |
10,764,604 | from sklearn.metrics import mean_squared_error<import_modules> | 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 |
10,764,604 | from sklearn.metrics import mean_squared_error<import_modules> | 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 |
10,764,604 | import xgboost as xgb<choose_model_class> | 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 |
10,764,604 | model=xgb.XGBRegressor(base_score=0.5, booster='gbtree', colsample_bylevel=1,
colsample_bynode=1, colsample_bytree=0.4603, gamma=0.0468,
importance_type='split', learning_rate=0.05, max_delta_step=0,
max_depth=20, min_child_weight=1.7817, missing=None,
n_estimators=1024, n_jobs=1, nthread=-1, objective='reg:squarederror',
random_state=7, reg_alpha=0.464, reg_lambda=0.8571,
scale_pos_weight=1, seed=None, silent=1, subsample=0.5213,
verbosity=1 )<train_model> | 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 |
10,764,604 | model.fit(x_train,y_train )<predict_on_test> | 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 |
10,764,604 | predictions=model.predict(x_test)
rmsle(y_test.to_list() ,predictions )<choose_model_class> | def predict_tta(model, n_iter):
probs = []
for i in range(n_iter):
test_ds = get_test_dataset(ordered=True)
test_images_ds = test_ds.map(lambda image, idnum: image)
probs.append(model.predict(test_images_ds,verbose=0))
return probs | Petals to the Metal - Flower Classification on TPU |
10,764,604 | <compute_train_metric><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 |
10,977,475 | <SOS> metric: macrofscore Kaggle data source: petals-to-the-metal-flower-classification-on-tpu<compute_test_metric> | import numpy as np
import tensorflow as tf
import pandas as pd
import random, re, math
from tensorflow import keras
import matplotlib.pyplot as plt
from kaggle_datasets import KaggleDatasets
from keras.callbacks import LearningRateScheduler
from keras import backend as K
from keras import layers
from sklearn.model_selection import KFold | Petals to the Metal - Flower Classification on TPU |
10,977,475 | score=rmsle_cv(model_lgb)
print("Xgboost score: {:.4f}({:.4f})
".format(score.mean() , score.std()))<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)
CLASSES = ['pink primrose', 'hard-leaved pocket orchid', 'canterbury bells', 'sweet pea', 'wild geranium', 'tiger lily', 'moon orchid', 'bird of paradise', 'monkshood', 'globe thistle',
'snapdragon', "colt's foot", 'king protea', 'spear thistle', 'yellow iris', 'globe-flower', 'purple coneflower', 'peruvian lily', 'balloon flower', 'giant white arum lily',
'fire lily', 'pincushion flower', 'fritillary', 'red ginger', 'grape hyacinth', 'corn poppy', 'prince of wales feathers', 'stemless gentian', 'artichoke', 'sweet william',
'carnation', 'garden phlox', 'love in the mist', 'cosmos', 'alpine sea holly', 'ruby-lipped cattleya', 'cape flower', 'great masterwort', 'siam tulip', 'lenten rose',
'barberton daisy', 'daffodil', 'sword lily', 'poinsettia', 'bolero deep blue', 'wallflower', 'marigold', 'buttercup', 'daisy', 'common dandelion',
'petunia', 'wild pansy', 'primula', 'sunflower', 'lilac hibiscus', 'bishop of llandaff', 'gaura', 'geranium', 'orange dahlia', 'pink-yellow dahlia',
'cautleya spicata', 'japanese anemone', 'black-eyed susan', 'silverbush', 'californian poppy', 'osteospermum', 'spring crocus', 'iris', 'windflower', 'tree poppy',
'gazania', 'azalea', 'water lily', 'rose', 'thorn apple', 'morning glory', 'passion flower', 'lotus', 'toad lily', 'anthurium',
'frangipani', 'clematis', 'hibiscus', 'columbine', 'desert-rose', 'tree mallow', 'magnolia', 'cyclamen ', 'watercress', 'canna lily',
'hippeastrum ', 'bee balm', 'pink quill', 'foxglove', 'bougainvillea', 'camellia', 'mallow', 'mexican petunia', 'bromelia', 'blanket flower',
'trumpet creeper', 'blackberry lily', 'common tulip', 'wild rose'] | Petals to the Metal - Flower Classification on TPU |
10,977,475 | model_lgb.fit(train,train_y )<predict_on_test> | 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 |
10,977,475 | model.fit(x_train,y_train)
predictions=model.predict(x_test)
rmsle(y_test.to_list() ,predictions )<choose_model_class> | NUM_TRAINING_IMAGES = count_data_items(TRAINING_FILENAMES)
NUM_VALIDATION_IMAGES = count_data_items(VALIDATION_FILENAMES)
NUM_TEST_IMAGES = count_data_items(TEST_FILENAMES)
print('Dataset: {} training images, {} validation images, {} unlabeled test images'.format(NUM_TRAINING_IMAGES, NUM_VALIDATION_IMAGES, NUM_TEST_IMAGES)) | Petals to the Metal - Flower Classification on TPU |
10,977,475 | model_lgb=lgb.LGBMRegressor(bagging_fraction=0.8, bagging_freq=5, bagging_seed=9,
boosting_type='gbdt', class_weight=None, colsample_bytree=1.0,
feature_fraction=0.8, feature_fraction_seed=9,
importance_type='gain', learning_rate=0.02, max_bin=55,
max_depth=-1, min_child_samples=30, min_child_weight=0.01,
min_data_in_leaf=6, min_split_gain=0.0,
min_sum_hessian_in_leaf=11, n_estimators=1024, n_jobs=-1,
num_leaves=20, objective='regression', random_state=None,
reg_alpha=0.01, reg_lambda=0.01, silent=True, subsample=1.0,
subsample_for_bin=200000, subsample_freq=0 )<predict_on_test> | train_dataset = load_dataset(TRAINING_FILENAMES, labeled = True)
valid_dataset = load_dataset(VALIDATION_FILENAMES, labeled=True, ordered=True)
test_dataset = get_test_dataset(ordered=True)
print('Loaded Datasets.... ' ) | Petals to the Metal - Flower Classification on TPU |
10,977,475 | model_lgb.fit(x_train,y_train)
predictions=model_lgb.predict(x_test)
rmsle(y_test.to_list() ,predictions )<normalization> | from tensorflow.keras.applications import ResNet50, Xception, DenseNet201
from tensorflow.keras import Sequential
from keras.layers import Dense, GlobalAveragePooling2D | Petals to the Metal - Flower Classification on TPU |
10,977,475 | test_sc=sc.transform(test_data[features].values )<predict_on_test> | def build_xception_network() :
with strategy.scope() :
network = Xception(input_shape=(IMAGE_SIZE[0], IMAGE_SIZE[1], 3),weights='imagenet',include_top=False)
network.trainable = True
model = Sequential([network, GlobalAveragePooling2D() , Dense(len(CLASSES), activation = 'softmax', dtype = 'float32')])
opt = 'Adam'
model.compile(optimizer = opt, loss = 'sparse_categorical_crossentropy', metrics = ['sparse_categorical_accuracy'])
return model
def build_resnet_network() :
with strategy.scope() :
network = ResNet50(input_shape=(IMAGE_SIZE[0], IMAGE_SIZE[1], 3),weights='imagenet',include_top=False)
network.trainable = True
model = Sequential([network, GlobalAveragePooling2D() , Dense(len(CLASSES), activation = 'softmax', dtype = 'float32')])
opt = 'Adam'
model.compile(optimizer = opt, loss = 'sparse_categorical_crossentropy', metrics = ['sparse_categorical_accuracy'])
return model
def build_densenet_network() :
with strategy.scope() :
network = DenseNet201(input_shape=(IMAGE_SIZE[0], IMAGE_SIZE[1], 3),weights='imagenet',include_top=False)
network.trainable = True
model = Sequential([network, GlobalAveragePooling2D() , Dense(len(CLASSES), activation = 'softmax', dtype = 'float32')])
opt = 'Adam'
model.compile(optimizer = opt, loss = 'sparse_categorical_crossentropy', metrics = ['sparse_categorical_accuracy'])
return model | Petals to the Metal - Flower Classification on TPU |
10,977,475 | model_lgb.fit(train,train_y)
predicted_values=model_lgb.predict(test_sc )<train_model> | print('Computing predictions.... ')
test_images_ds = test_dataset.map(lambda image, idnum: image)
test_ids_ds = test_dataset.map(lambda image, idnum: idnum ).unbatch()
test_ids = next(iter(test_ids_ds.batch(NUM_TEST_IMAGES)) ).numpy().astype('U')
probabilities = 0.25*model_resnet.predict(test_images_ds)+0.25*model_xception.predict(test_images_ds)+0.5*model_densenet.predict(test_images_ds)
predictions = np.argmax(probabilities, axis=-1)
print('Compiling submission file...')
np.savetxt('submission.csv',np.rec.fromarrays([test_ids, predictions]),fmt=['%s', '%d'],delimiter=',',header='id,label',comments='' ) | Petals to the Metal - Flower Classification on TPU |
10,977,475 | <create_dataframe><EOS> | cmdataset = get_validation_dataset(load_dataset(VALIDATION_FILENAMES, labeled = True, 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_xception.predict(images_ds)
cm_predictions = np.argmax(cm_probabilities, axis=-1)
cmat_1 = confusion_matrix(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)))
score_1 = f1_score(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)) , average='macro')
precision_1 = precision_score(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)) , average='macro')
recall_1 = recall_score(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)) , average='macro')
cmat_1 =(cmat_1.T / cmat_1.sum(axis=1)).T
display_confusion_matrix(cmat_1, score_1, precision_1, recall_1)
cm_correct_labels = next(iter(labels_ds.batch(NUM_VALIDATION_IMAGES)) ).numpy()
cm_probabilities = model_resnet.predict(images_ds)
cm_predictions = np.argmax(cm_probabilities, axis=-1)
cmat_2 = confusion_matrix(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)))
score_2 = f1_score(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)) , average='macro')
precision_2 = precision_score(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)) , average='macro')
recall_2 = recall_score(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)) , average='macro')
cmat_2 =(cmat_2.T / cmat_2.sum(axis=1)).T
display_confusion_matrix(cmat_2, score_2, precision_2, recall_2)
cm_correct_labels = next(iter(labels_ds.batch(NUM_VALIDATION_IMAGES)) ).numpy()
cm_probabilities = model_densenet.predict(images_ds)
cm_predictions = np.argmax(cm_probabilities, axis=-1)
cmat_3 = confusion_matrix(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)))
score_3 = f1_score(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)) , average='macro')
precision_3 = precision_score(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)) , average='macro')
recall_3 = recall_score(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)) , average='macro')
cmat_3 =(cmat_3.T / cmat_3.sum(axis=1)).T
display_confusion_matrix(cmat_3, score_3, precision_3, recall_3)
cm_correct_labels = next(iter(labels_ds.batch(NUM_VALIDATION_IMAGES)) ).numpy()
cm_probabilities = 0.25*model_resnet.predict(images_ds)+0.25*model_xception.predict(images_ds)+0.5*model_densenet.predict(images_ds)
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')
cmat =(cmat.T / cmat.sum(axis=1)).T
display_confusion_matrix(cmat, score, precision, recall)
| Petals to the Metal - Flower Classification on TPU |
10,871,371 | <SOS> metric: macrofscore Kaggle data source: petals-to-the-metal-flower-classification-on-tpu<save_to_csv> | print('Tensorflow version ' + tf.__version__)
!pip install -q efficientnet
| Petals to the Metal - Flower Classification on TPU |
10,871,371 | output.to_csv('sample_submission.csv',index=False )<set_options> | try:
tpu = tf.distribute.cluster_resolver.TPUClusterResolver()
print('Running on TPU ', tpu.master())
except ValueError:
tpu = None
if tpu:
tf.config.experimental_connect_to_cluster(tpu)
tf.tpu.experimental.initialize_tpu_system(tpu)
strategy = tf.distribute.experimental.TPUStrategy(tpu)
else:
strategy = tf.distribute.get_strategy()
print("REPLICAS: ", strategy.num_replicas_in_sync ) | Petals to the Metal - Flower Classification on TPU |
10,871,371 | device = torch.device('cuda' if torch.cuda.is_available() else 'cpu' )<load_from_csv> | 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 |
10,871,371 | train=pd.read_csv(".. /input/digit-recognizer/train.csv")
test=pd.read_csv(".. /input/digit-recognizer/test.csv")
label=train["label"]
train=train.drop(labels = ["label"],axis = 1)
train=train/255
test=test/255<init_hyperparams> | 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 |
10,871,371 | datagen = ImageDataGenerator(
rotation_range=10,
zoom_range = 0.10,
width_shift_range=0.1,
height_shift_range=0.1
)<create_dataframe> | 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 |
10,871,371 | train=torch.tensor(train, dtype=torch.float)
label=torch.tensor(label.values, dtype=torch.float)
batch_size = 32
train_data = torch.utils.data.TensorDataset(train,label)
train_iter = torch.utils.data.DataLoader(train_data, batch_size=batch_size, shuffle=True )<define_search_model> | 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 |
10,871,371 | class Residual(nn.Module):
def __init__(self, in_channels, out_channels, use_1x1conv=False, stride=1):
super(Residual, self ).__init__()
self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=1, stride=stride)
self.conv2 = nn.Conv2d(out_channels, out_channels, kernel_size=3, padding=1)
if use_1x1conv:
self.conv3 = nn.Conv2d(in_channels, out_channels, kernel_size=1, stride=stride)
else:
self.conv3 = None
self.bn1 = nn.BatchNorm2d(out_channels)
self.bn2 = nn.BatchNorm2d(out_channels)
def forward(self, X):
Y = F.relu(self.bn1(self.conv1(X)))
Y = self.bn2(self.conv2(Y))
if self.conv3:
X = self.conv3(X)
return F.relu(Y + X )<define_search_model> | 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,
'EfficientNetB7' : EfficientNetB7_model,
'MobileNetV2' : MobileNetV2_model,
}
historys = {}
predictions = {}
predictions_val = {}
predictions_prob = {}
MODELS_NUMBER = 6 | Petals to the Metal - Flower Classification on TPU |
10,871,371 | def resnet_block(in_channels, out_channels, num_residuals, first_block=False):
if first_block:
assert in_channels == out_channels
blk = []
for i in range(num_residuals):
if i == 0 and not first_block:
blk.append(Residual(in_channels, out_channels, use_1x1conv=True, stride=2))
else:
blk.append(Residual(out_channels, out_channels))
return nn.Sequential(*blk )<choose_model_class> | 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,'Xception'])
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,'Xception'] ) | Petals to the Metal - Flower Classification on TPU |
10,871,371 | net = nn.Sequential(
nn.Conv2d(1, 32, kernel_size=7, stride=2, padding=3),
nn.BatchNorm2d(32),
nn.ReLU() ,
nn.MaxPool2d(kernel_size=3, stride=2, padding=1),
resnet_block(32, 32, 2, first_block=True),
resnet_block(32, 64, 2),
resnet_block(64, 128, 2),
resnet_block(128, 256, 2),
nn.AdaptiveAvgPool2d(( 1,1)) ,
nn.Flatten() ,
nn.Linear(256,10),
)<choose_model_class> | avg_prob = predictions_prob['Xception'] + predictions_prob['VGG16'] + predictions_prob['DenseNet201'] + predictions_prob['InceptionV3'] + predictions_prob['EfficientNetB7']
pred_avg = pd.DataFrame(np.argmax(avg_prob, axis=-1)) | Petals to the Metal - Flower Classification on TPU |
10,871,371 | <train_model><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 |
10,859,686 | <SOS> metric: macrofscore Kaggle data source: petals-to-the-metal-flower-classification-on-tpu<save_to_csv> | !pip install -U -t /kaggle/working/ git+https://github.com/Kaggle/learntools.git
binder.bind(globals())
step_1.check() | Petals to the Metal - Flower Classification on TPU |
10,859,686 | test=torch.tensor(test, dtype=torch.float)
sub=net(test)
sub=sub.argmax(dim=1)
sub=sub.numpy()
sub.reshape(-1,1)
submission=pd.read_csv(".. /input/digit-recognizer/sample_submission.csv")
submission["Label"]=sub
submission.to_csv('submission.csv', index=False )<count_duplicates> | from petal_helper import * | Petals to the Metal - Flower Classification on TPU |
10,859,686 | duplicate_count = train["Id"].nunique() - train.shape[0];
if(duplicate_count == 0):
print("There is no duplicate data in the train data.")
else:
print("There are %d duplicate data in the train data." %duplicate_count)
train.drop("Id", axis = 1, inplace = True )<define_variables> | try:
tpu = tf.distribute.cluster_resolver.TPUClusterResolver()
print('Running on TPU ', tpu.master())
except ValueError:
tpu = None
if tpu:
tf.config.experimental_connect_to_cluster(tpu)
tf.tpu.experimental.initialize_tpu_system(tpu)
strategy = tf.distribute.experimental.TPUStrategy(tpu)
else:
strategy = tf.distribute.get_strategy()
print("REPLICAS: ", strategy.num_replicas_in_sync ) | Petals to the Metal - Flower Classification on TPU |
10,859,686 | med = train['SalePrice'].median()
medAbsDev = abs(train['SalePrice'] - med ).median()
ind =(abs(train['SalePrice'] - med)*.6745 / medAbsDev)> 3.5
print("There are suspected %d outliers in the train data." % sum(ind))
train = train[-ind]
train = train[train.GrLivArea < 4000]<data_type_conversions> | 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 |
10,859,686 | train["Alley"].fillna("None", inplace=True)
train["BsmtQual"].fillna("None", inplace=True)
train["BsmtCond"].fillna("None", inplace=True)
train["BsmtExposure"].fillna("None", inplace=True)
train["BsmtFinType1"].fillna("None", inplace=True)
train["BsmtFinSF1"].fillna(0, inplace=True)
train["BsmtFinType2"].fillna("None", inplace=True)
train["BsmtFinSF2"].fillna(0, inplace=True)
train["BsmtFullBath"].fillna(0, inplace=True)
train["BsmtHalfBath"].fillna(0, inplace=True)
train["BsmtUnfSF"].fillna(0, inplace=True)
train["TotalBsmtSF"].fillna(0, inplace=True)
train["KitchenQual"].fillna(0, inplace=True)
train["Functional"].fillna(0, inplace=True)
train["FireplaceQu"].fillna("None", inplace=True)
train["GarageType"].fillna("None", inplace=True)
train["GarageQual"].fillna(0, inplace=True)
train["GarageCond"].fillna(0, inplace=True)
train["GarageYrBlt"].fillna("None", inplace=True)
train["GarageFinish"].fillna("None", inplace=True)
train["GarageCars"].fillna(0, inplace=True)
train["GarageArea"].fillna(0, inplace=True)
train["PoolQC"].fillna("None", inplace=True)
train["Fence"].fillna("None", inplace=True)
train["MiscFeature"].fillna("None", inplace=True)
train["LotFrontage"].fillna(0, inplace=True)
train["MasVnrType"].fillna("None", inplace=True)
train["MasVnrArea"].fillna(0, inplace=True)
train["Electrical"].fillna("SBrkr", inplace=True)
train["Utilities"].fillna("None", inplace=True)
<categorify> | print("Number of classes: {}".format(len(CLASSES)))
print("First five classes, sorted alphabetically:")
for name in sorted(CLASSES)[:5]:
print(name)
print("Number of training images: {}".format(NUM_TRAINING_IMAGES)) | Petals to the Metal - Flower Classification on TPU |
10,859,686 | train = train.replace({"MSSubClass" : {20 : "SC20", 30 : "SC30", 40 : "SC40", 45 : "SC45", 50 : "SC50", 60 : "SC60",
70 : "SC70", 75 : "SC75", 80 : "SC80", 85 : "SC85", 90 : "SC90", 120 : "SC120", 150 : "SC150", 160 : "SC160",
180 : "SC180", 190 : "SC190"},
"MoSold" : {1 : "Jan", 2 : "Feb", 3 : "Mar", 4 : "Apr", 5 : "May", 6 : "Jun", 7 : "Jul", 8 : "Aug", 9 : "Sep",
10 : "Oct", 11 : "Nov", 12 : "Dec"} })
train = train.replace({"Alley" : {"Grvl" : 1, "Pave" : 2},
"BsmtCond" : {"No" : 0, "Po" : 1, "Fa" : 2, "TA" : 3, "Gd" : 4, "Ex" : 5},
"BsmtExposure" : {"No" : 0, "Mn" : 1, "Av": 2, "Gd" : 3},
"BsmtFinType1" : {"No" : 0, "Unf" : 1, "LwQ": 2, "Rec" : 3, "BLQ" : 4, "ALQ" : 5, "GLQ" : 6},
"BsmtFinType2" : {"No" : 0, "Unf" : 1, "LwQ": 2, "Rec" : 3, "BLQ" : 4, "ALQ" : 5, "GLQ" : 6},
"BsmtQual" : {"No" : 0, "Po" : 1, "Fa" : 2, "TA": 3, "Gd" : 4, "Ex" : 5},
"ExterCond" : {"Po" : 1, "Fa" : 2, "TA": 3, "Gd": 4, "Ex" : 5},
"ExterQual" : {"Po" : 1, "Fa" : 2, "TA": 3, "Gd": 4, "Ex" : 5},
"FireplaceQu" : {"No" : 0, "Po" : 1, "Fa" : 2, "TA" : 3, "Gd" : 4, "Ex" : 5},
"Functional" : {"Sal" : 1, "Sev" : 2, "Maj2" : 3, "Maj1" : 4, "Mod": 5, "Min2" : 6, "Min1" : 7, "Typ" : 8},
"GarageCond" : {"None" : 0, "No" : 0, "Po" : 1, "Fa" : 2, "TA" : 3, "Gd" : 4, "Ex" : 5},
"GarageQual" : {"None" : 0, "No" : 0, "Po" : 1, "Fa" : 2, "TA" : 3, "Gd" : 4, "Ex" : 5},
"HeatingQC" : {"Po" : 1, "Fa" : 2, "TA" : 3, "Gd" : 4, "Ex" : 5},
"KitchenQual" : {"Po" : 1, "Fa" : 2, "TA" : 3, "Gd" : 4, "Ex" : 5},
"LandSlope" : {"Sev" : 1, "Mod" : 2, "Gtl" : 3},
"LotShape" : {"IR3" : 1, "IR2" : 2, "IR1" : 3, "Reg" : 4},
"PavedDrive" : {"N" : 0, "P" : 1, "Y" : 2},
"PoolQC" : {"No" : 0, "Fa" : 1, "TA" : 2, "Gd" : 3, "Ex" : 4},
"Street" : {"Grvl" : 1, "Pave" : 2},
"Utilities" : {"None" : 0, "ELO" : 1, "NoSeWa" : 2, "NoSewr" : 3, "AllPub" : 4}} )<feature_engineering> | print("Training data shapes:")
for image, label in ds_train.take(3):
print(image.numpy().shape, label.numpy().shape)
print("Training data label examples:", label.numpy() ) | Petals to the Metal - Flower Classification on TPU |
10,859,686 | train["OverallGrade"] = train["OverallQual"] * train["OverallCond"]
train["GarageGrade"] = train["GarageQual"] * train["GarageCond"]
train["ExterGrade"] = train["ExterQual"] * train["ExterCond"]
train["KitchenScore"] = train["KitchenAbvGr"] * train["KitchenQual"]
train["FireplaceScore"] = train["Fireplaces"] * train["FireplaceQu"]
train["GarageScore"] = train["GarageArea"] * train["GarageQual"]
train["PoolScore"] = train["PoolArea"] * train["PoolQC"]
train["TotalBath"] = train["BsmtFullBath"] + train["BsmtHalfBath"]/2 + train["FullBath"] + train["HalfBath"]/2
train["AllSF"] = train["GrLivArea"] + train["TotalBsmtSF"]
train["AllFlrsSF"] = train["1stFlrSF"] + train["2ndFlrSF"]
train["AllPorchSF"] = train["OpenPorchSF"] + train["EnclosedPorch"] + train["3SsnPorch"] + train["ScreenPorch"]<sort_values> | print("Test data shapes:")
for image, idnum in ds_test.take(3):
print(image.numpy().shape, idnum.numpy().shape)
print("Test data IDs:", idnum.numpy().astype('U')) | Petals to the Metal - Flower Classification on TPU |
10,859,686 | corr = train.corr()
corr.sort_values(["SalePrice"], ascending = False, inplace = True)
corr.SalePrice<feature_engineering> | one_batch = next(iter(ds_train.unbatch().batch(20)))
display_batch_of_images(one_batch ) | Petals to the Metal - Flower Classification on TPU |
10,859,686 | train["AllSF-s2"] = train["AllSF"] ** 2
train["AllSF-Sq"] = np.sqrt(train["AllSF"])
train["OverallQual-s2"] = train["OverallQual"] ** 2
train["OverallQual-Sq"] = np.sqrt(train["OverallQual"])
train["AllFlrsSF-s2"] = train["AllFlrsSF"] ** 2
train["AllFlrsSF-Sq"] = np.sqrt(train["AllFlrsSF"])
train["GrLivArea-s2"] = train["GrLivArea"] ** 2
train["GrLivArea-Sq"] = np.sqrt(train["GrLivArea"])
train["ExterQual-s2"] = train["ExterQual"] ** 2
train["ExterQual-Sq"] = np.sqrt(train["ExterQual"] )<categorify> | pip install -q efficientnet | Petals to the Metal - Flower Classification on TPU |
10,859,686 | categorical_features = train.select_dtypes(include = ["object"] ).columns
numerical_features = train.select_dtypes(exclude = ["object"] ).columns
numerical_features = numerical_features.drop("SalePrice")
train_num = train[numerical_features]
train_cat = train[categorical_features]
skewness = train_num.apply(lambda x: skew(x))
skewness = skewness[abs(skewness)> 0.5]
print("%d out of %d numerical features are skewed.Apply log transform to these features." %(skewness.shape[0],
train_num.shape[1]))
train_num.loc[:,skewness.index] = np.log1p(np.asarray(train_num[skewness.index] , dtype=float))
train_cat = pd.get_dummies(train_cat )<train_model> | import efficientnet.tfkeras as efficientnet | Petals to the Metal - Flower Classification on TPU |
10,859,686 | y = np.log1p(train["SalePrice"])
X_train, X_test, y_train, y_test = train_test_split(pd.concat([train_num, train_cat], axis = 1),
y, test_size = 0.3, random_state = 514)
stdSc = StandardScaler()
X_train.loc[:, numerical_features] = stdSc.fit_transform(X_train.loc[:, numerical_features])
X_test.loc[:, numerical_features] = stdSc.transform(X_test.loc[:, numerical_features] )<compute_train_metric> | with strategy.scope() :
pretrained_model = efficientnet.EfficientNetB7(weights='noisy-student',include_top=False,input_shape=[*IMAGE_SIZE, 3])
pretrained_model.trainable=True
model = Sequential()
model.add(pretrained_model)
model.add(GlobalAveragePooling2D())
model.add(Dense(104, activation='softmax'))
model.compile(optimizer="adam",loss="sparse_categorical_crossentropy",metrics=["sparse_categorical_accuracy"] ) | Petals to the Metal - Flower Classification on TPU |
10,859,686 | scorer = make_scorer(mean_squared_error, greater_is_better = True)
def rmse_cv_train(model):
rmse = np.sqrt(cross_val_score(model, X_train, y_train, scoring = scorer, cv = 10))
return(rmse)
def rmse_cv_test(model):
rmse = np.sqrt(cross_val_score(model, X_test, y_test, scoring = scorer, cv = 10))
return(rmse )<train_model> | es = EarlyStopping(monitor='val_loss', mode='min', patience=6,
restore_best_weights=True, verbose=1)
lr = ReduceLROnPlateau(monitor='val_loss',factor=0.2,patience=4,verbose=1)
callbacks = [es, lr] | Petals to the Metal - Flower Classification on TPU |
10,859,686 | elasticNet = ElasticNetCV(l1_ratio = [0.1, 0.3, 0.5, 0.6, 0.7, 0.8, 0.85, 0.9, 0.95, 1],
alphas = [0.0001, 0.001, 0.01, 0.1, 1],
max_iter = 50000, cv = 10)
elasticNet.fit(X_train, y_train)
alpha = elasticNet.alpha_
ratio = elasticNet.l1_ratio_
print("Best l1_ratio :", ratio)
print("Best alpha :", alpha )<train_on_grid> | BATCH_SIZE = 16 * strategy.num_replicas_in_sync
EPOCHS = 30
STEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE
history = model.fit(
ds_train,
validation_data=ds_valid,
epochs=EPOCHS,
steps_per_epoch=STEPS_PER_EPOCH,
callbacks=callbacks
) | Petals to the Metal - Flower Classification on TPU |
10,859,686 | print("Try again for more precision with l1_ratio centered around " + str(ratio))
elasticNet = ElasticNetCV(l1_ratio = [ratio *.9, ratio *.95, ratio, ratio * 1.05, ratio * 1.1],
alphas = [0.0001, 0.001, 0.01, 0.1, 1],
max_iter = 50000, cv = 10)
elasticNet.fit(X_train, y_train)
alpha = elasticNet.alpha_
ratio = elasticNet.l1_ratio_
print("Best l1_ratio :", ratio)
print("Best alpha :", alpha )<train_on_grid> | 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)
labels = range(len(CLASSES))
cmat = confusion_matrix(
cm_correct_labels,
cm_predictions,
labels=labels,
)
cmat =(cmat.T / cmat.sum(axis=1)).T | Petals to the Metal - Flower Classification on TPU |
10,859,686 | print("Now try again for more precision on alpha, with l1_ratio fixed at " + str(ratio)+
" and alpha centered around " + str(alpha))
elasticNet = ElasticNetCV(l1_ratio = ratio,
alphas = [alpha *.6, alpha *.7, alpha *.8, alpha *.9,
alpha, alpha * 1.1, alpha * 1.2, alpha * 1.3, alpha * 1.4],
max_iter = 50000, cv = 5)
elasticNet.fit(X_train, y_train)
print("Best l1_ratio :", elasticNet.l1_ratio_)
print("Best alpha :", elasticNet.alpha_)
print("ElasticNet RMSE on Training set :", rmse_cv_train(elasticNet ).mean())
print("ElasticNet RMSE on Test set :", rmse_cv_test(elasticNet ).mean())
y_train_ela = elasticNet.predict(X_train)
y_test_ela = elasticNet.predict(X_test )<load_from_csv> | score = f1_score(
cm_correct_labels,
cm_predictions,
labels=labels,
average='macro',
)
precision = precision_score(
cm_correct_labels,
cm_predictions,
labels=labels,
average='macro',
)
recall = recall_score(
cm_correct_labels,
cm_predictions,
labels=labels,
average='macro',
)
display_confusion_matrix(cmat, score, precision, recall ) | Petals to the Metal - Flower Classification on TPU |
10,859,686 | test = pd.read_csv("/kaggle/input/house-prices-advanced-regression-techniques/test.csv")
test["Alley"].fillna("None", inplace=True)
test["BsmtQual"].fillna("None", inplace=True)
test["BsmtCond"].fillna("None", inplace=True)
test["BsmtExposure"].fillna("None", inplace=True)
test["BsmtFinType1"].fillna("None", inplace=True)
test["BsmtFinSF1"].fillna(0, inplace=True)
test["BsmtFinType2"].fillna("None", inplace=True)
test["BsmtFinSF2"].fillna(0, inplace=True)
test["BsmtFullBath"].fillna(0, inplace=True)
test["BsmtHalfBath"].fillna(0, inplace=True)
test["BsmtUnfSF"].fillna(0, inplace=True)
test["TotalBsmtSF"].fillna(0, inplace=True)
test["KitchenQual"].fillna(0, inplace=True)
test["Functional"].fillna(0, inplace=True)
test["FireplaceQu"].fillna("None", inplace=True)
test["GarageType"].fillna("None", inplace=True)
test["GarageQual"].fillna(0, inplace=True)
test["GarageCond"].fillna(0, inplace=True)
test["GarageYrBlt"].fillna("None", inplace=True)
test["GarageFinish"].fillna("None", inplace=True)
test["GarageCars"].fillna(0, inplace=True)
test["GarageArea"].fillna(0, inplace=True)
test["PoolQC"].fillna("None", inplace=True)
test["Fence"].fillna("None", inplace=True)
test["MiscFeature"].fillna("None", inplace=True)
test["LotFrontage"].fillna(0, inplace=True)
test["MasVnrType"].fillna("None", inplace=True)
test["MasVnrArea"].fillna(0, inplace=True)
test["Electrical"].fillna("SBrkr", inplace=True)
test["Utilities"].fillna("None", inplace=True)
test = test.replace({"MSSubClass" : {20 : "SC20", 30 : "SC30", 40 : "SC40", 45 : "SC45", 50 : "SC50", 60 : "SC60",
70 : "SC70", 75 : "SC75", 80 : "SC80", 85 : "SC85", 90 : "SC90", 120 : "SC120", 150 : "SC150", 160 : "SC160",
180 : "SC180", 190 : "SC190"},
"MoSold" : {1 : "Jan", 2 : "Feb", 3 : "Mar", 4 : "Apr", 5 : "May", 6 : "Jun", 7 : "Jul", 8 : "Aug", 9 : "Sep",
10 : "Oct", 11 : "Nov", 12 : "Dec"} })
test = test.replace({"Alley" : {"Grvl" : 1, "Pave" : 2},
"BsmtCond" : {"No" : 0, "Po" : 1, "Fa" : 2, "TA" : 3, "Gd" : 4, "Ex" : 5},
"BsmtExposure" : {"No" : 0, "Mn" : 1, "Av": 2, "Gd" : 3},
"BsmtFinType1" : {"No" : 0, "Unf" : 1, "LwQ": 2, "Rec" : 3, "BLQ" : 4, "ALQ" : 5, "GLQ" : 6},
"BsmtFinType2" : {"No" : 0, "Unf" : 1, "LwQ": 2, "Rec" : 3, "BLQ" : 4, "ALQ" : 5, "GLQ" : 6},
"BsmtQual" : {"No" : 0, "Po" : 1, "Fa" : 2, "TA": 3, "Gd" : 4, "Ex" : 5},
"ExterCond" : {"Po" : 1, "Fa" : 2, "TA": 3, "Gd": 4, "Ex" : 5},
"ExterQual" : {"Po" : 1, "Fa" : 2, "TA": 3, "Gd": 4, "Ex" : 5},
"FireplaceQu" : {"No" : 0, "Po" : 1, "Fa" : 2, "TA" : 3, "Gd" : 4, "Ex" : 5},
"Functional" : {"Sal" : 1, "Sev" : 2, "Maj2" : 3, "Maj1" : 4, "Mod": 5, "Min2" : 6, "Min1" : 7, "Typ" : 8},
"GarageCond" : {"None" : 0, "No" : 0, "Po" : 1, "Fa" : 2, "TA" : 3, "Gd" : 4, "Ex" : 5},
"GarageQual" : {"None" : 0, "No" : 0, "Po" : 1, "Fa" : 2, "TA" : 3, "Gd" : 4, "Ex" : 5},
"HeatingQC" : {"Po" : 1, "Fa" : 2, "TA" : 3, "Gd" : 4, "Ex" : 5},
"KitchenQual" : {"Po" : 1, "Fa" : 2, "TA" : 3, "Gd" : 4, "Ex" : 5},
"LandSlope" : {"Sev" : 1, "Mod" : 2, "Gtl" : 3},
"LotShape" : {"IR3" : 1, "IR2" : 2, "IR1" : 3, "Reg" : 4},
"PavedDrive" : {"N" : 0, "P" : 1, "Y" : 2},
"PoolQC" : {"No" : 0, "Fa" : 1, "TA" : 2, "Gd" : 3, "Ex" : 4},
"Street" : {"Grvl" : 1, "Pave" : 2},
"Utilities" : {"None" : 0, "ELO" : 1, "NoSeWa" : 2, "NoSewr" : 3, "AllPub" : 4}})
test["OverallGrade"] = test["OverallQual"] * test["OverallCond"]
test["GarageGrade"] = test["GarageQual"] * test["GarageCond"]
test["ExterGrade"] = test["ExterQual"] * test["ExterCond"]
test["KitchenScore"] = test["KitchenAbvGr"] * test["KitchenQual"]
test["FireplaceScore"] = test["Fireplaces"] * test["FireplaceQu"]
test["GarageScore"] = test["GarageArea"] * test["GarageQual"]
test["PoolScore"] = test["PoolArea"] * test["PoolQC"]
test["TotalBath"] = test["BsmtFullBath"] + test["BsmtHalfBath"]/2 + test["FullBath"] + test["HalfBath"]/2
test["AllSF"] = test["GrLivArea"] + test["TotalBsmtSF"]
test["AllFlrsSF"] = test["1stFlrSF"] + test["2ndFlrSF"]
test["AllPorchSF"] = test["OpenPorchSF"] + test["EnclosedPorch"] + test["3SsnPorch"] + test["ScreenPorch"]
test["AllSF-s2"] = test["AllSF"] ** 2
test["AllSF-Sq"] = np.sqrt(test["AllSF"])
test["OverallQual-s2"] = test["OverallQual"] ** 2
test["OverallQual-Sq"] = np.sqrt(test["OverallQual"])
test["AllFlrsSF-s2"] = test["AllFlrsSF"] ** 2
test["AllFlrsSF-Sq"] = np.sqrt(test["AllFlrsSF"])
test["GrLivArea-s2"] = test["GrLivArea"] ** 2
test["GrLivArea-Sq"] = np.sqrt(test["GrLivArea"])
test["ExterQual-s2"] = test["ExterQual"] ** 2
test["ExterQual-Sq"] = np.sqrt(test["ExterQual"])
test_num = test[numerical_features]
test_cat = test[categorical_features]
test_num.loc[:,skewness.index] = np.log1p(np.asarray(test_num[skewness.index] , dtype=float))
test_cat = pd.get_dummies(test_cat)
test_processed = pd.concat([test_num, test_cat], axis = 1)
test_processed.loc[:, numerical_features] = stdSc.transform(test_processed.loc[:, numerical_features] )<save_to_csv> | dataset = get_validation_dataset()
dataset = dataset.unbatch().batch(20)
batch = iter(dataset ) | Petals to the Metal - Flower Classification on TPU |
10,859,686 | final_train, final_test = X_train.align(test_processed, join='left', axis=1, fill_value=0)
y_test = elasticNet.predict(final_test)
sub = pd.DataFrame()
sub['Id'] = test["Id"]
sub['SalePrice'] = np.expm1(y_test)
sub.to_csv('submission.csv',index=False )<import_modules> | images, labels = next(batch)
probabilities = model.predict(images)
predictions = np.argmax(probabilities, axis=-1)
display_batch_of_images(( images, labels), predictions ) | Petals to the Metal - Flower Classification on TPU |
10,859,686 | import pandas as pd
import tensorflow as tf
import tensorflow_hub as hub
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.layers import Dense, Input, BatchNormalization, Dropout, Concatenate
from tensorflow.keras.models import Model, Sequential
from tensorflow.keras.callbacks import ModelCheckpoint<load_from_csv> | 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 ) | Petals to the Metal - Flower Classification on TPU |
10,859,686 | <define_variables><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 |
14,144,790 | <SOS> metric: macrofscore Kaggle data source: petals-to-the-metal-flower-classification-on-tpu<find_best_params> | !pip install -q efficientnet | 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.