Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

main.py 4.3 KB

You have to be logged in to leave a comment. Sign In
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
  1. import dagshub
  2. import mlflow
  3. import argparse
  4. import pandas as pd
  5. from sklearn.feature_extraction.text import TfidfVectorizer
  6. from sklearn.linear_model import SGDClassifier
  7. from sklearn.metrics import roc_auc_score, average_precision_score, accuracy_score, precision_score, recall_score, \
  8. f1_score
  9. from sklearn.model_selection import train_test_split
  10. import joblib
  11. DAGSHUB_REPO_OWNER = "<username>"
  12. DAGSHUB_REPO = "DAGsHub-Tutorial"
  13. dagshub.init(DAGSHUB_REPO, DAGSHUB_REPO_OWNER)
  14. # Consts
  15. CLASS_LABEL = 'MachineLearning'
  16. train_df_path = 'data/train.csv.zip'
  17. test_df_path = 'data/test.csv.zip'
  18. def get_or_create_experiment_id(name):
  19. exp = mlflow.get_experiment_by_name(name)
  20. if exp is None:
  21. exp_id = mlflow.create_experiment(name)
  22. return exp_id
  23. return exp.experiment_id
  24. def feature_engineering(raw_df):
  25. df = raw_df.copy()
  26. df['CreationDate'] = pd.to_datetime(df['CreationDate'])
  27. df['CreationDate_Epoch'] = df['CreationDate'].astype('int64') // 10 ** 9
  28. df = df.drop(columns=['Id', 'Tags'])
  29. df['Title_Len'] = df.Title.str.len()
  30. df['Body_Len'] = df.Body.str.len()
  31. # Drop the correlated features
  32. df = df.drop(columns=['FavoriteCount'])
  33. df['Text'] = df['Title'].fillna('') + ' ' + df['Body'].fillna('')
  34. return df
  35. def fit_tfidf(train_df, test_df):
  36. tfidf = TfidfVectorizer(max_features=25000)
  37. tfidf.fit(train_df['Text'])
  38. train_tfidf = tfidf.transform(train_df['Text'])
  39. test_tfidf = tfidf.transform(test_df['Text'])
  40. return train_tfidf, test_tfidf, tfidf
  41. def fit_model(train_X, train_y, random_state=42):
  42. clf_tfidf = SGDClassifier(loss='modified_huber', random_state=random_state)
  43. clf_tfidf.fit(train_X, train_y)
  44. return clf_tfidf
  45. def eval_model(clf, X, y):
  46. y_proba = clf.predict_proba(X)[:, 1]
  47. y_pred = clf.predict(X)
  48. return {
  49. 'roc_auc': roc_auc_score(y, y_proba),
  50. 'average_precision': average_precision_score(y, y_proba),
  51. 'accuracy': accuracy_score(y, y_pred),
  52. 'precision': precision_score(y, y_pred),
  53. 'recall': recall_score(y, y_pred),
  54. 'f1': f1_score(y, y_pred),
  55. }
  56. def split(random_state=42):
  57. print('Loading data...')
  58. df = pd.read_csv('data/CrossValidated-Questions.csv')
  59. df[CLASS_LABEL] = df['Tags'].str.contains('machine-learning').fillna(False)
  60. train_df, test_df = train_test_split(df, random_state=random_state, stratify=df[CLASS_LABEL])
  61. print('Saving split data...')
  62. train_df.to_csv(train_df_path)
  63. test_df.to_csv(test_df_path)
  64. def train():
  65. print('Loading data...')
  66. train_df = pd.read_csv(train_df_path)
  67. test_df = pd.read_csv(test_df_path)
  68. print('Engineering features...')
  69. train_df = feature_engineering(train_df)
  70. test_df = feature_engineering(test_df)
  71. exp_id = get_or_create_experiment_id("tutorial")
  72. with mlflow.start_run(experiment_id=exp_id):
  73. print('Fitting TFIDF...')
  74. train_tfidf, test_tfidf, tfidf = fit_tfidf(train_df, test_df)
  75. print('Saving TFIDF object...')
  76. joblib.dump(tfidf, 'outputs/tfidf.joblib')
  77. mlflow.log_params({f'tfidf__{k}': v for k, v in tfidf.get_params().items()})
  78. print('Training model...')
  79. train_y = train_df[CLASS_LABEL]
  80. model = fit_model(train_tfidf, train_y)
  81. print('Saving trained model...')
  82. joblib.dump(model, 'outputs/model.joblib')
  83. mlflow.log_param("model_class", type(model).__name__)
  84. mlflow.log_params({f'model__{k}': v for k, v in model.get_params().items()})
  85. print('Evaluating model...')
  86. train_metrics = eval_model(model, train_tfidf, train_y)
  87. print('Train metrics:')
  88. print(train_metrics)
  89. mlflow.log_metrics({f'train__{k}': v for k,v in train_metrics.items()})
  90. test_metrics = eval_model(model, test_tfidf, test_df[CLASS_LABEL])
  91. print('Test metrics:')
  92. print(test_metrics)
  93. mlflow.log_metrics({f'test__{k}': v for k,v in test_metrics.items()})
  94. if __name__ == '__main__':
  95. parser = argparse.ArgumentParser()
  96. subparsers = parser.add_subparsers(title='Split or Train step:', dest='step')
  97. subparsers.required = True
  98. split_parser = subparsers.add_parser('split')
  99. split_parser.set_defaults(func=split)
  100. train_parser = subparsers.add_parser('train')
  101. train_parser.set_defaults(func=train)
  102. parser.parse_args().func()
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...