Kaggle competition: PetFinder.my Adoption Prediction
<SOS> metric: QuadraticWeightedKappa Kaggle data source: petfinder.my-adoption-prediction<define_variables>
%matplotlib inline
%config InlineBackend.figure_format = 'svg'
warnings.filterwarnings("ignore")
 plt.rcParams['figure.figsize'] =(12, 9)
 plt.style.use('ggplot')
 pd.options.display.max_rows = 64
pd.options.display.max_columns = 512
pet_ids = train_df['PetID'].values
n_batches = len(pet_ids)// batch_size + 1<define_search_model>
train = pd.read_csv('.. /input/train/train.csv')
 train['AdoptionSpeed'].astype(np.int32)
 test = pd.read_csv('.. /input/test/test.csv')
 df = pd.concat([train,test],ignore_index=True )
inp = Input(( 256,256,3))
backbone = DenseNet121(input_tensor = inp,
weights=".. /input/densenet-keras/DenseNet-BC-121-32-no-top.h5",
include_top = False)
 x = backbone.output
x = GlobalAveragePooling2D()(x)
 x = Lambda(lambda x: K.expand_dims(x,axis = -1))(x)
 x = AveragePooling1D(4 )(x)
 out = Lambda(lambda x: x[:,:,0] )(x)
 m = Model(inp,out )<predict_on_test>
train_sentiment_files = sorted(glob.glob('.. /input/train_sentiment/*.json'))
test_sentiment_files = sorted(glob.glob('.. /input/test_sentiment/*.json'))
sentimental_analysis = train_sentiment_files + test_sentiment_files
features = {}
for b in tqdm_notebook(range(n_batches)) :
start = b*batch_size
end =(b+1)*batch_size
batch_pets = pet_ids[start:end]
batch_images = np.zeros(( len(batch_pets),img_size,img_size,3))
for i,pet_id in enumerate(batch_pets):
try:
batch_images[i] = load_image(".. /input/petfinder-adoption-prediction/train_images/", pet_id)
 except:
pass
batch_preds = m.predict(batch_images)
 for i,pet_id in enumerate(batch_pets):
features[pet_id] = batch_preds[i]<create_dataframe>
score_dict = dict(zip(petid,score))
magnitude_dict = dict(zip(petid,magnitude))
train_feats = pd.DataFrame.from_dict(features, orient='index')
 train_feats.columns = ['pic_'+str(i)for i in range(train_feats.shape[1])]<load_from_csv>
df['Score'] = df['PetID'].map(score_dict)
 df['Score'][df.Score.isnull() ] = 0
df['Magnitude'] = df['PetID'].map(magnitude_dict)
 df['Magnitude'][df.Magnitude.isnull() ] = 0
df.set_index('PetID',inplace=True )
test_df = pd.read_csv('.. /input/petfinder-adoption-prediction/test/test.csv')
 pet_ids = test_df['PetID'].values
n_batches = len(pet_ids)// batch_size + 1
features = {}
for b in tqdm_notebook(range(n_batches)) :
start = b*batch_size
end =(b+1)*batch_size
batch_pets = pet_ids[start:end]
batch_images = np.zeros(( len(batch_pets),img_size,img_size,3))
for i,pet_id in enumerate(batch_pets):
try:
batch_images[i] = load_image(".. /input/petfinder-adoption-prediction/test_images/", pet_id)
 except:
pass
batch_preds = m.predict(batch_images)
 for i,pet_id in enumerate(batch_pets):
features[pet_id] = batch_preds[i]<create_dataframe>
def namevaild(name):
if name == np.nan:
return 0
elif len(str(name)) < 3:
return 1
elif re.match(u'[0-9]', str(name ).lower()):
return 1
elif len(set(str(name ).lower().split(' ')+['no','not','yet','male','female','unnamed'])) != len(set(str(name ).lower().split(' ')))+6:
return 1
else:
return 2
df['Name_state'] = df['Name'].apply(namevaild )
test_feats = pd.DataFrame.from_dict(features, orient='index')
 test_feats.columns = ['pic_'+str(i)for i in range(test_feats.shape[1])]<rename_columns>
