jonathan-4a commited on
Commit
c96b6e4
·
verified ·
1 Parent(s): ae952dd

Upload e5_it_classifier.ipynb

Browse files
Files changed (1) hide show
  1. e5_it_classifier.ipynb +173 -0
e5_it_classifier.ipynb ADDED
@@ -0,0 +1,173 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "nbformat": 4,
3
+ "nbformat_minor": 5,
4
+ "metadata": {
5
+ "kernelspec": {
6
+ "display_name": "Python 3",
7
+ "language": "python",
8
+ "name": "python3"
9
+ },
10
+ "language_info": {
11
+ "name": "python",
12
+ "version": "3.10.0"
13
+ }
14
+ },
15
+ "cells": [
16
+ {
17
+ "cell_type": "markdown",
18
+ "metadata": {},
19
+ "source": [
20
+ "# IT vs Non-IT Job Title Classifier \u2014 `intfloat/e5-base-v2`\n",
21
+ "\n",
22
+ "Trains a logistic regression classifier on top of `intfloat/e5-base-v2` embeddings to classify job titles as IT or Non-IT. Exports the classifier head to ONNX for lightweight, runtime-friendly inference.\n",
23
+ "\n",
24
+ "**Steps:**\n",
25
+ "1. Load and split labeled job title data\n",
26
+ "2. Encode titles with e5-base-v2 (mean pool + L2 normalize)\n",
27
+ "3. Train logistic regression on embeddings\n",
28
+ "4. Evaluate on held-out test split\n",
29
+ "5. Run threshold sweep to inform deployment threshold choice\n",
30
+ "6. Export classifier to ONNX\n",
31
+ "\n",
32
+ "> \u26a0\ufe0f After running the install cell, go to **Runtime \u2192 Restart session**, then run all cells from top."
33
+ ]
34
+ },
35
+ {
36
+ "cell_type": "code",
37
+ "metadata": {},
38
+ "source": [
39
+ "# \u2500\u2500 Install \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n",
40
+ "# Restart the runtime after running this cell\n",
41
+ "!pip install -q -U transformers \"sentence-transformers[onnx]\" scikit-learn skl2onnx pandas"
42
+ ],
43
+ "outputs": [],
44
+ "execution_count": null
45
+ },
46
+ {
47
+ "cell_type": "code",
48
+ "metadata": {},
49
+ "source": [
50
+ "# \u2500\u2500 Load data \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n",
51
+ "import pandas as pd\n",
52
+ "import numpy as np\n",
53
+ "\n",
54
+ "DATA_URL = 'https://docs.google.com/spreadsheets/d/e/2PACX-1vQ2s_EXIc36mtdVCi72RY7iO380wMMEhxlhyBUeE71uBCC5fMsRlKpHgafasxcQochvQCBsQF8IuNei/pub?gid=1233103818&single=true&output=csv'\n",
55
+ "\n",
56
+ "jobs_df = pd.read_csv(DATA_URL)\n",
57
+ "jobs_df['text'] = jobs_df['job_title'].fillna('').str.strip()\n",
58
+ "\n",
59
+ "train_df = jobs_df[jobs_df['split'] == 'train'].reset_index(drop=True)\n",
60
+ "test_df = jobs_df[jobs_df['split'] == 'test'].reset_index(drop=True)\n",
61
+ "\n",
62
+ "print(f'Train: {len(train_df)} | Test: {len(test_df)}')\n",
63
+ "print(train_df['label'].value_counts())"
64
+ ],
65
+ "outputs": [],
66
+ "execution_count": null
67
+ },
68
+ {
69
+ "cell_type": "code",
70
+ "metadata": {},
71
+ "source": [
72
+ "# \u2500\u2500 Encode with e5-base-v2 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n",
73
+ "from sentence_transformers import SentenceTransformer\n",
74
+ "\n",
75
+ "encoder = SentenceTransformer('intfloat/e5-base-v2')\n",
76
+ "\n",
77
+ "def encode(texts, batch_size=500):\n",
78
+ " \"\"\"Encode texts with the e5 query prefix, mean pooling, and L2 normalization.\"\"\"\n",
79
+ " prefixed = ['query: ' + t for t in texts]\n",
80
+ " return encoder.encode(\n",
81
+ " prefixed,\n",
82
+ " batch_size=batch_size,\n",
83
+ " normalize_embeddings=True,\n",
84
+ " show_progress_bar=True,\n",
85
+ " )\n",
86
+ "\n",
87
+ "train_embs = encode(train_df['text'].tolist())\n",
88
+ "test_embs = encode(test_df['text'].tolist())\n",
89
+ "print(f'Train: {train_embs.shape} | Test: {test_embs.shape}')"
90
+ ],
91
+ "outputs": [],
92
+ "execution_count": null
93
+ },
94
+ {
95
+ "cell_type": "code",
96
+ "metadata": {},
97
+ "source": [
98
+ "# \u2500\u2500 Train logistic regression \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n",
99
+ "from sklearn.linear_model import LogisticRegression\n",
100
+ "from sklearn.metrics import classification_report, confusion_matrix, accuracy_score\n",
101
+ "\n",
102
+ "y_train = train_df['label'].tolist()\n",
103
+ "y_test = test_df['label'].tolist()\n",
104
+ "\n",
105
+ "clf = LogisticRegression(C=1.0, max_iter=1000, class_weight='balanced')\n",
106
+ "clf.fit(train_embs, y_train)\n",
107
+ "preds = clf.predict(test_embs)\n",
108
+ "\n",
109
+ "print(f'Accuracy: {accuracy_score(y_test, preds):.4f}')\n",
110
+ "print()\n",
111
+ "print(classification_report(y_test, preds, target_names=['Non-IT (0)', 'IT (1)']))\n",
112
+ "\n",
113
+ "cm = confusion_matrix(y_test, preds)\n",
114
+ "print('\u2500\u2500\u2500 Confusion Matrix \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500')\n",
115
+ "print(f'{\"\":18} Pred IT Pred Non-IT')\n",
116
+ "print(f' Actual IT {cm[1][1]:<10} {cm[1][0]} \u2190 fn: missed IT')\n",
117
+ "print(f' Actual Non-IT {cm[0][1]:<10} {cm[0][0]} \u2190 fp: Non-IT incorrectly kept')"
118
+ ],
119
+ "outputs": [],
120
+ "execution_count": null
121
+ },
122
+ {
123
+ "cell_type": "code",
124
+ "metadata": {},
125
+ "source": [
126
+ "# \u2500\u2500 Threshold sweep \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n",
127
+ "# Use this to inform your deployment threshold choice.\n",
128
+ "# Lower threshold \u2192 higher IT recall (fewer missed IT jobs, more false positives).\n",
129
+ "# Higher threshold \u2192 higher IT precision (fewer false positives, more missed IT jobs).\n",
130
+ "\n",
131
+ "probas = clf.predict_proba(test_embs)[:, 1]\n",
132
+ "y_true = np.array(y_test)\n",
133
+ "\n",
134
+ "print(f\"{'Threshold':>10} {'Accuracy':>9} {'IT Prec':>8} {'IT Rec':>8} {'NonIT Prec':>10} {'NonIT Rec':>10} {'FN':>6} {'FP':>6}\")\n",
135
+ "print('\u2500' * 85)\n",
136
+ "\n",
137
+ "for t in np.arange(0.20, 0.81, 0.05):\n",
138
+ " p = (probas >= t).astype(int)\n",
139
+ " tp_ = ((y_true==1)&(p==1)).sum()\n",
140
+ " tn_ = ((y_true==0)&(p==0)).sum()\n",
141
+ " fp_ = ((y_true==0)&(p==1)).sum()\n",
142
+ " fn_ = ((y_true==1)&(p==0)).sum()\n",
143
+ " acc_ = (tp_+tn_)/len(y_true)\n",
144
+ " it_p = tp_/(tp_+fp_) if (tp_+fp_) else 0\n",
145
+ " it_r = tp_/(tp_+fn_) if (tp_+fn_) else 0\n",
146
+ " nt_p = tn_/(tn_+fn_) if (tn_+fn_) else 0\n",
147
+ " nt_r = tn_/(tn_+fp_) if (tn_+fp_) else 0\n",
148
+ " print(f'{t:>10.2f} {acc_:>9.4f} {it_p:>8.4f} {it_r:>8.4f} {nt_p:>10.4f} {nt_r:>10.4f} {fn_:>6} {fp_:>6}')"
149
+ ],
150
+ "outputs": [],
151
+ "execution_count": null
152
+ },
153
+ {
154
+ "cell_type": "code",
155
+ "metadata": {},
156
+ "source": [
157
+ "# \u2500\u2500 Export classifier to ONNX \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n",
158
+ "from skl2onnx import convert_sklearn\n",
159
+ "from skl2onnx.common.data_types import FloatTensorType\n",
160
+ "\n",
161
+ "initial_type = [('input', FloatTensorType([None, train_embs.shape[1]]))]\n",
162
+ "onnx_clf = convert_sklearn(clf, initial_types=initial_type)\n",
163
+ "\n",
164
+ "with open('e5_it_classifier.onnx', 'wb') as f:\n",
165
+ " f.write(onnx_clf.SerializeToString())\n",
166
+ "\n",
167
+ "print(f'Saved \u2192 e5_it_classifier.onnx (embedding dim: {train_embs.shape[1]})')"
168
+ ],
169
+ "outputs": [],
170
+ "execution_count": null
171
+ }
172
+ ]
173
+ }