Conducting Data Science in the Wild¶

About This Project¶

In this project, you will walk through how to approach a data science problem from scratch. The context of the problem is as follows:

You are tasked to predict the severity of a patient's heart disease based on a set of medical attributes.

We will restrict your attention to regression trees and walk you through how to approach this problem systematically.

Evaluation¶

This project must be successfully completed and submitted in order to receive credit for this course. Your score on this project will be included in your final grade calculation.

You are expected to write code where you see # YOUR CODE HERE within the cells of this notebook. Not all cells will be graded; code input cells followed by cells marked with # Auto-graded test cell will be graded. Upon submitting your work, the code you write at these designated positions will be assessed using an "auto-grader" that will run all test cells to assess your code. You will receive feedback from the auto-grader that will identify any errors in your code. Use this feedback to improve your code if you need to resubmit. Be sure not to change the names of any provided functions, classes, or variables within the existing code cells, as this will interfere with the auto-grader. Also, remember to execute all code cells sequentially, not just those you’ve edited, to ensure your code runs properly.

You can resubmit your work as many times as necessary before the submission deadline. If you experience difficulty or have questions about this exercise, use the Q&A discussion board to engage with your peers or seek assistance from the instructor.

Before starting your work, please review eCornell's policy regarding plagiarism (the presentation of someone else's work as your own without source credit).

Submit Code for Auto-Grader Feedback¶

Once you have completed your work on this notebook, you will submit your code for auto-grader review. Follow these steps:

  1. Save your notebook.

  2. Mark as Completed — In the blue menu bar along the top of this code exercise window, you’ll see a menu item called Education. In the Education menu, click Mark as Completed to submit your code for auto-grader/instructor review. This process will take a moment and a progress bar will show you the status of your submission.

  3. Review your results — Once your work is marked as complete, the results of the auto-grader will automatically be presented in a new tab within the code exercise window. You can click on the assessment name in this feedback window to see more details regarding specific feedback/errors in your code submission.

  4. Repeat, if necessary — The Jupyter Notebook will always remain accessible in the first tabbed window of the exercise. To reattempt the work, you will first need to click Mark as Uncompleted in the Education menu and then proceed to make edits to the notebook. Once you are ready to resubmit, follow steps one through three. You can repeat this procedure as many times as necessary.

You can also download a copy of this notebook in multiple formats using the Save and Export Notebook As option in the File menu above.

Getting Started¶

In [1]:
import numpy as np

# Non-interactive plots
%matplotlib inline
import matplotlib.pyplot as plt

import sys
sys.path.append("/home/codio/workspace/.modules")
from helper import *

print("Python version:", sys.version.split(" ")[0])
Python version: 3.12.5

Part Zero: Understand the Type of Data and Information to Be Extracted¶

For your convenience, we have split the data into training set and test set for you. The training data is in heart_disease_train.csv and the test data is in heart_disease_test.csv. You should do all your model selection on the training set and evaluate your final model on the test data. Selecting model based on the test data is considered cheating so please refrain from doing so! Before you begin, go to the File Browser (folder icon) in the left sidebar menu (or press Shift+Cmd+F) and take a look at the two CSV files heart_disease_train.csv and heart_disease_test.csv. Also check out the attribute.txt file, which contains a description of each attribute in the CSV files.

Part One: Implement load_data [Graded]¶

Implement a function called load_data, which will load the given CSV file and return X, y data, where X are the patients' attributes and y is the severity of the patients' heart disease. Your function should:

  1. Open the file

  2. Read the comma-separated columns in the first line of the CSV file (remember to strip the ending delimiters "\n")

  3. For each line except the first one, read the comma-separated column values, convert all values from str to float, and add to the data matrix (remember to strip the ending delimiters "\n")

  4. Use the "label" column for y if necessary

