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

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

Comments

Loading...