df['Fee_per_pet'] = df.Fee/df.Quantity
df['Fee_Bin']=pd.factorize(pd.cut(df.Fee_per_pet,bins=[0,0.01,50,100,200,500,3000],right=False)) [0]
fee_bin_dummies_df = pd.get_dummies(df['Fee_Bin'] ).rename(columns=lambda x: 'Fee_Bin_' + str(x))
df = pd.concat([df, fee_bin_dummies_df], axis=1 )
test_feats = test_feats.reset_index()
test_feats.rename({'index': 'PetID'}, axis='columns', inplace=True)
 train_feats = train_feats.reset_index()
train_feats.rename({'index': 'PetID'}, axis='columns', inplace=True)
 test_feats.head()<load_from_csv>
df['Quantity_Bin']=pd.factorize(pd.cut(df.Quantity,bins=[1,2,4,22],right=False)) [0]
quantity_bin_dummies_df = pd.get_dummies(df['Quantity_Bin'] ).rename(columns=lambda x: 'Quantity_Bin_' + str(x))
df = pd.concat([df, quantity_bin_dummies_df], axis=1 )
print('Train')
 train = pd.read_csv(".. /input/petfinder-adoption-prediction/train/train.csv")
 print(train.shape)
 print('Test')
 test = pd.read_csv(".. /input/petfinder-adoption-prediction/test/test.csv")
 print(test.shape)
 print('Breeds')
 breeds = pd.read_csv(".. /input/petfinder-adoption-prediction/breed_labels.csv")
 print(breeds.shape)
 print('Colors')
 colors = pd.read_csv(".. /input/petfinder-adoption-prediction/color_labels.csv")
 print(colors.shape)
 print('States')
 states = pd.read_csv(".. /input/petfinder-adoption-prediction/state_labels.csv")
 print(states.shape)
 target = train['AdoptionSpeed']
train_id = train['PetID']
test_id = test['PetID']
train = pd.merge(train, train_feats, how='left', on='PetID')
 test = pd.merge(test, test_feats, how='left', on='PetID')
 train.drop(['AdoptionSpeed', 'PetID'], axis=1, inplace=True)
 test.drop(['PetID'], axis=1, inplace=True )<feature_engineering>
df.VideoAmt = df.VideoAmt.apply(lambda x: 1 if x > 0 else 0)
 df['PhotoAmt_Bin']=pd.factorize(pd.cut(df.PhotoAmt,bins=[0,1,2,4,31],right=False)) [0]
photo_bin_dummies_df = pd.get_dummies(df['PhotoAmt_Bin'] ).rename(columns=lambda x: 'PhotoAmt_Bin_' + str(x))
df = pd.concat([df, photo_bin_dummies_df], axis=1 )
doc_sent_mag = []
doc_sent_score = []
nf_count = 0
for pet in train_id:
try:
with open('.. /input/petfinder-adoption-prediction/train_sentiment/' + pet + '.json', 'r')as f:
sentiment = json.load(f)
 doc_sent_mag.append(sentiment['documentSentiment']['magnitude'])
 doc_sent_score.append(sentiment['documentSentiment']['score'])
 except FileNotFoundError:
nf_count += 1
doc_sent_mag.append(-1)
 doc_sent_score.append(-1)
 train.loc[:, 'doc_sent_mag'] = doc_sent_mag
train.loc[:, 'doc_sent_score'] = doc_sent_score
doc_sent_mag = []
doc_sent_score = []
nf_count = 0
for pet in test_id:
try:
with open('.. /input/petfinder-adoption-prediction/test_sentiment/' + pet + '.json', 'r')as f:
sentiment = json.load(f)
 doc_sent_mag.append(sentiment['documentSentiment']['magnitude'])
 doc_sent_score.append(sentiment['documentSentiment']['score'])
 except FileNotFoundError:
nf_count += 1
doc_sent_mag.append(-1)
 doc_sent_score.append(-1)
 test.loc[:, 'doc_sent_mag'] = doc_sent_mag
test.loc[:, 'doc_sent_score'] = doc_sent_score<train_on_grid>
def map_state(state):
if state == 41326:
return 'Selangor'
elif state == 41401:
return 'Kuala_Lumpur'
else:
return 'Other_State'
df['State_Bin'] = df.State.apply(map_state)
 state_bin_dummies_df = pd.get_dummies(df['State_Bin'] ).rename(columns=lambda x: 'State_' + str(x))
