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 3.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
  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. # Consts
  10. CLASS_LABEL = 'label'
  11. train_df_path = 'data/train.csv.zip'
  12. test_df_path = 'data/test.csv.zip'
  13. def feature_engineering(raw_df):
  14. df = raw_df.copy()
  15. df['len'] = df.comment.str.len()
  16. df['comment'] = df['comment'].fillna('')
  17. df = df.drop(columns=['isHate'])
  18. return df
  19. def fit_tfidf(train_df, test_df):
  20. tfidf = TfidfVectorizer(max_features=25000)
  21. tfidf.fit(train_df['comment'])
  22. train_tfidf = tfidf.transform(train_df['comment'])
  23. test_tfidf = tfidf.transform(test_df['comment'])
  24. return train_tfidf, test_tfidf, tfidf
  25. def fit_model(train_X, train_y, random_state=42):
  26. clf_tfidf = SGDClassifier(loss='modified_huber', random_state=random_state)
  27. clf_tfidf.fit(train_X, train_y)
  28. return clf_tfidf
  29. def eval_model(clf, X, y):
  30. y_proba = clf.predict_proba(X)[:, 1]
  31. y_pred = clf.predict(X)
  32. return {
  33. 'roc_auc': roc_auc_score(y, y_proba),
  34. 'average_precision': average_precision_score(y, y_proba),
  35. 'accuracy': accuracy_score(y, y_pred),
  36. 'precision': precision_score(y, y_pred),
  37. 'recall': recall_score(y, y_pred),
  38. 'f1': f1_score(y, y_pred),
  39. }
  40. def split(random_state=42):
  41. print('Loading data...')
  42. df = pd.read_csv('data/Ethos_Dataset_Binary.csv', delimiter=';')
  43. df[CLASS_LABEL] = df.isHate.apply(lambda x: float(x>=0.5))
  44. # df[CLASS_LABEL] = df['Tags'].str.contains('machine-learning').fillna(False)
  45. train_df, test_df = train_test_split(df, random_state=random_state, stratify=df[CLASS_LABEL])
  46. print('Saving split data...')
  47. train_df.to_csv(train_df_path)
  48. test_df.to_csv(test_df_path)
  49. def train():
  50. print('Loading data...')
  51. train_df = pd.read_csv(train_df_path)
  52. test_df = pd.read_csv(test_df_path)
  53. print('Engineering features...')
  54. train_df = feature_engineering(train_df)
  55. test_df = feature_engineering(test_df)
  56. print('Fitting TFIDF...')
  57. train_tfidf, test_tfidf, tfidf = fit_tfidf(train_df, test_df)
  58. print('Saving TFIDF object...')
  59. joblib.dump(tfidf, 'outputs/tfidf.joblib')
  60. print('Training model...')
  61. train_y = train_df[CLASS_LABEL]
  62. model = fit_model(train_tfidf, train_y)
  63. print('Saving trained model...')
  64. joblib.dump(model, 'outputs/model.joblib')
  65. print('Evaluating model...')
  66. train_metrics = eval_model(model, train_tfidf, train_y)
  67. print('Train metrics:')
  68. print(train_metrics)
  69. test_metrics = eval_model(model, test_tfidf, test_df[CLASS_LABEL])
  70. print('Test metrics:')
  71. print(test_metrics)
  72. if __name__ == '__main__':
  73. parser = argparse.ArgumentParser()
  74. subparsers = parser.add_subparsers(title='Split or Train step:', dest='step')
  75. subparsers.required = True
  76. split_parser = subparsers.add_parser('split')
  77. split_parser.set_defaults(func=split)
  78. train_parser = subparsers.add_parser('train')
  79. train_parser.set_defaults(func=train)
  80. parser.parse_args().func()
Tip!

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

Comments

Loading...