gpt-3.5-turbo-0613· OpenAI
WildChat-4.8M (AI2)
Take a titanic data set from Kaggle and do machine learning codes on it
- User
Take a titanic data set from Kaggle and do machine learning codes on it
- Assistant
Sure! Here's a step-by-step guide on how to perform machine learning on a Titanic dataset from Kaggle.
- 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- Load the dataset:
df = pd.read_csv('titanic_dataset.csv')- 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- 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'])- 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)- Train a Random Forest Classifier:
rf = RandomForestClassifier() rf.fit(X_train, y_train)- 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.