Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0613· OpenAIAi2 WildChat-4.8M (AI2)

Take a titanic data set from Kaggle and do machine learning codes on it

  1. User

    Take a titanic data set from Kaggle and do machine learning codes on it

  2. Assistant

    Sure! Here's a step-by-step guide on how to perform machine learning on a Titanic dataset from Kaggle.

    1. Import the necessary libraries:
    import pandas as pd
    import numpy as np
    import seaborn as sns
    from sklearn.model_selection import train_test_split
    from sklearn.preprocessing import LabelEncoder
    from sklearn.ensemble import RandomForestClassifier
    from sklearn.metrics import accuracy_score
    
    1. Load the dataset:
    df = pd.read_csv('titanic_dataset.csv')
    
    1. Perform exploratory data analysis:
    print(df.head())          # Display the first few rows of the dataset
    print(df.describe())      # Summary statistics of the dataset
    print(df.isnull().sum())  # Check for missing values
    
    1. Preprocess the data:
    df = df.dropna(subset=['Age', 'Embarked'])  # Drop rows with missing values in Age and Embarked columns
    df = df[['Survived', 'Pclass', 'Sex', 'Age', 'Fare', 'Embarked']]  # Select relevant columns
    
    # Convert categorical variables to numerical
    le = LabelEncoder()
    df['Sex'] = le.fit_transform(df['Sex'])
    df['Embarked'] = le.fit_transform(df['Embarked'])
    
    1. Split the dataset into training and testing sets:
    X = df.drop('Survived', axis=1)
    y = df['Survived']
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
    
    1. Train a Random Forest Classifier:
    rf = RandomForestClassifier()
    rf.fit(X_train, y_train)
    
    1. Make predictions on the test set and evaluate the model:
    y_pred = rf.predict(X_test)
    accuracy = accuracy_score(y_test, y_pred)
    print('Accuracy:', accuracy)
    

    That's it! You have successfully performed machine learning on the Titanic dataset using a Random Forest Classifier. Feel free to tune the model parameters and explore different algorithms for further improvement.