df = pd.concat([df, state_bin_dummies_df], axis=1 )
train_desc = train.Description.fillna("none" ).values
test_desc = test.Description.fillna("none" ).values
tfv = TfidfVectorizer(min_df=3, max_features=10000,
strip_accents='unicode', analyzer='word', token_pattern=r'\w{1,}',
ngram_range=(1, 3), use_idf=1, smooth_idf=1, sublinear_tf=1,
stop_words = 'english')
 tfv.fit(list(train_desc))
X = tfv.transform(train_desc)
 X_test = tfv.transform(test_desc)
 print("X(tfidf):", X.shape)
 svd = TruncatedSVD(n_components=200)
 svd.fit(X)
 X = svd.transform(X)
 print("X(svd):", X.shape)
 X = pd.DataFrame(X, columns=['svd_{}'.format(i)for i in range(200)])
 train = pd.concat(( train, X), axis=1)
 X_test = svd.transform(X_test)
 X_test = pd.DataFrame(X_test, columns=['svd_{}'.format(i)for i in range(200)])
 test = pd.concat(( test, X_test), axis=1)
 print("train:", train.shape)
<define_variables>
rescuer_dict = df.RescuerID.value_counts().to_dict()
df['Rescuer_Num'] = df.RescuerID.map(rescuer_dict)
vertex_xs = []
vertex_ys = []
bounding_confidences = []
bounding_importance_fracs = []
dominant_blues = []
dominant_greens = []
dominant_reds = []
dominant_pixel_fracs = []
dominant_scores = []
label_descriptions = []
label_scores = []
nf_count = 0
nl_count = 0
for pet in train_id:
try:
with open('.. /input/petfinder-adoption-prediction/train_metadata/' + pet + '-1.json', 'r')as f:
data = json.load(f)
 vertex_x = data['cropHintsAnnotation']['cropHints'][0]['boundingPoly']['vertices'][2]['x']
vertex_xs.append(vertex_x)
 vertex_y = data['cropHintsAnnotation']['cropHints'][0]['boundingPoly']['vertices'][2]['y']
vertex_ys.append(vertex_y)
 bounding_confidence = data['cropHintsAnnotation']['cropHints'][0]['confidence']
bounding_confidences.append(bounding_confidence)
 bounding_importance_frac = data['cropHintsAnnotation']['cropHints'][0].get('importanceFraction', -1)
 bounding_importance_fracs.append(bounding_importance_frac)
 dominant_blue = data['imagePropertiesAnnotation']['dominantColors']['colors'][0]['color']['blue']
dominant_blues.append(dominant_blue)
 dominant_green = data['imagePropertiesAnnotation']['dominantColors']['colors'][0]['color']['green']
dominant_greens.append(dominant_green)
 dominant_red = data['imagePropertiesAnnotation']['dominantColors']['colors'][0]['color']['red']
dominant_reds.append(dominant_red)
 dominant_pixel_frac = data['imagePropertiesAnnotation']['dominantColors']['colors'][0]['pixelFraction']
dominant_pixel_fracs.append(dominant_pixel_frac)
 dominant_score = data['imagePropertiesAnnotation']['dominantColors']['colors'][0]['score']
dominant_scores.append(dominant_score)
 if data.get('labelAnnotations'):
label_description = data['labelAnnotations'][0]['description']
label_descriptions.append(label_description)
 label_score = data['labelAnnotations'][0]['score']
label_scores.append(label_score)
 else:
nl_count += 1
label_descriptions.append('nothing')
 label_scores.append(-1)
 except FileNotFoundError:
nf_count += 1
vertex_xs.append(-1)
 vertex_ys.append(-1)
 bounding_confidences.append(-1)
 bounding_importance_fracs.append(-1)
 dominant_blues.append(-1)
 dominant_greens.append(-1)
 dominant_reds.append(-1)
 dominant_pixel_fracs.append(-1)
 dominant_scores.append(-1)
 label_descriptions.append('nothing')
 label_scores.append(-1)
 print(nf_count)
 print(nl_count)
 train.loc[:, 'vertex_x'] = vertex_xs
