text_plain_output_1.png
from sklearn.ensemble import RandomForestClassifier

import numpy as np

import pandas as pd

import numpy as np
import pandas as pd
import csv
from sklearn.ensemble import RandomForestClassifier
def munge_data(df):
    """fill in missing values and convert characters to numerical"""
    df['Sex'] = df['Sex'].map({'female': 0, 'male': 1}).astype(int)
    median_ages = np.zeros((2, 3))
    for i in range(0, 2):
        for j in range(0, 3):
            median_ages[i, j] = df[(df['Sex'] == i) & (df['Pclass'] == j + 1)]['Age'].dropna().median()
    for i in range(0, 2):
        for j in range(0, 3):
            df.loc[df.Age.isnull() & (df.Sex == i) & (df.Pclass == j + 1), 'Age'] = median_ages[i, j]
    df['Embarked'] = df['Embarked'].dropna().map({'C': 1, 'S': 2, 'Q': 3}).astype(int)
    mode = df['Embarked'].dropna().mode().astype(int)
    df['Embarked'] = df['Embarked'].fillna(mode)
    df = df.drop(['PassengerId', 'Name', 'Ticket', 'Cabin'], axis=1)
    return df.fillna(0)
train_df = pd.read_csv('../input/train.csv', header=0)
test_df = pd.read_csv('../input/test.csv', header=0)
ids = test_df['PassengerId'].values
train_df = munge_data(train_df)
test_df = munge_data(test_df)
train_data = train_df.values
test_data = test_df.values
print('Training...')
rf = RandomForestClassifier(n_estimators=100)
rf = rf.fit(train_data[0:, 1:], train_data[0:, 0])
print('Accuracy = ', (rf.predict(train_data[0:, 1:]) == train_data[0:, 0]).mean())