0% found this document useful (0 votes)
6 views4 pages

Data Science Coding Notes and EDA

All coding related to data science

Uploaded by

Saman
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views4 pages

Data Science Coding Notes and EDA

All coding related to data science

Uploaded by

Saman
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Coding Notes Data Science

pd.read_csv
import pandas as pd

# reading csv file


df = pd.read_csv("[Link]")
df
pd.read_excel
pip install pandas
pip install xlrd
import pandas as pd
df = pd.read_excel("[Link]")
print(df)
pd.read_sql
# import the modules
import pandas as pd
from sqlalchemy import create_engine

# SQLAlchemy connectable
cnx = create_engine('sqlite:///[Link] ').connect()

# table named 'contacts' will be returned as a dataframe.


df = pd.read_sql_table('contacts', cnx)
print(df)
pd.read_table
# importing pandas
import pandas as pd

pd.read_table('[Link]', delimiter=',')
Clean a real world messy dataset (eg: Kaggle)
# modules we'll use
import pandas as pd
import numpy as np

# read in all our data


nfl_data = pd.read_csv("../input/nflplaybyplay2009to2016/NFL Play by Play 2009-2017 (v4).csv")

# set seed for reproducibility


[Link](0)
# look at the first five rows of the nfl_data file.
# I can see a handful of missing data already!
nfl_data.head()
# get the number of missing data points per column
missing_values_count = nfl_data.isnull().sum()

# look at the # of missing points in the first ten columns


missing_values_count[0:10]
# how many total missing values do we have?
total_cells = [Link](nfl_data.shape)
total_missing = missing_values_count.sum()

# percent of data that is missing


percent_missing = (total_missing/total_cells) * 100
print(percent_missing)
# look at the # of missing points in the first ten columns
missing_values_count[0:10]
# remove all the rows that contain a missing value
nfl_data.dropna()
# remove all columns with at least one missing value
columns_with_na_dropped = nfl_data.dropna(axis=1)
columns_with_na_dropped.head()
# just how much data did we lose?
print("Columns in original dataset: %d \n" % nfl_data.shape[1])
print("Columns with na's dropped: %d" % columns_with_na_dropped.shape[1])
# get a small subset of the NFL dataset
subset_nfl_data = nfl_data.loc[:, 'EPA':'Season'].head()
subset_nfl_data
# replace all NA's with 0
subset_nfl_data.fillna(0)
# replace all NA's the value that comes directly after it in the same column,
# then replace all the remaining na's with 0
subset_nfl_data.fillna(method='bfill', axis=0).fillna(0)
Apply EDA on a student performance dataset
# This Python 3 environment comes with many helpful analytics libraries installed
# It is defined by the kaggle/python docker image: [Link]
# For example, here's several helpful packages to load in

import numpy as np # linear algebra