train.loc[:, 'vertex_y'] = vertex_ys
train.loc[:, 'bounding_confidence'] = bounding_confidences
train.loc[:, 'bounding_importance'] = bounding_importance_fracs
train.loc[:, 'dominant_blue'] = dominant_blues
train.loc[:, 'dominant_green'] = dominant_greens
train.loc[:, 'dominant_red'] = dominant_reds
train.loc[:, 'dominant_pixel_frac'] = dominant_pixel_fracs
train.loc[:, 'dominant_score'] = dominant_scores
train.loc[:, 'label_description'] = label_descriptions
train.loc[:, 'label_score'] = label_scores
vertex_xs = []
vertex_ys = []
bounding_confidences = []
bounding_importance_fracs = []
dominant_blues = []
dominant_greens = []
dominant_reds = []
dominant_pixel_fracs = []
dominant_scores = []
label_descriptions = []
label_scores = []
nf_count = 0
nl_count = 0
for pet in test_id:
try:
with open('.. /input/petfinder-adoption-prediction/test_metadata/' + pet + '-1.json', 'r')as f:
data = json.load(f)
 vertex_x = data['cropHintsAnnotation']['cropHints'][0]['boundingPoly']['vertices'][2]['x']
vertex_xs.append(vertex_x)
 vertex_y = data['cropHintsAnnotation']['cropHints'][0]['boundingPoly']['vertices'][2]['y']
vertex_ys.append(vertex_y)
 bounding_confidence = data['cropHintsAnnotation']['cropHints'][0]['confidence']
bounding_confidences.append(bounding_confidence)
 bounding_importance_frac = data['cropHintsAnnotation']['cropHints'][0].get('importanceFraction', -1)
 bounding_importance_fracs.append(bounding_importance_frac)
 dominant_blue = data['imagePropertiesAnnotation']['dominantColors']['colors'][0]['color']['blue']
dominant_blues.append(dominant_blue)
 dominant_green = data['imagePropertiesAnnotation']['dominantColors']['colors'][0]['color']['green']
dominant_greens.append(dominant_green)
 dominant_red = data['imagePropertiesAnnotation']['dominantColors']['colors'][0]['color']['red']
dominant_reds.append(dominant_red)
 dominant_pixel_frac = data['imagePropertiesAnnotation']['dominantColors']['colors'][0]['pixelFraction']
dominant_pixel_fracs.append(dominant_pixel_frac)
 dominant_score = data['imagePropertiesAnnotation']['dominantColors']['colors'][0]['score']
dominant_scores.append(dominant_score)
 if data.get('labelAnnotations'):
label_description = data['labelAnnotations'][0]['description']
label_descriptions.append(label_description)
 label_score = data['labelAnnotations'][0]['score']
label_scores.append(label_score)
 else:
nl_count += 1
label_descriptions.append('nothing')
 label_scores.append(-1)
 except FileNotFoundError:
nf_count += 1
vertex_xs.append(-1)
 vertex_ys.append(-1)
 bounding_confidences.append(-1)
 bounding_importance_fracs.append(-1)
 dominant_blues.append(-1)
 dominant_greens.append(-1)
 dominant_reds.append(-1)
 dominant_pixel_fracs.append(-1)
 dominant_scores.append(-1)
 label_descriptions.append('nothing')
 label_scores.append(-1)
 print(nf_count)
 test.loc[:, 'vertex_x'] = vertex_xs
test.loc[:, 'vertex_y'] = vertex_ys
test.loc[:, 'bounding_confidence'] = bounding_confidences
test.loc[:, 'bounding_importance'] = bounding_importance_fracs
test.loc[:, 'dominant_blue'] = dominant_blues
test.loc[:, 'dominant_green'] = dominant_greens
test.loc[:, 'dominant_red'] = dominant_reds
test.loc[:, 'dominant_pixel_frac'] = dominant_pixel_fracs
test.loc[:, 'dominant_score'] = dominant_scores
test.loc[:, 'label_description'] = label_descriptions
test.loc[:, 'label_score'] = label_scores<drop_column>
breeds = pd.read_csv('.. /input/breed_labels.csv')
 breeds_dict = {k: v for k, v in zip(breeds['BreedID'], breeds['BreedName'])}