Implementation Notes:

  • In any case, do not include the "label" column in the data matrix — the model will then be able to use this feature to predict y

  • The function should handle two explicit cases. With label=True, it should output the data matrix X and the corresponding label vector y; with label=False, it should output only the data matrix X

  • Feel free to use pd.read_csv or other data loaders — just make sure the returned X, y are NumPy arrays of shapes (n, d) and n (respectively)

In [29]:
def load_data(file="heart_disease_train.csv", label=True):
    """
    Returns the data matrix and optionally the corresponding label vector.

    Input:
        file: filename of the dataset
        label: a boolean to decide whether to return the labels or not

    Output:
        X: (numpy array) nxd data matrix of patient attributes
        y: (numpy array) n-dimensional vector of labels (if label=False, y is not returned)
    """
    X = None
    y = None

    # YOUR CODE HERE
    data = np.loadtxt(file, delimiter=',', skiprows=1)
    if label:
        X = data[:, :-1]
        y = data[:, -1]
        return X, y
    return data
    # END OF YOUR CODE
In [30]:
X, y = load_data()
print(f"Training data matrix shape: {X.shape}")
print(f"Label vector shape: {y.shape}")
Training data matrix shape: (244, 13)
Label vector shape: (244,)

The following tests check that your load_data function reads in the correct number of rows, the correct number of unique values for y, and the same training data as the correct implementation.

In [31]:
Xtrain, ytrain = load_data()
Xtrain_grader, ytrain_grader = load_data_grader()
Xtest = load_data(file="heart_disease_test.csv", label=False)
Xtest_grader = load_data_grader(file="heart_disease_test.csv", label=False)


def load_data_test1():
    return len(Xtrain) == len(ytrain)


def load_data_test2():
    return len(Xtrain) == len(Xtrain_grader)


def load_data_test3():
    y_unique = np.sort(np.unique(ytrain))
    y_grader_unique = np.sort(np.unique(ytrain_grader))

    if len(y_unique) != len(y_grader_unique):
        return False
    else:
        return np.linalg.norm(y_unique - y_grader_unique) < 1e-7


def load_data_test4():
    return (
        type(Xtrain) == np.ndarray
        and type(ytrain) == np.ndarray
        and type(Xtest) == np.ndarray
    )


def load_data_test5():
    Xtrain.sort()
    Xtrain_grader.sort()
    return np.linalg.norm(Xtrain - Xtrain_grader) < 1e-07


def load_data_test6():
    ntr, dtr = Xtrain.shape
    nte, dte = Xtest.shape
    return dtr == dte


def load_data_test7():
    Xtest.sort()
    Xtest_grader.sort()
    return np.linalg.norm(Xtest - Xtest_grader) < 1e-07


runtest(load_data_test1, "load_data_test1")
runtest(load_data_test2, "load_data_test2")
runtest(load_data_test3, "load_data_test3")
runtest(load_data_test4, "load_data_test4 (Testing for correct types)")
runtest(load_data_test5, "load_data_test5 (Testing training data for correctness)")
runtest(
    load_data_test6,
    "load_data_test6 (training and testing data dimensions should match)",
)
runtest(load_data_test7, "load_data_test7 (Testing test data for correctness)")
Running Test: load_data_test1 ... ✔ Passed!
Running Test: load_data_test2 ... ✔ Passed!
Running Test: load_data_test3 ... ✔ Passed!
Running Test: load_data_test4 (Testing for correct types) ... ✔ Passed!
Running Test: load_data_test5 (Testing training data for correctness) ... ✔ Passed!
Running Test: load_data_test6 (training and testing data dimensions should match) ... ✔ Passed!
Running Test: load_data_test7 (Testing test data for correctness) ... ✔ Passed!

Skip over the auto-graded test cells below (see Evaluation for details).

