Kaggle competition: What's Cooking? (Kernels Only)
<SOS> metric: CategorizationAccuracy Kaggle data source: whats-cooking?-(kernels-only)<data_type_conversions>
import json
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from collections import Counter
from sklearn.preprocessing import LabelEncoder
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.svm import SVC
from sklearn.ensemble import RandomForestClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn.linear_model import Perceptron
from sklearn.multiclass import OneVsRestClassifier
<prepare_x_and_y>
data = pd.read_json('.. /input/train.json')
 data.head()
def dropout(image, DIM=256, PROBABILITY = 0.75, CT = 8, SZ = 0.2):
P = tf.cast(tf.random.uniform([],0,1)<PROBABILITY, tf.int32)
 if(P==0)|(CT==0)|(SZ==0): return image
for k in range(CT):
x = tf.cast(tf.random.uniform([],0,DIM),tf.int32)
 y = tf.cast(tf.random.uniform([],0,DIM),tf.int32)
 WIDTH = tf.cast(SZ*DIM,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[ya:yb,0:xa,:]
two = tf.zeros([yb-ya,xb-xa,3])
 three = image[ya:yb,xb:DIM,:]
middle = tf.concat([one,two,three],axis=1)
 image = tf.concat([image[0:ya,:,:],middle,image[yb:DIM,:,:]],axis=0)
 image = tf.reshape(image,[DIM,DIM,3])
 return image<normalization>
n = 6714
frame= pd.DataFrame(Counter([i for sublist in data.ingredients for i in sublist] ).most_common(n))
frame = frame.head(10)
 frame
ROT_ = 180.0
SHR_ = 2.0
HZOOM_ = 8.0
WZOOM_ = 8.0
HSHIFT_ = 8.0
WSHIFT_ = 8.0
def get_mat(rotation, shear, height_zoom, width_zoom, height_shift, width_shift):
rotation = math.pi * rotation / 180.
 shear = math.pi * shear / 180.
 def get_3x3_mat(lst):
return tf.reshape(tf.concat([lst],axis=0), [3,3])
 c1 = tf.math.cos(rotation)
 s1 = tf.math.sin(rotation)
 one = tf.constant([1],dtype='float32')
 zero = tf.constant([0],dtype='float32')
 rotation_matrix = get_3x3_mat([c1, s1, zero,
-s1, c1, zero,
zero, zero, one])
 c2 = tf.math.cos(shear)
 s2 = tf.math.sin(shear)
 shear_matrix = get_3x3_mat([one, s2, zero,
zero, c2, zero,
zero, zero, one])
 zoom_matrix = get_3x3_mat([one/height_zoom, zero, zero,
zero, one/width_zoom, zero,
zero, zero, one])
 shift_matrix = get_3x3_mat([one, zero, height_shift,
zero, one, width_shift,
zero, zero, one])
 return K.dot(K.dot(rotation_matrix, shear_matrix),
K.dot(zoom_matrix, shift_matrix))
def transform(image, DIM=256):
XDIM = DIM%2
rot = ROT_ * tf.random.normal([1], dtype='float32')
 shr = SHR_ * tf.random.normal([1], dtype='float32')
 h_zoom = 1.0 + tf.random.normal([1], dtype='float32')/ HZOOM_
w_zoom = 1.0 + tf.random.normal([1], dtype='float32')/ WZOOM_
h_shift = HSHIFT_ * tf.random.normal([1], dtype='float32')
 w_shift = WSHIFT_ * 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])
 def data_augment(data, label):
img = data['inp1']
img = transform(img,DIM=dim)
 if DROPOUT :
img = dropout(img, DIM=dim, PROBABILITY=droprate, CT=dropct, SZ=dropsize)
 img = tf.image.random_flip_left_right(img)
 img = tf.image.random_saturation(img, 0.7, 1.3)
 img = tf.image.random_contrast(img, 0.8, 1.2)
 img = tf.image.random_brightness(img, 0.1)
 img = tf.reshape(img, [dim,dim, 3])
 data['inp1'] = img
return data, label
def data_augment_test(data , label = 0):
img = data['inp1']
img = transform(img,DIM=dim)
 if DROPOUT :
img = dropout(img, DIM=dim, PROBABILITY=droprate, CT=dropct, SZ=dropsize)
 img = tf.image.random_flip_left_right(img)
 img = tf.image.random_saturation(img, 0.7, 1.3)
 img = tf.image.random_contrast(img, 0.8, 1.2)
 img = tf.image.random_brightness(img, 0.1)
 img = tf.reshape(img, [dim,dim, 3])
 data['inp1'] = img
return data , 0<init_hyperparams>
train = json.load(open('.. /input/train.json'))
test = json.load(open('.. /input/test.json'))
train_doc = [" ".join(doc['ingredients'] ).lower() for doc in train]
test_doc = [" ".join(doc['ingredients'] ).lower() for doc in test]
y_train = [doc['cuisine'] for doc in train]
lb = LabelEncoder()
y_train = lb.fit_transform(y_train)
 y_train
