Kaggle competition: Anokha AI Adept
df = df.drop(df[df['ingredients'].str.len() < 2].index, axis=0)
 df = df.drop(df[df['ingredients'].str.len() > 30].index, axis=0 )<string_transform>
import keras
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten
from keras.layers import Conv2D, MaxPooling2D, MaxPool2D
from keras.utils import to_categorical
from keras.preprocessing import image
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from keras.utils import to_categorical
from tqdm import tqdm
dfX = df['ingredients'].str.join(' ' ).str.lower()
dfX_test = df_test['ingredients'].str.join(' ' ).str.lower()<categorify>
train = pd.read_csv('/kaggle/input/anokha-ai-adept/train.csv')
 train.head()
train['label'].value_counts().plot.bar()
dfy = df['cuisine']
lbe = LabelEncoder()
y = lbe.fit_transform(dfy.values )<feature_engineering>
train_image = []
for i in tqdm(range(train.shape[0])) :
img = image.load_img('/kaggle/input/anokha-ai-adept/Train/'+train['filename'][i], target_size=(64,64,1), grayscale=True)
 img = image.img_to_array(img)
 img = img/255
train_image.append(img)
 X = np.array(train_image )
tfidf = TfidfVectorizer(stop_words='english')
 X = tfidf.fit_transform(dfX.values)
 X_test = tfidf.transform(dfX_test.values )<choose_model_class>
y=train['label'].values
class_weights = class_weight.compute_class_weight('balanced',np.unique(y),y)
 class_weights = {0:1.4 ,
1: 0.8,
2:1}
clf = SVC(C=100,
kernel='rbf',
degree=3,
gamma=1,
coef0=1,
shrinking=True,
tol=0.001,
probability=False,
cache_size=200,
class_weight=None,
verbose=False,
max_iter=-1,
decision_function_shape=None,
random_state=None)
 clf.fit(X, y )<predict_on_test>
y = to_categorical(y )
y_test = clf.predict(X_test)
 y_pred = lbe.inverse_transform(y_test)
 cross_val_score(clf, X, y, cv=3 )<save_to_csv>
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42, test_size=0.3 )
sub = pd.DataFrame({'id':df_test.index, 'cuisine':y_pred})
 sub.to_csv('cuisine_output.csv', index=False )<import_modules>
model = Sequential()
model.add(Conv2D(256, kernel_size=(3, 3),activation='relu',input_shape=(64,64,1)))
 model.add(Conv2D(128,(3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
 model.add(Conv2D(128,(3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
 model.add(Conv2D(128,(3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
 model.add(Conv2D(128,(3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
 model.add(Dropout(0.2))
model.add(Flatten())
 model.add(Dense(128, activation='relu'))
model.add(Dropout(0.3))
model.add(Dense(3, activation='softmax'))
import json
import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer,CountVectorizer
from sklearn.svm import SVC
from sklearn.multiclass import OneVsRestClassifier
from sklearn.metrics import *
from sklearn.model_selection import GridSearchCV<load_from_disk>
def recall_m(y_true, y_pred):
true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))
 possible_positives = K.sum(K.round(K.clip(y_true, 0, 1)))
 recall = true_positives /(possible_positives + K.epsilon())
 return recall
def precision_m(y_true, y_pred):
true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))
 predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1)))
 precision = true_positives /(predicted_positives + K.epsilon())
 return precision
def f1_m(y_true, y_pred):
precision = precision_m(y_true, y_pred)
 recall = recall_m(y_true, y_pred)
 return 2*(( precision*recall)/(precision+recall+K.epsilon()))
model.compile(loss='categorical_crossentropy',optimizer='rmsprop',metrics=['acc',f1_m,precision_m, recall_m] )
train_data=pd.read_json('.. /input/train.json')
 test_data=pd.read_json('.. /input/test.json' )<categorify>
earlystop = EarlyStopping(restore_best_weights=True )
def preprocess(data):
Mydata=[]
for i in range(len(data['ingredients'])) :
a=" ".join(data['ingredients'][i])
 Mydata.append(a)
 return Mydata
train=preprocess(train_data)
 test=preprocess(test_data )<feature_engineering>
learning_rate_reduction = ReduceLROnPlateau(monitor='val_f1_m',
patience=3,
verbose=1,
factor=0.5,
min_lr=0.00001 )
vect=TfidfVectorizer()
train_TDF=vect.fit_transform(train)
 test_TDF=vect.transform(test )<categorify>
callbacks = [earlystop, learning_rate_reduction]
le=LabelEncoder()
enc_target=le.fit_transform(target)
 enc_target.shape<choose_model_class>
model.fit(X_train, y_train, epochs=45, validation_data=(X_test, y_test), batch_size=16, class_weight=class_weights )
<categorify>
test_file = pd.read_csv('/kaggle/input/anokha-ai-adept/test.csv' )
Y=pd.get_dummies(train_data.cuisine)
 input_data=Y.values<categorify>
test_image = []
for i in tqdm(range(test_file.shape[0])) :
img = image.load_img('/kaggle/input/anokha-ai-adept/Test/'+test_file['filename'][i], target_size=(64,64,1), grayscale=True)
 img = image.img_to_array(img)
 img = img/255
test_image.append(img)
 test = np.array(test_image )
train_TDF.toarray()<normalization>
prediction = model.predict_classes(test )
scaler=MinMaxScaler()
scaler.fit(train_TDF.toarray())
 featuresNN=scaler.transform(train_TDF.toarray() )<split>
sample = pd.read_csv('/kaggle/input/anokha-ai-adept/SampleSolution.csv')
 sample['label'] = prediction
sample.to_csv('sample1.csv', header=True, index=False )