text_plain_output_1.png
from sklearn.cross_validation import KFold

from sklearn.linear_model import LinearRegression

import numpy as np # linear algebra

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

titanic_train = pd.read_csv('../input/train.csv')

titanic_train['Age'].fillna(titanic_train['Age'].median(), inplace=True)
titanic_train['Embarked'].fillna('S', inplace=True)

titanic_train['Sex'].replace({'male': 0, 'female': 1}, inplace=True)
titanic_train['Embarked'].replace({'S': 0, 'C': 1, 'Q': 2}, inplace=True)

from sklearn.linear_model import LinearRegression
from sklearn.cross_validation import KFold
predictors = ['Pclass', 'Sex', 'Age', 'SibSp', 'Parch', 'Fare', 'Embarked']
algo = LinearRegression()
kf = KFold(titanic_train.shape[0], n_folds=3, random_state=1)
predictions = []
for train, test in kf:
    train_predictors = titanic_train[predictors].iloc[train, :]
    train_target = titanic_train['Survived'].iloc[train]
    algo.fit(train_predictors, train_target)
    test_prediction = algo.predict(titanic_train[predictors].iloc[test, :])
    predictions.append(test_prediction)
predictions

accuracy = sum([1 if x == True else 0 for x in titanic_train['Survived'] == [1 if p > 0.5 else 0 for p in np.concatenate(predictions, axis=0)]]) / len(titanic_train)
accuracy