In [ ]:
# Auto-graded test cell worth one point (load_data_test1)
In [ ]:
# Auto-graded test cell worth one point (load_data_test2)
In [ ]:
# Auto-graded test cell worth one point (load_data_test3)
In [ ]:
# Auto-graded test cell worth one point (load_data_test4)
In [ ]:
# Auto-graded test cell worth one point (load_data_test5)
In [ ]:
# Auto-graded test cell worth one point (load_data_test6)
In [ ]:
# Auto-graded test cell worth one point (load_data_test7)

Part Two: Picking a Metric for Evaluation¶

Since this is a classification problem, there are multiple loss functions or metrics we can use to evaluate. You will use mean_squared_loss as your loss function since you can always cast a classification problem as regression problem.

We have implemented the mean_squared_loss function below.

In [32]:
def mean_squared_loss(pred, truth):
    """
    Calculates the mean squared loss between predicted and true labels.

    Input:
        pred: n-dimensional vector of predicted labels
        truth: n-dimensional vector of true labels

    Output:
        loss: average squared loss
    """
    return np.mean((pred - truth) ** 2)

Part Three: Model Selection [Graded]¶

At this point, you have:

  • Split the data into training set and test set

  • Understood and loaded the data

  • Picked a metric for evaluation

Now you are ready for model selection!

A data scientist would typically try different models such as perceptron, linear regression, etc. For simplicity, we restrict your attention to regression trees.

Implementation Notes:

  • You will implement the make_prediction function (below), which loads the training and test sets, finds the optimal regression tree trained on heart_disease_train.csv, and returns the tree's predictions on heart_disease_test.csv

  • If you want to create a tree of depth k, then you would call RegressionTree(depth=k)

  • You will be evaluated based on mean_squared_loss, and will receive a full score if the loss on your classifier is less than 0.18

  • You may use any functions that you implemented in the previous projects

Hints:

  • Select the best depth to avoid overfitting

  • Pick the optimal subset of features for your classification model

The next cell has some functions/classes from previous projects that you may find useful.

In [33]:
#### Regression Tree ####
# Create a regression tree with no restriction on depth
tree = RegressionTree(depth=np.inf)

# Fit/train the regression tree
tree.fit(X, y)

# Use the trained regression tree to make predictions
pred = tree.predict(X)

#### k-Fold Cross Validation ####
# Specify the depths
depths = [1, 3]

# Generate 5 folds for X data
indices = generate_kFold(n=X.shape[0], k=5)

# Find best depth across the folds
best_depth, training_losses, validation_losses = cross_validation(X, y, depths, indices)

Use the code in the previous cell to implement a make_prediction function in the next cell.

In [54]:
def make_prediction():
    """
    Loads the training and test sets, trains a regression tree,
    and outputs predictions for the test set.

    Output:
        prediction: the prediction of your classifier on the heart_disease_test.csv
    """
    prediction = None
    Xtrain, ytrain = load_data(file="heart_disease_train.csv", label=True)
    ytrain = ytrain > 0
    Xtest = load_data(file="heart_disease_test.csv", label=False)

    # YOUR CODE HERE
    depths = [1,3]
    indices = generate_kFold(n=Xtrain.shape[0], k=5)
    best_depth, training_losses, validation_losses = cross_validation(Xtrain, ytrain, depths, indices)
    tree = RegressionTree(depth=best_depth)
    tree.fit(Xtrain, ytrain)
    prediction = tree.predict(Xtest)
    # END OF YOUR CODE
    
    return prediction

Run the next cell to check your implementation of make_prediction on a sample dataset.

In [55]:
def make_prediction_test():
    """
    Test for your make_prediction function
    """
    truth = np.array(
        [
            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1,
            1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1
        ]
    )
    pred = make_prediction()
    loss = mean_squared_loss(pred, truth)
    return loss < 0.18


runtest(make_prediction_test, "make_prediction_test")
Running Test: make_prediction_test ... ✔ Passed!

Skip over the auto-graded test cell below (see Evaluation for details).

In [ ]:
# Auto-graded test cell worth one point (make_prediction_test)