"""
# Introduction

###  Every drug is a biological molecule(protein,lipid etc.) whenever it enters in any body it need to go through various processes and it is called pharmacokinetics.There is four major steps.
 
### **1.Adsorption-** In this step the molecule get absorbed in the blood stream.If it is oral then it is absorbed in the abdominal region.If it is injected in blood it directly in the blood stream.

### **2.Distribution-** Every disease have a special pathogen or target.In case of antibiotic it is the pathogen and the drug molecule get adhere to pathogen cells.

### **3.Metabolism-** Now the molecule introduced in the metabolism cycles and starts its action.

### **4.Excretion-** Now its also important for the molecule to get out of the body so in order to minimize side effect on body.

### Through out this all processes the drug molecule need to interect with different molecules and there are various factors that defines the mechanism of action of the drug.

### The motivation of this competition is to find the mechanism of action of the drug through its whole life inside the body with the help of different factors and that we are going to predict as targets.These targets are nothing but chemical properties of these molecules.The features includes the gene expression data and cell viability.
"""
"""
# Libraries
"""
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
from tensorflow.keras.models import Sequential
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.layers import Activation,Dense,Dropout,BatchNormalization,Input
from tensorflow.keras.metrics import Recall,Precision
from sklearn.model_selection import train_test_split
import numpy as np # linear algebra
import pandas as pd # data processing
tf.random.set_seed(0)

import os
for dirname, _, filenames in os.walk('/kaggle/input'):
    for filename in filenames:
        print(os.path.join(dirname, filename))

"""
# Data
### Now lets talk about the csv files that are provided.The train_features.csv file contain 875 features that will be used in training the data.Next test_features.csv file has the test data that is going to be used in prediction.Third csv file contains optional data.The train_targets_scored.csv contains 206 target columns for the training feature data.
### So we have two different csv first have features and second contains targets.
"""
X =pd.read_csv('/kaggle/input/lish-moa/train_features.csv')
test=pd.read_csv('/kaggle/input/lish-moa/test_features.csv')
pd.read_csv('/kaggle/input/lish-moa/train_targets_nonscored.csv')
y =pd.read_csv('/kaggle/input/lish-moa/train_targets_scored.csv')
sample_submission=pd.read_csv('/kaggle/input/lish-moa/sample_submission.csv')
from sklearn.preprocessing import LabelEncoder
X = X.iloc[: , 1: ].values
y = y.iloc[:,1:].values
le = LabelEncoder()
X[:,2] = le.fit_transform(X[:,2])
le = LabelEncoder()
X[:,0] = le.fit_transform(X[:,0])
print(X)
"""
# Model
"""
"""
### I use holdout validation we can also go with kfold.
"""
X_train, X_val, y_train, y_val = train_test_split(X, y, test_size = 0.12)
model = Sequential([
    
    Input(X_train.shape[1]),
    layers.BatchNormalization(),
    Dropout(0.3),
    Dense(512, activation=tf.nn.leaky_relu),
    layers.BatchNormalization(),
    layers.Dropout(0.4),
    Dense(256, activation=tf.nn.leaky_relu),
    layers.BatchNormalization(),
    layers.Dropout(0.4),
    #Dense(206, activation="relu"),
    #layers.BatchNormalization(),
    #layers.Dropout(0.5),
    Dense(y_train.shape[1], activation ="sigmoid")
    
    
])
model.compile(
    optimizer=Adam(learning_rate=0.0075),
    loss='binary_crossentropy',
    metrics=['Recall','Precision']
)
model.summary()
def func(arg):
    
    arg = tf.convert_to_tensor(arg, dtype=tf.float32)
    return arg
"""
# Training
"""
"""
### Here I am using callback technique that is used to stop the training the model as per requirement.We can stop on the basis of loss ,val_loss,accuracy,Validation accuracy. 
"""
class mycallback(tf.keras.callbacks.Callback):
    def on_epoch_end(self,epoch,logs={}):
        if (logs.get('loss')<=0.0152):
            self.model.stop_training=True
callback= mycallback()
history=model.fit(func(X_train),func(y_train) , verbose=2, epochs=200, 
         validation_data=(func(X_val),func(y_val)),batch_size=32768,callbacks=[callback])
import matplotlib.pyplot as plt
plt.figure(figsize=(25,10))
plt.plot(history.history['recall'])  
plt.plot(history.history['val_recall'])
plt.title('model recall')  
plt.ylabel('recall')  
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.figure(figsize=(25,10))
plt.plot(history.history['loss'])  
plt.plot(history.history['val_loss'])
plt.title('model loss')  
plt.ylabel('loss')  
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.figure(figsize=(25,10))
plt.plot(history.history['precision'])  
plt.plot(history.history['val_precision'])
plt.title('model precison')  
plt.ylabel('loss')  
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
X_final = test.iloc[: , 1: ].values
le = LabelEncoder()
X_final[:,2] = le.fit_transform(X_final[:,2])
le = LabelEncoder()
X_final[:,0] = le.fit_transform(X_final[:,0])
print(X_final)
y_pred = model.predict(func(X_final))

columns = list(sample_submission.columns)
columns.remove('sig_id')

for i in range(len(columns)):
    sample_submission[columns[i]] = y_pred[:, i]

sample_submission.to_csv('submission.csv', index=False)
"""
# Thanks for your time. Please upvote if you like this,I will really appreciate it.
# Any critisism will be appreciated feel free to comment.Love to get improvement tips.
"""