df['Breed1_name'] = df['Breed1'].apply(lambda x: '_'.join(breeds_dict[x].split())if x in breeds_dict else 'NA')
 df['Breed2_name'] = df['Breed2'].apply(lambda x: '_'.join(breeds_dict[x].split())if x in breeds_dict else 'NA' )
train.drop(['Name', 'RescuerID', 'Description'], axis=1, inplace=True)
 test.drop(['Name', 'RescuerID', 'Description'], axis=1, inplace=True )<data_type_conversions>
df['Breed'] = df['Breed1_name'] + '--' + df['Breed2_name']
def mix_breed(string):
breed = string.split('--')
 if breed[0] in ['Mixed_Breed','NA']:
return 1
elif breed[1] == 'Mixed_Breed':
return 1
elif breed[1] == 'NA':
return 0
elif breed[0] != breed[1]:
return 1
else:
return 0
df['Mixed_Breed'] = df.Breed.apply(mix_breed )
numeric_cols = ['Age', 'Quantity', 'Fee', 'VideoAmt', 'PhotoAmt', 'AdoptionSpeed',
'doc_sent_mag', 'doc_sent_score', 'dominant_score', 'dominant_pixel_frac',
'dominant_red', 'dominant_green', 'dominant_blue', 'bounding_importance',
'bounding_confidence', 'vertex_x', 'vertex_y', 'label_score'] +\
[col for col in train.columns if col.startswith('pic')or col.startswith('svd')]
cat_cols = list(set(train.columns)- set(numeric_cols))
train.loc[:, cat_cols] = train[cat_cols].astype('category')
 test.loc[:, cat_cols] = test[cat_cols].astype('category')
 print(train.shape)
 print(test.shape)
 foo = train.dtypes
cat_feature_names = foo[foo == "category"]
cat_features = [train.columns.get_loc(c)for c in train.columns if c in cat_feature_names]<drop_column>
train = train.drop('label_description',axis=1)
 test= test.drop('label_description', axis=1 )<define_variables>
df_copy = df.drop(columns=['Description','Fee','Fee_per_pet','Name','PhotoAmt','Quantity','RescuerID','State','State_Bin','Fee_Bin','Quantity_Bin','PhotoAmt_Bin','Breed','Breed1_name','Breed2_name'])
 train = df_copy[df.AdoptionSpeed.notnull() ]
test = df_copy[df.AdoptionSpeed.isnull() ]
print(train.shape, test.shape )
col_vals_dict= {col: list(train[col].unique())for col in train.select_dtypes(['category'])}
embed_cols = []
for c in col_vals_dict:
if len(col_vals_dict[c])>=2:
embed_cols.append(c)
 print(c + ': %d values' % len(col_vals_dict[c]))<import_modules>
X_train = train.drop(columns=['AdoptionSpeed'])
 y_train = train.AdoptionSpeed
X_test = test.drop(columns=['AdoptionSpeed'] )
class CyclicLR(Callback):

 def __init__(self, base_lr=0.001, max_lr=0.006, step_size=2000., mode='triangular',
gamma=1., scale_fn=None, scale_mode='cycle'):
super(CyclicLR, self ).__init__()
self.base_lr = base_lr
self.max_lr = max_lr
self.step_size = step_size
self.mode = mode
self.gamma = gamma
if scale_fn == None:
if self.mode == 'triangular':
self.scale_fn = lambda x: 1.
 self.scale_mode = 'cycle'
elif self.mode == 'triangular2':
self.scale_fn = lambda x: 1/(2.**(x-1))
self.scale_mode = 'cycle'
elif self.mode == 'exp_range':
self.scale_fn = lambda x: gamma**(x)
 self.scale_mode = 'iterations'
else:
self.scale_fn = scale_fn
self.scale_mode = scale_mode
self.clr_iterations = 0.
 self.trn_iterations = 0.
 self.history = {}
self._reset()
def _reset(self, new_base_lr=None, new_max_lr=None,
new_step_size=None):

 if new_base_lr != None:
self.base_lr = new_base_lr
if new_max_lr != None:
self.max_lr = new_max_lr
if new_step_size != None:
self.step_size = new_step_size
self.clr_iterations = 0.
 def clr(self):
