Increase familiarity with Pandas and SciKit Learn libraries for data cleaning
Learn how to work with messy datasets
Learn how to combine different datasets
Understand the importance of data preprocessing for improving model performance
Gain experience in encoding categorical features and normalizing numerical features
Pre-requisites
Knowledge of the basic syntax of Python is expected
Overview
A team of doctors and scientists have been working to combat Chronic Kidney Disease (CKD). They've collected detailed medical data from 400 patients. This dataset is crucial for understanding and predicting CKD. Your mission is to clean and preprocess this dataset to prepare it for machine learning!
You'll be given 2 dirty datasets. Apply data cleaning techniques using pandas functions to create a clean and preprocessed dataset.
There are many different data loading/analysis libraries out there for python but don't reinvent the wheel. Pandas is by far the most universally used library for manipulating datasets. It includes tools for loading datasets, slicing/combining the data, and easily transforming back and forth to NumPy primitives. The following tutorials should cover some but not all the tools you will need to complete this assignment.
I get this error: # Load the datasets
numerical_data = arff.loadarff('chronic_kidney_disease_full.arff')
categorical_data = arff.loadarff('chronic_kidney_disease.arff')
The error you're experiencing could stem from a few different sources when loading ARFF files using the module. Here are a few solutions to troubleshoot the issue and ensure that you properly load your datasets.
Starter Code
CS 383 Data Cleaning Assignment.ipynb
Submissions
To make a submission for the project, submit a pdf of CS_383_Data_Cleaning_Assignment jupyter notebook under Assignment 3 - Data Cleaning and Preprocessing on Gradescope.
How to generate a pdf of your jupyter notebook:
On your Github repository after finishing the assignment, click on CS_383_Data_Cleaning_Assignment.ipynb to open the markdown preview.
Use your browser 's "Print to PDF" feature to save your PDF.
On Gradescope, please assign the pages of your pdf to the specific questions/sections outlined.
How many late days are you using for this assignment? 1 Day
Imports and pip installations (if needed)
import pandas as pd
import numpy as np
from scipy.io import arff
Part 1: Load the dataset
#Load the dataset
numerical_data = arff.loadarff('chronic_kidney_disease_full.arff')
categorical_data = arff.loadarff('chronic_kidney_disease.arff')
Explain what the each data is in your own words. What are the features and labels? Are the features in the given datasets : categorical, numerical or both? Give 3 examples of categorical and numerical columns each (if they exist)
Answer:
Part 3: Data Preprocessing
A fundamental skill in Machine Learning is mastering the art of data cleaning and preprocessing. In this assignment, you will learn and apply essential data cleaning techniques to transform a raw dataset into a clean, ready-to-use form which you can use for regression or classification tasks. By the end of this assignment, you'll have a fully clean dataset and a solid foundation in preparing data for various machine learning models.
Part 3.1 : Drop Duplicate rows
Let's start by checking if the given datasets have any duplicate rows (same Unique Id). Use pandas to identify and remove these duplicate rows from the given dataset
For the numerical dataset, check if there are duplicate rows in the dataset. If yes, print total number of duplicate rows
Drop these duplicate rows
Repeat the same for categorical dataset. Print the duplicate rows and drop them
Part 3.2: Combine two differents datasets
A good skill to have is to know how to combine 2 different datasets.
Are all the unique ids are present in both datasets? Why do you think so? If not, what do the rows that are missing from one of the datasets look like in the combined table?
Answer:
Merge the two given numerical and categorical datasets based on their unique_ID.
#Print the combined dataset
Part 3.3: Rows with Missing values
Removing missing values from a dataset is important for classification because it ensures the model is trained on complete and accurate data, leading to better performance and reliable predictions. Incomplete data can introduce bias and errors, negatively impacting the model's effectiveness.
Calculate the percentage of rows that contain atleast one missing value
Print %
Drop these rows from the dataset
Print the Dataset
Part 3.4: Sort the dataset according to the Labels
Sort the dataset according to the values in 'Target' column. Make sure reset the indices after sorting
Print the dataset
Part 3.5: Encoding Categorical data
In this step, we identify and process the categorical columns in the sorted dataset. We map each unique value in these columns to separate "dummy" columns.
For example, the column 'rbc' will be transformed into two columns 'rbc_normal' and 'rbc_abnormal'. If a row's value in 'rbc' is 'normal', the 'rbc_normal' column will be set to 1 and 'rbc_abnormal' will be set to 0.
**Note: Find a correct pandas function to do this **
In the example we went through above, another solution is to have a single column for the binary variable. In the downstream modeling would this be equivalent? What effect would this have if the categorical variable could take more than 2 values? For example, let's say we have a categorical feature that is "type of condiment" that can take 5 separate values and we are trying to predict the rating of a particular sandwich.
Answer:
Part 3.6 : Remove Outliers from Numerical Columns
Outliers can disproportionately influence the fit of a regression model, potentially leading to a model that does not generalize well therefore it is important that we remove outliers from the numerical columns of the dataset.
For this dataset, we define an outlier to be 3 times the standard deviation from the mean. Drop these outliers from the dataset
Normalizing numerical attributes ensures that all features contribute equally to the model by scaling them to a consistent range, which improves model performance and convergence. It prevents features with larger scales from disproportionately influencing the model's learning process.
Normalize the all Numerical Attributes in the dataset.
Print the dataset
Part 3.8: Remove Unnecessary columns
Are there any columns in this dataset which are not appropriate for modeling and predictions? Which column(s)? Justify their exclusion and remove them
Answer:
#Remove that column
Print the dataset
Part 3.9: Export the Cleaned Data
Now that you've completed these cleaning steps you should have a pandas dataframe which is much cleaner and ready for modeling. Our final step is to save our work. Export the DataFrame to a two new formats: csv and json.
Export the dataframe to a new csv file
Export the dataframe to a new json file
Part 4: Data conversions with Large Language Models
One powerful use case of ChatGPT (and other generative language models) is cleaning and transforming data. In some cases, these models can directly manipulate loosely structured data that you provide to them into a standard format. In the other cases, you can often prompt the model to create a conversion or extraction script for you in python or Pandas and then run it on your own.
In this part of the assignment you will prompt 383GPT to explore these capabilities.
Part 4.1 GPT Data Manipulation
Take the cleaned dataset that you created in part three and output the top 15 rows of that dataset. Then copy the terminal output, open 383gpt and ask it to convert that output to a markdown table. Paste that markdown table in the cell bellow
Paste here:
Paste the markdown table here
** Caution: ** while language models can perform data conversions they also can * hallucinate * during this process, particularly for bigger datasets. Reflect on this below, how could you mitigate data conversion hallucinations from LLM conversions?
Part 4.2 GPT Pandas Prompting
In this section, you will prompt 383GPT to write pandas code manipulations for you.
After working with this data for awhile, we realized we're starting to forget the meanings of the abbreviated column names. Let's ask 383GPT to fix this for us. First, navigate to the UCI dataset overview and copy the abbrevation to name mapping. Then, go to 383GPT and instruct the LLM to provide you with a pandas script to apply this renaming to all the columns of your dataset. Paste that code below and make any adjustments necessary to run it in your notebook.
Code to rename all the columns in the dataset
Part 4.3 Augmenting our skills with prompting
In addition, we can also use 383GPT to convert our data manipulation operations between different data manipulation languages and libraries. For example let's prompt 383GPT to convert the following SQL query to a pandas query.
SQL Query
sql
SELECT Target, COUNT(*) AS count
FROM your_table_name
GROUP BY Target;
Prompt 383GPT to convert this to a pandas query. Run this query below, then describe what it does. (If you're not familiar with SQL that is okay you need to only comment on the final resulting output.)
Converted SQL to Pandas code
Describe what the above code does here
Certainly! Here’s how you can approach your data cleaning and preprocessing project, step by step, according to the outline you provided.
Part 1: Load the Dataset
First, you will need to load the datasets provided. Since the datasets are in ARFF format (usually used for machine learning), you'll use the arff function to read them.
python
# Imports and pip installations
import pandas as pd
import numpy as np
from scipy.io import arff
# Load the datasets
numerical_data = arff.loadarff('chronic_kidney_disease_full.arff')
categorical_data = arff.loadarff('chronic_kidney_disease.arff')
# Converting to pandas DataFrame
numerical_df = pd.DataFrame(numerical_data[0])
categorical_df = pd.DataFrame(categorical_data[0])
# Print datasets
print(numerical_df.head())
print(categorical_df.head())
Part 2: Analyze the Dataset
In this part, you describe the data.
Your task is to identify what each dataset contains.
Features and labels need to be clarified, and the types of data should be assessed.
plaintext
The 'numerical_data' dataset contains features related to patient attributes and lab test results, while 'categorical_data' contains more categorical features such as 'rbc', 'pc', etc., and the 'Target' label indicating CKD presence.
Examples:
- Categorical Features: 'rbc', 'pc', 'dm'
- Numerical Features: 'age', 'bp', 'bgr'
Part 3: Data Preprocessing
Part 3.1: Drop Duplicate Rows
Check for duplicate rows in both datasets:
python
# Check for duplicate rows in the numerical dataset
duplicate_rows_numerical = numerical_df[numerical_df.duplicated()]
print(f"Duplicate rows in numerical dataset: {duplicate_rows_numerical.shape[0]}")
# Drop duplicate rows
numerical_df = numerical_df.drop_duplicates()
# Repeat for categorical dataset
duplicate_rows_categorical = categorical_df[categorical_df.duplicated()]
print(f"Duplicate rows in categorical dataset: {duplicate_rows_categorical.shape[0]}")
categorical_df = categorical_df.drop_duplicates()
Part 3.2: Combine Two Different Datasets
Merge the two datasets on their unique IDs:
python
# Check for unique_ids (assuming both datasets have a column named 'Unique_ID')
if 'Unique_ID' in numerical_df.columns and 'Unique_ID' in categorical_df.columns:
combined_df = pd.merge(numerical_df, categorical_df, on='Unique_ID')
else:
print("Unique_ID column not found in one or both datasets.")
print(combined_df.head())
Part 3.3: Rows with Missing Values
Identify and drop rows with missing values:
python
percentage_missing = combined_df.isnull().any(axis=1).mean() * 100
print(f"Percentage of rows with at least one missing value: {percentage_missing:.2f}%")
# Drop rows with missing values
combined_df = combined_df.dropna()
print(combined_df.head())
Part 3.4: Sort the Dataset According to the Labels
Using separate dummy columns helps avoid multicollinearity in models like linear regression. If a categorical variable has more than two values, you lose information with binary encoding (i.e., more than 2 values would complicate interpretation).
Part 3.6: Remove Outliers from Numerical Columns
Define and remove outliers:
python
numerical_columns = ['age', 'bp', 'bgr', 'bu', 'sc', 'sod', 'pot', 'hemo', 'pcv', 'wbcc', 'rbcc']
# Remove outliers
for column in numerical_columns:
mean = combined_df[column].mean()
std_dev = combined_df[column].std()
combined_df = combined_df[(combined_df[column] > mean - 3 * std_dev) &
(combined_df[column] < mean + 3 * std_dev)]
print(combined_df.head())
Part 4: Data Conversions with Large Language Models
This part involves interaction with GPT models and is more straightforward. You would retrieve the first 15 rows and convert them to a markdown table format, then you need to ask an LLM for renaming:
python
# Output top 15 rows
print(combined_df.head(15))
For replacing abbreviations:
You can create a dictionary based on the UCI overview and use it to rename the dataframe:
python
rename_dict = {
'rbc': 'Red Blood Cell',
'pc': 'Pus Cell',
'bp': 'Blood Pressure',
# add all other abbreviations here as needed
}
combined_df.rename(columns=rename_dict, inplace=True)
SQL to Pandas Conversion:
For the SQL query provided:
python
# The equivalent pandas code:
count_groups = combined_df.groupby('Target').size().reset_index(name='count')
print(count_groups)
Conclusion
Make sure to write reflections on the cleaning process, the importance of each step, and how you would handle future projects differently, especially regarding error checking and validation of processed data. Submit your notebook as instructed, along with the necessary markdown tables and reflections prompted by the LLM interactions. Good luck!
scipy.io.arff
1. Check the File Paths
Make sure that the ARFF files (chronic_kidney_disease_full.arff and chronic_kidney_disease.arff) are located in the same directory as your Jupyter notebook or Python script. If they are located in a different folder, specify the correct path.
2. Verify ARFF File Format
ARFF files should adhere to a specific structure. If the files are malformed or not in the correct ARFF format, you might encounter issues when trying to load them. Open the files in a text editor and check if they contain the necessary headers and data portions.
3. Correct Import Statements
Ensure you're importing the required libraries properly. Here is how to appropriately import and load the data:
python
# Imports
import pandas as pd
from scipy.io import arff
# Load the datasets (use full paths if necessary)
numerical_data = arff.loadarff('chronic_kidney_disease_full.arff')
categorical_data = arff.loadarff('chronic_kidney_disease.arff')
# Converting to pandas DataFrame
numerical_df = pd.DataFrame(numerical_data[0]) # [0] contains the actual data and column names.
categorical_df = pd.DataFrame(categorical_data[0]) # [0] contains the actual data and column names.
# Print datasets
print(numerical_df.head())
print(categorical_df.head())
4. Handling Byte Strings
ARFF files loaded via scipy.io.arff may have columns with byte strings. If the columns are not decoded properly, they may cause issues when creating a DataFrame. You can convert byte strings to regular strings using encoding.
Make sure you have both pandas and scipy libraries installed in your environment. If not, you can install them using:
bash
pip install pandas scipy
Final Steps
Try running the adjusted code snippets and see if the error persists. If you encounter a specific error message, please provide it, and I’ll assist you further in troubleshooting based on that error.