text_plain_output_1.png
from sklearn import preprocessing

from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier, VotingClassifier

from sklearn.model_selection import train_test_split

import pandas as pd

import pickle

dtrain = pd.read_csv('/kaggle/input/spaceship-titanic/train.csv')

dtest = pd.read_csv('/kaggle/input/spaceship-titanic/test.csv')

dtrain.isna().sum()

le = preprocessing.LabelEncoder()
dtrain['VIP'] = le.fit_transform(dtrain['VIP'])
oe = preprocessing.OneHotEncoder(handle_unknown='ignore')
encoder_home = pd.DataFrame(oe.fit_transform(dtrain[['HomePlanet']]).toarray())
encoder_dest = pd.DataFrame(oe.fit_transform(dtrain[['Destination']]).toarray())
dtrain['Earth'] = encoder_home[0]
dtrain['Europa'] = encoder_home[1]
dtrain['Mars'] = encoder_home[2]
dtrain['CANCRI'] = encoder_dest[0]
dtrain['PSO'] = encoder_dest[1]
dtrain['TRAPPIST'] = encoder_dest[2]

median_age = dtrain.Age.median()
dtrain['Age'].fillna(median_age, inplace=True)
median_mall = dtrain.ShoppingMall.median()
dtrain['ShoppingMall'].fillna(median_mall, inplace=True)
median_spa = dtrain.Spa.median()
dtrain['Spa'].fillna(median_spa, inplace=True)
median_vr = dtrain.VRDeck.median()
dtrain['VRDeck'].fillna(median_vr, inplace=True)
median_room = dtrain.RoomService.median()
dtrain['RoomService'].fillna(median_room, inplace=True)
median_vip = dtrain.VIP.median()
dtrain['VIP'].fillna(median_vip, inplace=True)
median_food = dtrain.FoodCourt.median()
dtrain['FoodCourt'].fillna(median_food, inplace=True)

predict = dtrain['Transported']
X = dtrain[['Age', 'Earth', 'Mars', 'Europa', 'ShoppingMall', 'Spa', 'RoomService', 'VRDeck', 'FoodCourt', 'CANCRI', 'TRAPPIST', 'PSO']]
y = predict

def train_model(model_used):
    best = 0
    sum = 0
    counter = 0
    x_train, x_test, y_train, y_test = train_test_split(X, y, test_size=0.3)
    for i in range(10):
        x_train, x_test, y_train, y_test = train_test_split(X, y, test_size=0.3)
        model = model_used
        model.fit(x_train, y_train)
        acc = model.score(x_test, y_test)
        sum += acc
        counter += 1
        if acc > best:
            best = acc
            with open('titanic.pickle', 'wb') as file:
                pickle.dump(model, file)
    with open('titanic.pickle', 'rb') as file:
        model_trained = pickle.load(file)
    return model_trained

modelRF = train_model(RandomForestClassifier(bootstrap=True, random_state=0, n_estimators=20, criterion='entropy'))