import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
import [Link] as plt
import seaborn as sns
df=pd.read_csv('/kaggle/input/students-performance-in-exams/
[Link]')
[Link]()
[Link]()
[Link]
[Link]().sum() #checks if there are any missing values
Lets start with plotting graphs
[Link]['[Link]'] = (20, 10)
[Link](df['math score'], palette = 'dark')
[Link]('Math Score',fontsize = 20)
[Link]()
To analyse the data in more deeper way, lets few new columns: Total marks, Percentage and Grades.

df['total marks']=df['math score']+df['reading score']+df['writing score']


df['percentage']=df['total marks']/300*100
#Assigning the grades

def determine_grade(scores):
if scores >= 85 and scores <= 100:
return 'Grade A'
elif scores >= 70 and scores < 85:
return 'Grade B'
elif scores >= 55 and scores < 70:
return 'Grade C'
elif scores >= 35 and scores < 55:
return 'Grade D'
elif scores >= 0 and scores < 35:
return 'Grade E'

df['grades']=df['percentage'].apply(determine_grade)
[Link]()
df['grades'].value_counts().[Link](autopct="%1.1f%%")
[Link]()
Implementation of Linear Regression Model
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from [Link] import mean_squared_error

# Sample data (replace with your actual data)


X = [Link]([[1], [2], [3], [4], [5]]) # Independent variable (features)
y = [Link]([2, 4, 5, 4, 5]) # Dependent variable (target)

# Split data into training and testing sets


X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# Create a linear regression model


model = LinearRegression()

# Train the model using the training data


[Link](X_train, y_train)

# Make predictions on the test data


y_pred = [Link](X_test)

# Evaluate the model


mse = mean_squared_error(y_test, y_pred)
print(f"Mean Squared Error: {mse}")

# Print the coefficients


print(f"Intercept: {model.intercept_}")
print(f"Coefficient: {model.coef_}")

Implementation of Random Forest Model


from [Link] import RandomForestClassifier
from sklearn.model_selection import train_test_split
from [Link] import accuracy_score
import pandas as pd

# Load the data (replace 'your_data.csv' with your actual file)


data = pd.read_csv('your_data.csv')

# Separate features (X) and target (y)


X = [Link]('target_column_name', axis=1) # Replace 'target_column_name'
y = data['target_column_name']

# Split data into training and testing sets


X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# Create a Random Forest Classifier model


model = RandomForestClassifier(n_estimators=100, random_state=42)
# n_estimators is the number of trees in the forest

# Train the model


[Link](X_train, y_train)

# Make predictions on the test set


y_pred = [Link](X_test)

# Evaluate the model


accuracy = accuracy_score(y_test, y_pred)
print(f"Accuracy: {accuracy}")

Common questions

Powered by AI

Visualizations, such as count plots or pie charts, help in understanding the distribution and proportions of different features in a dataset . They can reveal patterns, outliers, or skewness in the data which might not be otherwise obvious. However, they are limited by the level of detail they can show and might oversimplify complex relationships or depend heavily on the choice of variables to display. They can also be misleading if not properly labeled or scaled .

The Mean Squared Error (MSE) is a key metric in evaluating the performance of a linear regression model as it quantifies the average of the squares of the errors between the observed and predicted values . A lower MSE indicates a model that is better fitted to the data, as it signifies smaller discrepancies between predictions and actual values. However, MSE can be sensitive to outliers, which might disproportionately affect its value .

Dropping data with 'NA' values can introduce bias as it reduces the dataset's size, possibly disproportionately affecting certain subsets of data more than others . Important patterns inherent in the missing values themselves might be discarded. Additionally, dropping many data points might lead to lost diversity and poorer generalization of the machine learning model .

Splitting a dataset into training and testing sets allows a machine learning model to learn from one subset and be evaluated on another, which it has not seen before. This ensures that the model's ability to generalize to new, unseen data is tested, thereby providing a more accurate measure of its performance . By using a separate testing set, we prevent the model from simply memorizing the training data (overfitting) and test its robustness across different scenarios .

Implementing a Random Forest Classifier involves loading the dataset, separating features and the target, splitting the data into training and testing sets, creating and training the model, making predictions, and evaluating accuracy . Being an ensemble method, the Random Forest creates multiple decision trees and merges them to obtain a more accurate and stable prediction. Its accuracy is evaluated by comparing the predicted results with the actual test data .

Common methods to handle missing data include removing rows or columns with missing values, and replacing missing values with specific values or strategies. Removing rows or columns with missing values can lead to loss of valuable data, especially if the dataset is large and only a small portion of it has missing values . Replacing missing values with a specific value like zero or by forward/backward filling may introduce bias or distort the dataset's integrity .

In a linear regression model, the intercept represents the predicted value when all other predictors are set to zero; it gives a baseline level of the dependent variable when the influence of independent variables is absent . The coefficients represent the expected change in the dependent variable for a one-unit change in the predictor variable, assuming all other variables remain constant. Together, they help interpret the relationship between independent and dependent variables within the model .

Conducting exploratory data analysis (EDA) is crucial as it provides an opportunity to understand data distributions, identify outliers, and detect patterns or correlations . EDA helps clean data, manage missing values, and feature selection or engineering, which can significantly impact model performance. Without EDA, models may overfit to noise or patterns that are not relevant, leading to poor predictive performance on new data .

Computing new columns such as 'Total Marks' and 'Percentage' in a dataset can significantly enhance its analytical power by aggregating and normalizing raw score data into a more comparative format . These computed fields enable deeper insights into the overall performance across different subjects and facilitate easy comparison between students, allowing for more effective clustering or classification in models. Such transformation can reveal hidden patterns and improve the interpretability of the data .

Reproducibility in data science ensures that an experiment can be repeated with the same tools and data to achieve the same results, which enhances transparency and reliability . It allows for verification of results and builds trust in the findings across different users or audiences. Without reproducibility, external validation of claims becomes challenging, risking findings that might be due to chance or specific conditions that cannot be replicated .

You might also like