A method is a function defined inside a class. It gives an object behavior: a model object can train or predict, while a data object can prepare data, create plots, or calculate metrics. Methods keep related data and operations together, helping organize reusable data science code. section 4.1 section 4.4
Call a method with dot notation: write the object name, a dot, and the method name. Methods commonly receive self as their first parameter, allowing them to read or change instance variables attached to that particular object. The special __init__ method runs when an object is created and sets up values other methods can use. section 4.2 section 4.2.1
Bundle dataset tasks into methods
A DataSet object can store training and test data once, then expose get_summary_plots() to generate feature histograms. Another method can calculate precision from prediction columns. This replaces repeated exploration and evaluation code with named operations on the same dataset object. section 4.2.1 section 4.2
Wrap model tuning
A RandomForestModel can place hyperparameter tuning in a tune method and prediction retrieval in a predict method. Generalizing that design into MlModel lets the same method interface work with different scikit-learn models. section 4.2.2
Listing 4.11 This code adds a new method (called get_summary_plots) to our class. This method will generate a histogram of each input feature in the feature_list variable.
import pandas as pd #1
from sklearn.model_selection import train_test_split #1
import matplotlib.pyplot as plt #1
class DataSet: #2
def __init__(self, #3
feature_list: list, #3
file_name: str, #3
label_col: str, #3
pos_category: str): #3
self.customer_data = pd.read_csv(file_name) #4
self.train_data, #5
self.test_data = train_test_split( #5
self.customer_data, #5
train_size = 0.7, #5
random_state = 0) #5
self.train_data = self.\ #6
train_data.\ #6
reset_index(drop = True) #6
self.test_data = self.\ #6
test_data.\ #6
reset_index(drop = True) #6
self.feature_list = feature_list #7
self.train_features = self.\ #8
train_data[feature_list] #8
self.test_features = self.\ #8
test_data[feature_list] #8
self.train_labels = self.\ #9
train_data[label_col].\ #9
map(lambda key: 1 if key == pos_category #9
else 0) #9
self.test_labels = self.\
test_data[label_col].\ #9
map(lambda key: 1 if key == pos_category #9
else 0) #9
def get_summary_plots(self): #10
for feature in self.feature_list: #10
self.train_data[feature].hist() #10
plt.title(feature) #10
plt.show() #10
The listing shows a method defined on a DataSet class and tied to the object’s stored feature data. section 4.2.1
























