Spaces:
Sleeping
Sleeping
Bachstelze commited on
Commit ·
19ac57f
1
Parent(s): 1f883f1
add dynamic feature resolving
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657import pickleimport pandas as pdfrom sklearn.linear_model import LinearRegressionfrom sklearn.metrics import mean_absolute_error, r2_scoretrain_path = "../Datasets_all/A2_dataset_80.csv"test_path = "../Datasets_all/A2_dataset_20.csv"# validating the linear regression model based on# https://medium.com/@_SSP/validating-machine-learning-regression-models-a-comprehensive-guide-b94fd94e339cdef load_and_evaluate_model(model_path):# Load the pickled modelwith open(model_path, "rb") as f:model = pickle.load(f)# check the model typeassert isinstance(model, LinearRegression)# Load datatrain_df = pd.read_csv(train_path)test_df = pd.read_csv(test_path)# Define target and featurestarget_col = "AimoScore"unwanted_cols = ["EstimatedScore"]features_cols = [colfor col in train_df.columnsif col not in unwanted_cols and col != target_col]X_test = test_df[features_cols]y_test = test_df[target_col]# Predict on test sety_pred = model.predict(X_test)# Evaluatemae = mean_absolute_error(y_test, y_pred)r2 = r2_score(y_test, y_pred)print(f"Mean Absolute Error on test set: {mae:.4f}")print(f"R^2 score on test set: {r2:.4f}")# assert the threeshold valuesassert mae < 0.15, "Mean Absolute Error is too high"assert r2 > 0.5, "R^2 score is too low"# Save predictions to CSVtest_df["Predicted_AimoScore"] = y_predtest_df.to_csv("predicted_test.csv", index=False)if __name__ == "__main__":1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586import pickleimport pandas as pdfrom sklearn.linear_model import LinearRegressionfrom sklearn.metrics import mean_absolute_error, r2_scoreimport re # For using regular expressionstrain_path = "../Datasets_all/A2_dataset_80.csv"test_path = "../Datasets_all/A2_dataset_20.csv"def extract_missing_feature(error_message):# Use regex to find feature names in the ValueError messagematch = re.search(r"Feature names unseen at fit time:\s*-\s*(.+)", error_message)if match:return match.group(1).strip().split(', ') # Return list of feature namesreturn []def load_and_evaluate_model(model_path):# Load the pickled modelwith open(model_path, "rb") as f:model = pickle.load(f)# Check the model typeassert isinstance(model, LinearRegression)# Load datatrain_df = pd.read_csv(train_path)test_df = pd.read_csv(test_path)# Define target and features dynamicallytarget_col = "AimoScore"unwanted_cols = ["EstimatedScore"]features_cols = [col for col in train_df.columnsif col not in unwanted_cols and col != target_col]# Initialize features for predictionX_test = test_df[features_cols]y_test = test_df[target_col]#define y_predy_pred = 0# Continue to predict until no ValueErrors occurwhile True:try:# Predict on test sety_pred = model.predict(X_test)# Evaluatemae = mean_absolute_error(y_test, y_pred)r2 = r2_score(y_test, y_pred)print(f"Mean Absolute Error on test set: {mae:.4f}")print(f"R^2 score on test set: {r2:.4f}")# Assert the threshold valuesassert mae < 0.15, "Mean Absolute Error is too high"assert r2 > 0.5, "R^2 score is too low"break # Exit the loop if no errors occurexcept ValueError as e:print(f"Error during prediction: {e}")# Extract missing features from the error messagemissing_features = extract_missing_feature(str(e))# Remove missing features from X_test and features_colsif missing_features:print(f"Removing missing features from test set: {missing_features}")# Update features listfeatures_cols = [col for col in features_cols if col not in missing_features]# Update X_testX_test = X_test[features_cols]else:print("No more features can be removed, stopping execution.")break # Exit if there are no more features to removeif 'y_pred' in locals(): # Check if predictions were made# Save predictions to CSVtest_df["Predicted_AimoScore"] = y_predtest_df.to_csv("predicted_test.csv", index=False)if __name__ == "__main__":
test/test_model.py+54-25