cycle = np.floor(1+self.clr_iterations/(2*self.step_size))
x = np.abs(self.clr_iterations/self.step_size - 2*cycle + 1)
 if self.scale_mode == 'cycle':
return self.base_lr +(self.max_lr-self.base_lr)*np.maximum(0,(1-x)) *self.scale_fn(cycle)
 else:
return self.base_lr +(self.max_lr-self.base_lr)*np.maximum(0,(1-x)) *self.scale_fn(self.clr_iterations)
 def on_train_begin(self, logs={}):
logs = logs or {}
if self.clr_iterations == 0:
K.set_value(self.model.optimizer.lr, self.base_lr)
 else:
K.set_value(self.model.optimizer.lr, self.clr())
 def on_batch_end(self, epoch, logs=None):
logs = logs or {}
self.trn_iterations += 1
self.clr_iterations += 1
self.history.setdefault('lr', [] ).append(K.get_value(self.model.optimizer.lr))
self.history.setdefault('iterations', [] ).append(self.trn_iterations)
 for k, v in logs.items() :
self.history.setdefault(k, [] ).append(v)
 K.set_value(self.model.optimizer.lr, self.clr())
 class QWKEvaluation(Callback):
def __init__(self, validation_data=() , interval=1):
super(Callback, self ).__init__()
self.interval = interval
self.history = []
self.X_val, self.y_val = validation_data
def on_epoch_end(self, epoch, logs={}):
if epoch % self.interval == 0:
y_pred = self.model.predict(self.X_val, batch_size=1000, verbose=0)
 y_pred = eval_predict(self.y_val, y_pred)
 score = quadratic_weighted_kappa(self.y_val, y_pred)
 print("QWK - epoch: %d - score: %.6f
" %(epoch+1, score))
self.history.append(score)
 if score >= max(self.history): self.model.save('checkpoint.h5')
 def eval_predict(y=[], y_pred=[], coeffs=None, ret_coeffs=False):
optR = OptimizedRounder()
if not coeffs:
optR.fit(y_pred.reshape(-1,), y)
 coeffs = optR.coefficients()
if ret_coeffs: return optR.coefficients()
return optR.predict(y_pred, coeffs ).reshape(-1, )<set_options>
rf = RandomForestClassifier(n_estimators = 600, max_depth=None, criterion='gini')
 rf.fit(X_train,y_train)
 y_predict = rf.predict(X_test ).astype(np.int32)
 submission = pd.DataFrame({'PetID': test.index, 'AdoptionSpeed': y_predict})
 submission = submission[['PetID','AdoptionSpeed']]
submission.head()
seed = 2019
np.random.seed(seed)
 tf.set_random_seed(seed)
 def get_model(dr=0.15, seed=2019):
np.random.seed(seed)
 tf.set_random_seed(seed)
 sess = tf.Session()
K.set_session(sess)
 inputs = []
embeddings = []
input_type = Input(shape=[1], name='Type')
 embedding = Embedding(2,1, input_length=1 )(input_type)
 embedding = Reshape(target_shape=(1,))(embedding)
 inputs.append(input_type)
 embeddings.append(embedding)
 input_breed1 = Input(shape=[1],name= 'Breed1')
 embedding = Embedding(176,10, input_length=1 )(input_breed1)
 embedding = Reshape(target_shape=(10,))(embedding)
 inputs.append(input_breed1)
 embeddings.append(embedding)
 input_breed2 = Input(shape=[1], name= 'Breed2')
 embedding = Embedding(135,10, input_length=1 )(input_breed2)
 embedding = Reshape(target_shape=(10,))(embedding)
 inputs.append(input_breed2)
 embeddings.append(embedding)
 input_gender = Input(shape=[1], name= 'Gender')
 embedding = Embedding(3,2, input_length=1 )(input_gender)
 embedding = Reshape(target_shape=(2,))(embedding)
 inputs.append(input_gender)
 embeddings.append(embedding)
 input_color1 = Input(shape=[1], name= 'Color1')
 embedding = Embedding(7,4, input_length=1 )(input_color1)
 embedding = Reshape(target_shape=(4,))(embedding)
 inputs.append(input_color1)
 embeddings.append(embedding)
 input_color2 = Input(shape=[1], name= 'Color2')
 embedding = Embedding(7,4, input_length=1 )(input_color2)
 embedding = Reshape(target_shape=(4,))(embedding)
 inputs.append(input_color2)
 embeddings.append(embedding)
 input_color3 = Input(shape=[1], name= 'Color3')
 embedding = Embedding(6,3, input_length=1 )(input_color3)
 embedding = Reshape(target_shape=(3,))(embedding)
 inputs.append(input_color3)
 embeddings.append(embedding)
 input_maturity_size = Input(shape=[1], name= 'MaturitySize')
 embedding = Embedding(4,2, input_length=1 )(input_maturity_size)
 embedding = Reshape(target_shape=(2,))(embedding)
 inputs.append(input_maturity_size)
 embeddings.append(embedding)
 input_fur_length = Input(shape=[1], name= 'FurLength')
 embedding = Embedding(3,2, input_length=1 )(input_fur_length)
 embedding = Reshape(target_shape=(2,))(embedding)
 inputs.append(input_fur_length)
 embeddings.append(embedding)
 input_vaccinated = Input(shape=[1], name= 'Vaccinated')
 embedding = Embedding(3,2, input_length=1 )(input_vaccinated)
 embedding = Reshape(target_shape=(2,))(embedding)
 inputs.append(input_vaccinated)
 embeddings.append(embedding)
 input_dewormed = Input(shape=[1], name='Dewormed')
 embedding = Embedding(3,2, input_length=1 )(input_vaccinated)
 embedding = Reshape(target_shape=(2,))(embedding)
 inputs.append(input_dewormed)
 embeddings.append(embedding)
 input_sterilized = Input(shape=[1], name='Sterilized')
 embedding = Embedding(3,2, input_length=1 )(input_sterilized)
 embedding = Reshape(target_shape=(2,))(embedding)
 inputs.append(input_sterilized)
 embeddings.append(embedding)
 input_health = Input(shape=[1], name='Health')
 embedding = Embedding(3,2, input_length=1 )(input_health)
 embedding = Reshape(target_shape=(2,))(embedding)
 inputs.append(input_health)
 embeddings.append(embedding)
 input_state = Input(shape=[1], name='State')
 embedding = Embedding(14,7, input_length=1 )(input_health)
 embedding = Reshape(target_shape=(7,))(embedding)
 inputs.append(input_state)
 embeddings.append(embedding)
 input_pic = Input(shape=[num_train[pic_cols].shape[1]], name='pic_col')
 bn_pic = BatchNormalization()(input_pic)
 inputs.append(input_pic)
 embeddings.append(bn_pic)
 input_svd = Input(shape=[num_train[svd_cols].shape[1]], name='svd_col')
 bn_svd = BatchNormalization()(input_svd)
 inputs.append(input_svd)
 embeddings.append(bn_svd)
 input_meta = Input(shape=[num_train[meta_cols].shape[1]], name='meta_col')
 bn_meta = BatchNormalization()(input_meta)
 inputs.append(input_meta)
 embeddings.append(bn_meta)
 input_sent = Input(shape=[num_train[sent_cols].shape[1]], name='sent_col')
 bn_sent = BatchNormalization()(input_sent)
 inputs.append(input_sent)
 embeddings.append(bn_sent)
 input_other = Input(shape=[num_train[othernum_cols].shape[1]], name='other_col')
 bn_other = BatchNormalization()(input_other)
 inputs.append(input_other)
 embeddings.append(bn_other)
 main_l= Concatenate()(embeddings)
 main_l = BatchNormalization()(main_l)
 main_l= Dropout(dr )(Dense(250, activation = 'relu' )(main_l))
main_l= Dropout(dr )(Dense(100, activation = 'relu' )(main_l))
main_l = Dense(50, activation='relu' )(main_l)
 main_l= Dense(10, activation = 'relu' )(main_l)
 output = Dense(1, activation = 'linear' )(main_l)
 model = Model(inputs, output)
 optimizer= optimizers.Adam()
model.compile(loss='logcosh', optimizer=optimizer)
 return model, sess 
<categorify>
submission.to_csv('submission.csv', index=False )
<train_on_grid><EOS> 
submission.to_csv('submission.csv', index=False )