Feature Engineering (40 min)
C7 - Générer des données d'entrée afin de satisfaire les contraintes inhérentes au modèles (Feature Engineering)
🎯 Build a Pipeline that handles geo and date data with custom transformations
📝 Create feat_geo and feat_date, two lists containing the name of geo coordinates and date features, respectively.
feat_geo = ['lat', 'lon', 'rally_point_lon', 'rally_point_lat']
feat_date = ['date']
executed in 4ms, finished 15:29:41 2024-01-11
☑️ All transformers in this section should be created as a python class, with inheritance from sklearn BaseEstimator and sklearn TransformerMixin
📝 Create a Custom Transformer, DistanceTransformer, to compute a distance from two sets of coordinates:
☑️ Use lat, lon, rally_point_lat, rally_point_lon as input
☑️ The transform method must return a distance in kilometers
☑️ It returns a DataFrame with a single column distance
☑️ You have to compute the distance using the Haversine formula
☑️ As your client does not expect you to be an expert on geolocalization, he encourages you to look this formula up to find a proper implementation in python
class DistanceTransformer(BaseEstimator, TransformerMixin):
def init(self):
pass
def fit(self, X_filled, y=None):
return self
def transform(self, X_filled):
if not all(column in X_filled.columns for column in feat_geo):
raise ValueError(f"The input DataFrame must contain the following columns: {feat_geo}")
code
# Define the Haversine function
def haversine(lon1, lat1, lon2, lat2):
# Convert decimal degrees to radians
lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])
# Haversine formula
dlon = lon2 - lon1
dlat = lat2 - lat1
a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2
c = 2 * asin(sqrt(a))
r = 6371 # Radius of earth in kilometers
return c * r
code
# Apply the Haversine function to each row in the DataFrame
distances = X_filled.apply(lambda row: haversine(row['lon'], row['lat'], row['rally_point_lon'], row['rally_point_lat']), axis=1)
# Return a DataFrame with the computed distances
distance_df = pd.DataFrame(distances, columns=['distance'])
return distance_df
executed in 9ms, finished 15:46:37 2024-01-11
☑️ Create a pipeline with your DistanceTransformer and then a sklearn Scaling method for the newly created distance.
distance_scaling_pipeline = Pipeline([
('distance_transformer', DistanceTransformer()),
('scaler', StandardScaler()) # Scale the computed distances
])
executed in 4ms, finished 15:51:58 2024-01-11
📝 Create a Custom Transformer, CyclicalEncoder
☑️ Use the date as input
☑️ Use the formulas below:
month_cos = 𝑐𝑜𝑠(2𝜋∗𝑚𝑜𝑛𝑡ℎ12)
month_sin = 𝑠𝑖𝑛(2𝜋∗𝑚𝑜𝑛𝑡ℎ12)
☑️ The transform method must return a DataFrame two columns: month_cos and month_sin
class CyclicalEncoder(BaseEstimator, TransformerMixin):
def init(self):
pass
def fit(self, X_filled, y=None):
return self
def transform(self, X_filled):
if 'date' not in X_filled.columns:
raise ValueError("The input DataFrame must contain a 'date' column.")
X_filled['date'] = pd.to_datetime(X_filled['date'])
month = X_filled['date'].dt.month
month_sin = np.sin(2 * np.pi * month / 12)
month_cos = np.cos(2 * np.pi * month / 12)
df = pd.DataFrame({'month_sin': month_sin, 'month_cos': month_cos})
return df
executed in 7ms, finished 15:54:03 2024-01-11
📝 Create feature_engineering, a Pipeline that applies both your custom transformers to the relevant columns
☑️ It should apply your DistanceTransformer + Scaling pipeline to the coordinates
☑️ It should apply your CyclicalEncoder to the date
Create a pipeline with the custom transformers
feature_engineering = Pipeline([
('distance_pipeline', distance_scaling_pipeline),
('cyclical_encoder', CyclicalEncoder())
])
executed in 4ms, finished 15:59:44 2024-01-11
📝 Transform a sample of a 100 rows with your feature_engineering pipeline.
☑️ Store the resulting transformed data in, features_transformed, a DataFrame with three columns distance, month_cos and month_sin
Transform a sample of 100 rows with the feature_engineering pipeline
features_transformed = feature_engineering.fit_transform(X_filled.iloc[:100])
executed in 77ms, finished 16:02:04 2024-01-11
AttributeError Traceback (most recent call last)
Cell In [39], line 2
1 # Transform a sample of 100 rows with the feature_engineering pipeline
----> 2 features_transformed = feature_engineering.fit_transform(X_filled.iloc[:100])
File ~/.pyenv/versions/3.10.6/envs/lewagon/lib/python3.10/site-packages/sklearn/base.py:1152, in _fit_context..decorator..wrapper(estimator, *args, **kwargs)
1145 estimator._validate_params()
1147 with config_context(
1148 skip_parameter_validation=(
1149 prefer_skip_nested_validation or global_skip_validation
1150 )
1151 ):
-> 1152 return fit_method(estimator, *args, **kwargs)
File ~/.pyenv/versions/3.10.6/envs/lewagon/lib/python3.10/site-packages/sklearn/pipeline.py:479, in Pipeline.fit_transform(self, X, y, **fit_params)
477 fit_params_last_step = fit_params_steps[self.steps[-1][0]]
478 if hasattr(last_step, "fit_transform"):
--> 479 return last_step.fit_transform(Xt, y, **fit_params_last_step)
480 else:
481 return last_step.fit(Xt, y, **fit_params_last_step).transform(Xt)
File ~/.pyenv/versions/3.10.6/envs/lewagon/lib/python3.10/site-packages/sklearn/utils/_set_output.py:157, in _wrap_method_output..wrapped(self, X, *args, **kwargs)
155 @wraps(f)
156 def wrapped(self, X, *args, **kwargs):
--> 157 data_to_wrap = f(self, X, *args, **kwargs)
158 if isinstance(data_to_wrap, tuple):
159 # only wrap the first output for cross decomposition
160 return_tuple = (
161 _wrap_data_with_container(method, data_to_wrap[0], X, self),
162 *data_to_wrap[1:],
163 )
File ~/.pyenv/versions/3.10.6/envs/lewagon/lib/python3.10/site-packages/sklearn/base.py:916, in TransformerMixin.fit_transform(self, X, y, **fit_params)
912 # non-optimized default implementation; override when a better
913 # method is possible for a given clustering algorithm
914 if y is None:
915 # fit method of arity 1 (unsupervised transformation)
--> 916 return self.fit(X, **fit_params).transform(X)
917 else:
918 # fit method of arity 2 (supervised transformation)
919 return self.fit(X, y, **fit_params).transform(X)
File ~/.pyenv/versions/3.10.6/envs/lewagon/lib/python3.10/site-packages/sklearn/utils/_set_output.py:157, in _wrap_method_output..wrapped(self, X, *args, **kwargs)
155 @wraps(f)
156 def wrapped(self, X, *args, **kwargs):
--> 157 data_to_wrap = f(self, X, *args, **kwargs)
158 if isinstance(data_to_wrap, tuple):
159 # only wrap the first output for cross decomposition
160 return_tuple = (
161 _wrap_data_with_container(method, data_to_wrap[0], X, self),
162 *data_to_wrap[1:],
163 )
Cell In [35], line 9, in CyclicalEncoder.transform(self, X_filled)
8 def transform(self, X_filled):
----> 9 if 'date' not in X_filled.columns:
10 raise ValueError("The input DataFrame must contain a 'date' column.")
12 X_filled['date'] = pd.to_datetime(X_filled['date'])
AttributeError: 'numpy.ndarray' object has no attribute 'columns'
Assistant
The error you're seeing is because the output of the distance_scaling_pipeline is a numpy array, and numpy arrays do not have a "columns" attribute.
The CyclicalEncoder transformer is trying to access the columns of a DataFrame, but it's receiving a numpy array instead.
To fix this issue, you could modify your CyclicalEncoder and DistanceTransformer to work with numpy arrays instead of DataFrames. Alternatively, if you want to keep working with DataFrames, you could modify your pipeline to ensure that the output of the distance_scaling_pipeline is a DataFrame.
Here is an example of how you could modify your pipeline to ensure that the output of each step is a DataFrame:
python
from sklearn.compose import ColumnTransformer
# Define transformers for each type of feature
distance_transformer = Pipeline([
('distance', DistanceTransformer()),
('scaler', StandardScaler())
])
date_transformer = CyclicalEncoder()
# Use ColumnTransformer to apply the appropriate transformer to each type of feature
preprocessor = ColumnTransformer(
transformers=[
('num', distance_transformer, feat_geo),
('date', date_transformer, feat_date)
])
# Now, when you call preprocessor.fit_transform(X_filled.iloc[:100]),
# it should return a DataFrame with columns for the distance and date features.
Remember to ensure that your custom Transformers (DistanceTransformer and CyclicalEncoder) return dataframes and not numpy arrays. You can convert a numpy array to a DataFrame with pd.DataFrame().