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

featurization.py 4.1 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
131
132
133
134
135
136
  1. import os
  2. import pickle
  3. import sys
  4. import numpy as np
  5. import pandas as pd
  6. import scipy.sparse as sparse
  7. import yaml
  8. from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer
  9. def get_df(data):
  10. """Read the input data file and return a data frame."""
  11. df = pd.read_csv(
  12. data,
  13. encoding="utf-8",
  14. header=None,
  15. delimiter="\t",
  16. names=["id", "label", "text"],
  17. )
  18. sys.stderr.write(f"The input data frame {data} size is {df.shape}\n")
  19. return df
  20. def save_matrix(df, matrix, names, output):
  21. """
  22. Save the matrix to a pickle file.
  23. Args:
  24. df (pandas.DataFrame): Input data frame.
  25. matrix (scipy.sparse.csr_matrix): Input matrix.
  26. names (list): List of feature names.
  27. output (str): Output file name.
  28. """
  29. id_matrix = sparse.csr_matrix(df.id.astype(np.int64)).T
  30. label_matrix = sparse.csr_matrix(df.label.astype(np.int64)).T
  31. result = sparse.hstack([id_matrix, label_matrix, matrix], format="csr")
  32. msg = "The output matrix {} size is {} and data type is {}\n"
  33. sys.stderr.write(msg.format(output, result.shape, result.dtype))
  34. with open(output, "wb") as fd:
  35. pickle.dump((result, names), fd)
  36. pass
  37. def generate_and_save_train_features(train_input, train_output, bag_of_words, tfidf):
  38. """
  39. Generate train feature matrix.
  40. Args:
  41. train_input (str): Train input file name.
  42. train_output (str): Train output file name.
  43. bag_of_words (sklearn.feature_extraction.text.CountVectorizer): Bag of words.
  44. tfidf (sklearn.feature_extraction.text.TfidfTransformer): TF-IDF transformer.
  45. """
  46. df_train = get_df(train_input)
  47. train_words = np.array(df_train.text.str.lower().values)
  48. bag_of_words.fit(train_words)
  49. train_words_binary_matrix = bag_of_words.transform(train_words)
  50. feature_names = bag_of_words.get_feature_names_out()
  51. tfidf.fit(train_words_binary_matrix)
  52. train_words_tfidf_matrix = tfidf.transform(train_words_binary_matrix)
  53. save_matrix(df_train, train_words_tfidf_matrix, feature_names, train_output)
  54. def generate_and_save_test_features(test_input, test_output, bag_of_words, tfidf):
  55. """
  56. Generate test feature matrix.
  57. Args:
  58. test_input (str): Test input file name.
  59. test_output (str): Test output file name.
  60. bag_of_words (sklearn.feature_extraction.text.CountVectorizer): Bag of words.
  61. tfidf (sklearn.feature_extraction.text.TfidfTransformer): TF-IDF transformer.
  62. """
  63. df_test = get_df(test_input)
  64. test_words = np.array(df_test.text.str.lower().values)
  65. test_words_binary_matrix = bag_of_words.transform(test_words)
  66. test_words_tfidf_matrix = tfidf.transform(test_words_binary_matrix)
  67. feature_names = bag_of_words.get_feature_names_out()
  68. save_matrix(df_test, test_words_tfidf_matrix, feature_names, test_output)
  69. def main():
  70. params = yaml.safe_load(open("params.yaml"))["featurize"]
  71. np.set_printoptions(suppress=True)
  72. if len(sys.argv) != 3 and len(sys.argv) != 5:
  73. sys.stderr.write("Arguments error. Usage:\n")
  74. sys.stderr.write("\tpython featurization.py data-dir-path features-dir-path\n")
  75. sys.exit(1)
  76. in_path = sys.argv[1]
  77. out_path = sys.argv[2]
  78. train_input = os.path.join(in_path, "train.tsv")
  79. test_input = os.path.join(in_path, "test.tsv")
  80. train_output = os.path.join(out_path, "train.pkl")
  81. test_output = os.path.join(out_path, "test.pkl")
  82. max_features = params["max_features"]
  83. ngrams = params["ngrams"]
  84. os.makedirs(out_path, exist_ok=True)
  85. bag_of_words = CountVectorizer(
  86. stop_words="english", max_features=max_features, ngram_range=(1, ngrams)
  87. )
  88. tfidf = TfidfTransformer(smooth_idf=False)
  89. generate_and_save_train_features(
  90. train_input=train_input,
  91. train_output=train_output,
  92. bag_of_words=bag_of_words,
  93. tfidf=tfidf,
  94. )
  95. generate_and_save_test_features(
  96. test_input=test_input,
  97. test_output=test_output,
  98. bag_of_words=bag_of_words,
  99. tfidf=tfidf,
  100. )
  101. if __name__ == "__main__":
  102. main()
Tip!

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

Comments

Loading...