LR_START = 0.000005
LR_MAX = 0.00000725 * strategy.num_replicas_in_sync
LR_MIN = 0.000005
LR_RAMPUP_EPOCHS = 5
LR_SUSTAIN_EPOCHS = 4
LR_EXP_DECAY =.8
def lrfn(epoch):
if epoch < LR_RAMPUP_EPOCHS:
lr =(LR_MAX - LR_START)/ LR_RAMPUP_EPOCHS * epoch + LR_START
elif epoch < LR_RAMPUP_EPOCHS + LR_SUSTAIN_EPOCHS:
lr = LR_MAX
else:
lr =(LR_MAX - LR_MIN)* LR_EXP_DECAY**(epoch - LR_RAMPUP_EPOCHS - LR_SUSTAIN_EPOCHS)+ LR_MIN
return lr
lr_callback = tf.keras.callbacks.LearningRateScheduler(lrfn, verbose = True)
 rng = [i for i in range(EPOCHS)]
y = [lrfn(x)for x in rng]
plt.plot(rng, y)
 print("Learning rate schedule: {:.3g} to {:.3g} to {:.3g}".format(y[0], max(y), y[-1]))<normalization>
tfidf = TfidfVectorizer(binary=True)
 X_train = tfidf.fit_transform(train_doc)
 X_test = tfidf.transform(test_doc)
 X_train
train['target'].values
class_weights = class_weight.compute_class_weight(class_weight='balanced',
classes=np.unique(train['target'].values),
y=train['target'].values, 
)
 class_weights = {i : class_weights[i] for i in range(len(class_weights)) }
print(class_weights )<define_variables>
svc = SVC(C=100, gamma=0.9, coef0=1, tol=0.001, decision_function_shape=None)
 model_svc = OneVsRestClassifier(svc, n_jobs=1)
 model_svc.fit(X_train, y_train )
if ANATOM :
tab_feats=[
'sex',
'age_approx',
'anatom_site_general_challenge0',
'anatom_site_general_challenge1',
'anatom_site_general_challenge2',
'anatom_site_general_challenge3',
'anatom_site_general_challenge4',
'anatom_site_general_challenge5',
'anatom_site_general_challenge6'
]
else :
tab_feats=[
'sex',
'age_approx',
]
N_TAB_FEATS=len(tab_feats)
 print(f"The number of tabular features is {N_TAB_FEATS}." )<choose_model_class>
%time
EFNS = [efn.EfficientNetB0, efn.EfficientNetB1, efn.EfficientNetB2, efn.EfficientNetB3,
efn.EfficientNetB4, efn.EfficientNetB5, efn.EfficientNetB6]
def get_model() :
with strategy.scope() :
pretrained_model = EFNS[ef](input_shape=(*IMAGE_SIZE, 3),
weights='imagenet',
include_top=False 
)
 pretrained_model.trainable = True
inp1 = tf.keras.layers.Input(shape=(*IMAGE_SIZE, 3), name='inp1')
 inp2 = tf.keras.layers.Input(shape=(N_TAB_FEATS), name='inp2')
 x=pretrained_model(inp1)
 x=tf.keras.layers.GlobalAveragePooling2D()(x)
 x=tf.keras.layers.Dense(512,
kernel_regularizer=tf.keras.regularizers.l2(l=0.01),
activation='relu' )(x)
 x=tf.keras.layers.Dropout(0.2 )(x)
 x=tf.keras.layers.Dense(256,
kernel_regularizer=tf.keras.regularizers.l2(l=0.01),
activation='relu' )(x)
 x=tf.keras.layers.Dropout(0.2 )(x)
 x=tf.keras.layers.Dense(128,
kernel_regularizer=tf.keras.regularizers.l2(l=0.01),
activation='relu' )(x)
 x=tf.keras.layers.Dropout(0.2 )(x)
 x=tf.keras.layers.Dense(64, kernel_regularizer=tf.keras.regularizers.l2(l=0.01),
activation='relu' )(x)
 x=tf.keras.layers.Dropout(0.2 )(x)
 y=tf.keras.layers.Dense(100,
kernel_regularizer=tf.keras.regularizers.l2(l=0.01),
activation='relu' )(inp2)
 concat=tf.keras.layers.concatenate([y, x])
 output = tf.keras.layers.Dense(1, activation='sigmoid', name='output' )(concat)
 model = tf.keras.models.Model(inputs=[inp1,inp2], outputs=[output])
 model.compile(
 optimizer='adam',
loss = 'binary_crossentropy',
metrics=[tf.keras.metrics.AUC() ], 
)
 return model<define_variables>
y_test = model_svc.predict(X_test)
 print(y_test)
 y_pred = lb.inverse_transform(y_test)
 print(y_pred)
 test_id = [doc['id'] for doc in test]
sub = pd.DataFrame({'id': test_id, 'cuisine': y_pred}, columns=['id', 'cuisine'])
 sub.to_csv('svm_output.csv', index=False )
<find_best_params><EOS> 
test_id = [doc['id'] for doc in test]
sub = pd.DataFrame({'id': test_id, 'cuisine': y_pred}, columns=['id', 'cuisine'])
 sub.to_csv('svm_output.csv', index=False )