调用KickstarterModel类方法时触发NotImplementedError,求排查方案
Let's break down the issues in your code that are causing the error and fix them step by step:
1. The Root Cause of NotImplementedError
Looking at your error traceback, it seems your preprocess_training_data method contains an invalid line that triggers the NotImplementedError. In the snippet from your error log:
def preprocess_training_data(self, df): NotImplementedError:
This line is leftover from a placeholder pattern (common when sketching out class methods initially) but was never removed once you added the actual preprocessing logic. Just writing NotImplementedError: like this is invalid syntax and will throw the error immediately when the method runs.
2. Additional Bugs in Your Preprocessing Logic
Even after fixing the error above, your code has two critical issues that will break functionality:
- Undefined variable
y: The final liney_train = yreferences a variableythat doesn't exist. You meant to use they_trainvariable you defined earlier in the method. - Wasted processed data: You're storing the cleaned features and target in local variables
X_trainandy_traininstead of the class instance attributesself.X_trainandself.y_train. This means the data won't be accessible to other methods (like atrainmethod) later on.
Fixed Code
Here's the corrected version of your KickstarterModel class:
from sklearn.tree import DecisionTreeClassifier class KickstarterModel: def __init__(self): self.model = DecisionTreeClassifier() self.X_train = None self.y_train = None def preprocess_training_data(self, df): # Define target variable y_train = df['state'].apply(lambda x: 0 if x == 'failed' else 1) # Process numerical features numerical_columns = df.describe().columns X = df[numerical_columns].copy() X.set_index('id', inplace=True) X["dif_launched_created"] = X.launched_at - X.created_at X["dif_deadline_created"] = X.deadline - X.created_at X["dif_deadline_launched"] = X.deadline - X.launched_at X['goal_in_usd'] = X.goal * X.static_usd_rate X.drop(['deadline', 'created_at', 'launched_at', 'goal', 'static_usd_rate'], axis=1, inplace=True) # Save processed data to instance attributes self.X_train = X self.y_train = y_train
Key Changes Made:
- Removed the invalid
NotImplementedError:line from the method body - Fixed the undefined
yvariable by using the existingy_trainvariable - Assigned processed features and target to
self.X_trainandself.y_trainso the data persists in the class instance for later use (like training the classifier)
After making these changes, calling model.preprocess_training_data(df) should run without errors, and your cleaned training data will be ready to use with your decision tree model.
内容的提问来源于stack exchange,提问作者Tom Smith

