# This Python 3 environment comes with many helpful analytics libraries installed
# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python
# For example, here's several helpful packages to load

import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)

# Input data files are available in the read-only "../input/" directory
# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory

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

# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using "Save & Run All" 
# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session
import plotly.express as px
"""
<font color="blue">
 Random forest is a type of ensemble algorithm which means that it includes more than one algorithm and puts them together in order to make more powerful work.
"""
train=pd.read_csv("../input/titanic/train.csv")
train
test=pd.read_csv("../input/titanic/test.csv")
test
fig = px.scatter_3d(train, x='Pclass', y='Sex', z='Survived',
                    color='Survived')
fig.show()
train.isnull().sum()
test.isnull().sum()
import matplotlib.pyplot as plt
import seaborn as sns
plt.figure(figsize=(15,10))
sns.heatmap(train.isnull(),cmap="plasma")
plt.figure(figsize=(15,10))
sns.heatmap(train.isnull(),cmap="plasma")
train["Age"].fillna(train["Age"].mean())
plt.figure(figsize=(15,10))
sns.boxplot(x="Pclass",y="Age",data=train)
train["Age"].mean()
def age_mean(col):
    Age=col[0]
    Pclass=col[1]
    if pd.isnull(Age):
        
        if Pclass==1:
            return 38
        elif Pclass ==2:
            return 29
        else:
            return 25
    else:
        return Age
train["Age"]=train[["Age","Pclass"]].apply(age_mean,axis=1)
train["Age"]
plt.figure(figsize=(15,10))
sns.heatmap(train.isnull(),cmap="plasma")
train.drop("Cabin",axis=1,inplace=True)
plt.figure(figsize=(15,10))
sns.heatmap(train.isnull(),cmap="plasma")
train.isnull().sum()
train["Embarked"].value_counts()
train["Embarked"].fillna(value="S",inplace=True)
train.isnull().sum()
test.isnull().sum()
test["Age"]=test[["Age","Pclass"]].apply(age_mean,axis=1)
test["Age"]
test.isnull().sum()
test.drop("Cabin",axis=1,inplace=True)
test.isnull().sum()
test["Fare"].fillna(value=test["Fare"].mean(),inplace=True)
test.isnull().sum()
train.drop(["PassengerId","Name","Ticket"],axis=1,inplace=True)
train
passenger_id=test["PassengerId"]
"""
Exploratory Data Analysis
"""
sns.set_style("darkgrid")#Set the aesthetic style of the plots like darkgrid, whitegrid, dark, white, ticks
plt.figure(figsize=(15,10))
sns.countplot(train["Survived"],hue="Sex",data=train,palette="RdBu_r")
sns.set_style("darkgrid")#Set the aesthetic style of the plots like darkgrid, whitegrid, dark, white, ticks
plt.figure(figsize=(15,10))
sns.countplot(train["Survived"],hue="Pclass",data=train,palette="RdBu_r")
test=test.drop(["PassengerId","Name","Ticket"],axis=1)
test

train=pd.get_dummies(data=train,columns=["Sex","Embarked"],drop_first=True)
train
test=pd.get_dummies(data=test,columns=["Sex","Embarked"],drop_first=True)
test
train
X_train=train.drop("Survived",axis=1)
X_train
X_train
y_train=train["Survived"]
y_train
test
from sklearn.ensemble import RandomForestClassifier
forest=RandomForestClassifier(n_estimators=7)
forest.fit(X_train,y_train)
predictions=forest.predict(test)
predictions
output = pd.DataFrame({'PassengerId': passenger_id, 'Survived': predictions})
output.to_csv('my_submission.csv', index=False)