1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
|
- import os
- import warnings
- import sys
- import pandas as pd
- import numpy as np
- from sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score
- from sklearn.model_selection import train_test_split
- from sklearn.linear_model import ElasticNet
- from get_data import read_params
- import argparse
- import joblib
- import json
- def eval_metrics(actual, pred):
- rmse = np.sqrt(mean_squared_error(actual, pred))
- mae = mean_absolute_error(actual, pred)
- r2 = r2_score(actual, pred)
- return rmse, mae, r2
- def train_and_evaluate(config_path):
- config = read_params(config_path)
- test_data_path = config["split_data"]["test_path"]
- train_data_path = config["split_data"]["train_path"]
- random_state = config["base"]["random_state"]
- model_dir = config["model_dir"]
- alpha = config["estimators"]["ElasticNet"]["params"]["alpha"]
- l1_ratio = config["estimators"]["ElasticNet"]["params"]["l1_ratio"]
- target = [config["base"]["target_col"]]
- train = pd.read_csv(train_data_path, sep=",")
- test = pd.read_csv(test_data_path, sep=",")
- train_y = train[target]
- test_y = test[target]
- train_x = train.drop(target, axis=1)
- test_x = test.drop(target, axis=1)
- lr = ElasticNet(
- alpha=alpha,
- l1_ratio=l1_ratio,
- random_state=random_state)
- lr.fit(train_x, train_y)
- predicted_qualities = lr.predict(test_x)
- (rmse, mae, r2) = eval_metrics(test_y, predicted_qualities)
- print("Elasticnet model (alpha=%f, l1_ratio=%f):" % (alpha, l1_ratio))
- print(" RMSE: %s" % rmse)
- print(" MAE: %s" % mae)
- print(" R2: %s" % r2)
- #####################################################
- scores_file = config["reports"]["scores"]
- params_file = config["reports"]["params"]
- with open(scores_file, "w") as f:
- scores = {
- "rmse": rmse,
- "mae": mae,
- "r2": r2
- }
- json.dump(scores, f, indent=4)
- with open(params_file, "w") as f:
- params = {
- "alpha": alpha,
- "l1_ratio": l1_ratio,
- }
- json.dump(params, f, indent=4)
- #####################################################
- os.makedirs(model_dir, exist_ok=True)
- model_path = os.path.join(model_dir, "model.joblib")
- joblib.dump(lr, model_path)
- if __name__ == "__main__":
- args = argparse.ArgumentParser()
- args.add_argument("--config", default="params.yaml")
- parsed_args = args.parse_args()
- train_and_evaluate(config_path=parsed_args.config)
|