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": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": 1,
6
+ "id": "8495bede-ab8f-416b-b5f2-6a76b1e63935",
7
+ "metadata": {
8
+ "tags": []
9
+ },
10
+ "outputs": [
11
+ {
12
+ "name": "stderr",
13
+ "output_type": "stream",
14
+ "text": [
15
+ "D:\\Projects\\LLMs\\venv\\lib\\site-packages\\tqdm\\auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html\n",
16
+ " from .autonotebook import tqdm as notebook_tqdm\n"
17
+ ]
18
+ }
19
+ ],
20
+ "source": [
21
+ "from tqdm import tqdm\n",
22
+ "from sentence_transformers import SentenceTransformer, util"
23
+ ]
24
+ },
25
+ {
26
+ "cell_type": "code",
27
+ "execution_count": 2,
28
+ "id": "2b8cae6d-547b-4018-9f68-b0a45284b4b4",
29
+ "metadata": {
30
+ "tags": []
31
+ },
32
+ "outputs": [],
33
+ "source": [
34
+ "# model = SentenceTransformer('DMetaSoul/sbert-chinese-general-v2')\n",
35
+ "model = SentenceTransformer('TintinMeimei/menglang_yongtulv_aimatch_v1')"
36
+ ]
37
+ },
38
+ {
39
+ "cell_type": "code",
40
+ "execution_count": 3,
41
+ "id": "d3907a6f-f8ab-40fe-8702-c8cb81e189c6",
42
+ "metadata": {
43
+ "tags": []
44
+ },
45
+ "outputs": [],
46
+ "source": [
47
+ "def sim(text1, text2):\n",
48
+ " emb1 = model.encode(text1, convert_to_tensor=True)\n",
49
+ " emb2 = model.encode(text2, convert_to_tensor=True)\n",
50
+ " score = util.cos_sim(emb1, emb2)\n",
51
+ " return score"
52
+ ]
53
+ },
54
+ {
55
+ "cell_type": "code",
56
+ "execution_count": 24,
57
+ "id": "3cec9f05-4ea9-46f8-a393-950c67a0150a",
58
+ "metadata": {
59
+ "tags": []
60
+ },
61
+ "outputs": [],
62
+ "source": [
63
+ "text1 = '挂机空调'\n",
64
+ "# text2 = '1.1.11 高效节能家用电器制造\\n包括节能型房间空调器、空调机组、电冰箱、电动洗衣机、平板电视机、电风扇等家用电器制造。房间空气调节器能效优于《房间空气调节器能效限定值及能效等级》(GB 12021.3)标准1级能效水平;转速可控型房间空气调节器能效优于《转速可控型房间空气调节器能效限定值及能效等级》(GB 21455)标准1级能效水平;多联式空调(热泵)机组能效比优于《多联式空调(热泵)机组能效限定值及能源效率等级》(GB 21454)标准1级能效水平;家用电冰箱能效优于《家用电冰箱耗电量限定值及能效等级》(GB 12021.2)标准1级能效水平;电动洗衣机能效优于《电动洗衣机能效水效限定值及等级》(GB 12021.4)标准1级能效水平;电饭煲能效优于《电饭锅能效限定值及能效等级》(GB 12021.6)标准1级能效水平;平板电视机能效优于《平板电视能效限定值及能效等级》(GB 24850)标准1级能效水平;交流电风扇能效优于《交流电风扇能效限定值及能效等级》(GB 12021.9)标准1级能效水平。其他高效节能家用电器能效均优于相应国家强制性标准1级能效水平。'\n",
65
+ "# text2 = '包括节能泵、节能型真空干燥设备、节能型真空炉等设备制造。清水离心泵能效指标优于《清水离心泵能效限定值及节能评价值》(GB 19762)标准中节能评价值水平;石油化工离心泵能效优于《石油化工离心泵能效限定值及能效等级》(GB 32284)标准中1级能效水平;潜水电泵能效优于《井用潜水电泵能效限定值及能效等级》(GB 32030)、《小型潜水电泵能效限定值及能效等级》(GB 32029)、《污水污物潜水电泵能效限定值及能效等级》(GB 32031)标准中1级能效水平。'\n",
66
+ "text2 = '退耕还林'"
67
+ ]
68
+ },
69
+ {
70
+ "cell_type": "code",
71
+ "execution_count": 25,
72
+ "id": "d570bf57-2518-4306-a7ae-712e81199460",
73
+ "metadata": {
74
+ "tags": []
75
+ },
76
+ "outputs": [
77
+ {
78
+ "data": {
79
+ "text/plain": [
80
+ "tensor([[-0.5000]], device='cuda:0')"
81
+ ]
82
+ },
83
+ "execution_count": 25,
84
+ "metadata": {},
85
+ "output_type": "execute_result"
86
+ }
87
+ ],
88
+ "source": [
89
+ "sim(text1, text2)"
90
+ ]
91
+ },
92
+ {
93
+ "cell_type": "markdown",
94
+ "id": "040cc794-9bb0-4c22-986c-933ca55ee637",
95
+ "metadata": {},
96
+ "source": [
97
+ "### Process Data"
98
+ ]
99
+ },
100
+ {
101
+ "cell_type": "code",
102
+ "execution_count": 6,
103
+ "id": "d46e4e74-f7c2-4339-b009-4ba77f1b2f9a",
104
+ "metadata": {
105
+ "tags": []
106
+ },
107
+ "outputs": [
108
+ {
109
+ "data": {
110
+ "text/html": [
111
+ "<div>\n",
112
+ "<style scoped>\n",
113
+ " .dataframe tbody tr th:only-of-type {\n",
114
+ " vertical-align: middle;\n",
115
+ " }\n",
116
+ "\n",
117
+ " .dataframe tbody tr th {\n",
118
+ " vertical-align: top;\n",
119
+ " }\n",
120
+ "\n",
121
+ " .dataframe thead th {\n",
122
+ " text-align: right;\n",
123
+ " }\n",
124
+ "</style>\n",
125
+ "<table border=\"1\" class=\"dataframe\">\n",
126
+ " <thead>\n",
127
+ " <tr style=\"text-align: right;\">\n",
128
+ " <th></th>\n",
129
+ " <th>X1</th>\n",
130
+ " <th>X2</th>\n",
131
+ " <th>Y</th>\n",
132
+ " <th>Split</th>\n",
133
+ " </tr>\n",
134
+ " </thead>\n",
135
+ " <tbody>\n",
136
+ " <tr>\n",
137
+ " <th>0</th>\n",
138
+ " <td>中新制药厂空调末端送回风系统改造-询价公示</td>\n",
139
+ " <td>1.1.11 高效节能家用电器制造\\n包括节能型房间空调器、空调机组、电冰箱、电动洗衣机、平...</td>\n",
140
+ " <td>1</td>\n",
141
+ " <td>train</td>\n",
142
+ " </tr>\n",
143
+ " <tr>\n",
144
+ " <th>1</th>\n",
145
+ " <td>中新制药厂空调末端送回风系统改造-询价公示</td>\n",
146
+ " <td>1.5.1 锅炉(窑炉)节能改造和能效提升\\n包括燃煤锅炉“以大代小”,采用先进燃煤锅炉、节...</td>\n",
147
+ " <td>0</td>\n",
148
+ " <td>train</td>\n",
149
+ " </tr>\n",
150
+ " </tbody>\n",
151
+ "</table>\n",
152
+ "</div>"
153
+ ],
154
+ "text/plain": [
155
+ " X1 X2 \\\n",
156
+ "0 中新制药厂空调末端送回风系统改造-询价公示 1.1.11 高效节能家用电器制造\\n包括节能型房间空调器、空调机组、电冰箱、电动洗衣机、平... \n",
157
+ "1 中新制药厂空调末端送回风系统改造-询价公示 1.5.1 锅炉(窑炉)节能改造和能效提升\\n包括燃煤锅炉“以大代小”,采用先进燃煤锅炉、节... \n",
158
+ "\n",
159
+ " Y Split \n",
160
+ "0 1 train \n",
161
+ "1 0 train "
162
+ ]
163
+ },
164
+ "execution_count": 6,
165
+ "metadata": {},
166
+ "output_type": "execute_result"
167
+ }
168
+ ],
169
+ "source": [
170
+ "import pandas as pd\n",
171
+ "\n",
172
+ "df_data = pd.read_excel('AI匹配算法样本.xlsx', sheet_name='Sheet1', dtype=str)\n",
173
+ "df_data.head(2)"
174
+ ]
175
+ },
176
+ {
177
+ "cell_type": "code",
178
+ "execution_count": 7,
179
+ "id": "673ce0e0-2801-4bb3-8e5d-5c4aff3ac725",
180
+ "metadata": {
181
+ "tags": []
182
+ },
183
+ "outputs": [
184
+ {
185
+ "name": "stderr",
186
+ "output_type": "stream",
187
+ "text": [
188
+ "C:\\Users\\vermouth\\AppData\\Local\\Temp\\ipykernel_22160\\3257358016.py:1: FutureWarning: Using short name for 'orient' is deprecated. Only the options: ('dict', list, 'series', 'split', 'records', 'index') will be used in a future version. Use one of the above to silence this warning.\n",
189
+ " train_data = [item for item in df_data.to_dict(orient='record') if item['Split']=='train']\n",
190
+ "C:\\Users\\vermouth\\AppData\\Local\\Temp\\ipykernel_22160\\3257358016.py:2: FutureWarning: Using short name for 'orient' is deprecated. Only the options: ('dict', list, 'series', 'split', 'records', 'index') will be used in a future version. Use one of the above to silence this warning.\n",
191
+ " eval_data = [item for item in df_data.to_dict(orient='record') if item['Split']=='eval']\n",
192
+ "C:\\Users\\vermouth\\AppData\\Local\\Temp\\ipykernel_22160\\3257358016.py:3: FutureWarning: Using short name for 'orient' is deprecated. Only the options: ('dict', list, 'series', 'split', 'records', 'index') will be used in a future version. Use one of the above to silence this warning.\n",
193
+ " test_data = [item for item in df_data.to_dict(orient='record') if item['Split']=='test']\n"
194
+ ]
195
+ }
196
+ ],
197
+ "source": [
198
+ "train_data = [item for item in df_data.to_dict(orient='record') if item['Split']=='train']\n",
199
+ "eval_data = [item for item in df_data.to_dict(orient='record') if item['Split']=='eval']\n",
200
+ "test_data = [item for item in df_data.to_dict(orient='record') if item['Split']=='test']"
201
+ ]
202
+ },
203
+ {
204
+ "cell_type": "markdown",
205
+ "id": "5037803d-980d-48a1-a61d-528bb9508ce0",
206
+ "metadata": {},
207
+ "source": [
208
+ "### Model 1 - Fine tune a Sentence Transformer"
209
+ ]
210
+ },
211
+ {
212
+ "cell_type": "code",
213
+ "execution_count": 8,
214
+ "id": "773429e9-57ce-418f-ad44-3c35d1b31a74",
215
+ "metadata": {},
216
+ "outputs": [],
217
+ "source": [
218
+ "# from sentence_transformers import InputExample, losses\n",
219
+ "# from torch.utils.data import DataLoader\n",
220
+ "\n",
221
+ "# # Prepare data\n",
222
+ "# train_data_sbert = []\n",
223
+ "# eval_data_sbert = []\n",
224
+ "# test_data_sbert = []\n",
225
+ "\n",
226
+ "# for item in train_data:\n",
227
+ "# label = 1.0 if float(item.get('Y')) == 1 else -1.0\n",
228
+ "# train_data_sbert.append(InputExample(texts=[item.get('X1'), item.get('X2')], label=label))\n",
229
+ "# train_dataloader = DataLoader(train_data_sbert, shuffle=True, batch_size=2)\n",
230
+ "# train_loss = losses.CosineSimilarityLoss(model)"
231
+ ]
232
+ },
233
+ {
234
+ "cell_type": "code",
235
+ "execution_count": 9,
236
+ "id": "ec1b68cb-bec3-4896-b196-ec31b1132ad1",
237
+ "metadata": {},
238
+ "outputs": [],
239
+ "source": [
240
+ "# from sentence_transformers import evaluation\n",
241
+ "# evaluator = evaluation.EmbeddingSimilarityEvaluator([item.get('X1') for item in eval_data], [item.get('X2') for item in eval_data], [1.0 if float(item.get('Y'))==1 else -1.0 for item in eval_data])"
242
+ ]
243
+ },
244
+ {
245
+ "cell_type": "code",
246
+ "execution_count": 10,
247
+ "id": "7c05c6ef-c5e7-416b-b797-9f8735ae5436",
248
+ "metadata": {},
249
+ "outputs": [],
250
+ "source": [
251
+ "# model.fit(train_objectives=[(train_dataloader, train_loss)], epochs=1, warmup_steps=100, evaluator=evaluator, evaluation_steps=500)"
252
+ ]
253
+ },
254
+ {
255
+ "cell_type": "code",
256
+ "execution_count": 11,
257
+ "id": "7de1e5f0-4b83-4d34-8385-77cdaa0ef08f",
258
+ "metadata": {},
259
+ "outputs": [],
260
+ "source": [
261
+ "# model.save('./tmp_model')"
262
+ ]
263
+ },
264
+ {
265
+ "cell_type": "markdown",
266
+ "id": "fdd686b1-c654-4135-8989-05f23c914afa",
267
+ "metadata": {
268
+ "tags": []
269
+ },
270
+ "source": [
271
+ "### Model 2 - No Fine Tune + Threshold Tuning"
272
+ ]
273
+ },
274
+ {
275
+ "cell_type": "code",
276
+ "execution_count": 12,
277
+ "id": "a0247889-577d-4a92-8c0f-9c923748df93",
278
+ "metadata": {
279
+ "tags": []
280
+ },
281
+ "outputs": [],
282
+ "source": [
283
+ "def sim(text1, text2):\n",
284
+ " emb1 = model.encode(text1, convert_to_tensor=True)\n",
285
+ " emb2 = model.encode(text2, convert_to_tensor=True)\n",
286
+ " score = util.cos_sim(emb1, emb2)\n",
287
+ " return score\n",
288
+ "\n",
289
+ "def _acc_thres(scores, thres):\n",
290
+ " correct = 0\n",
291
+ " total = len(scores)\n",
292
+ " for score, truth in scores:\n",
293
+ " truth = float(truth)\n",
294
+ " pred = 1 if score >= thres else 0\n",
295
+ " if pred == truth:\n",
296
+ " correct += 1\n",
297
+ " return round(correct/total, 3)\n",
298
+ "\n",
299
+ "def model_train(train_data, eval_data):\n",
300
+ " score_train = []\n",
301
+ " score_eval = []\n",
302
+ " for item in tqdm(train_data):\n",
303
+ " score = sim(item['X1'], item['X2'])\n",
304
+ " score_train.append((score, item['Y']))\n",
305
+ " for item in tqdm(eval_data):\n",
306
+ " score = sim(item['X1'], item['X2'])\n",
307
+ " score_eval.append((score, item['Y']))\n",
308
+ " # find threshold that minize train error\n",
309
+ " score_train = sorted(score_train, reverse=True)\n",
310
+ " win_acc = -1\n",
311
+ " win_thres = -1\n",
312
+ " for thres in range(5, 100, 5):\n",
313
+ " thres = thres*0.01\n",
314
+ " acc = _acc_thres(score_train, thres)\n",
315
+ " if acc > win_acc:\n",
316
+ " win_acc = acc\n",
317
+ " win_thres = thres\n",
318
+ " eval_acc = _acc_thres(score_eval, win_thres)\n",
319
+ " return {'thres': win_thres, 'train_accuracy': win_acc, 'eval_accuracy': eval_acc}"
320
+ ]
321
+ },
322
+ {
323
+ "cell_type": "code",
324
+ "execution_count": 13,
325
+ "id": "4e943ef9-ad40-494e-9d53-db9ccbf48bb4",
326
+ "metadata": {
327
+ "tags": []
328
+ },
329
+ "outputs": [
330
+ {
331
+ "name": "stderr",
332
+ "output_type": "stream",
333
+ "text": [
334
+ "100%|█████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 12256/12256 [13:54<00:00, 14.69it/s]\n",
335
+ "100%|██████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 4248/4248 [04:44<00:00, 14.94it/s]\n"
336
+ ]
337
+ }
338
+ ],
339
+ "source": [
340
+ "r = model_train(train_data, eval_data)"
341
+ ]
342
+ },
343
+ {
344
+ "cell_type": "code",
345
+ "execution_count": 14,
346
+ "id": "9cd38cc9-fe71-45b9-a22e-977a2e787fb5",
347
+ "metadata": {
348
+ "tags": []
349
+ },
350
+ "outputs": [
351
+ {
352
+ "data": {
353
+ "text/plain": [
354
+ "{'thres': 0.25, 'train_accuracy': 0.831, 'eval_accuracy': 0.816}"
355
+ ]
356
+ },
357
+ "execution_count": 14,
358
+ "metadata": {},
359
+ "output_type": "execute_result"
360
+ }
361
+ ],
362
+ "source": [
363
+ "r"
364
+ ]
365
+ },
366
+ {
367
+ "cell_type": "code",
368
+ "execution_count": 15,
369
+ "id": "53622ff1-7465-4663-a9f0-0c18df37b93e",
370
+ "metadata": {
371
+ "tags": []
372
+ },
373
+ "outputs": [
374
+ {
375
+ "name": "stderr",
376
+ "output_type": "stream",
377
+ "text": [
378
+ "100%|██████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 4468/4468 [04:58<00:00, 14.98it/s]\n"
379
+ ]
380
+ }
381
+ ],
382
+ "source": [
383
+ "score_test = []\n",
384
+ "for item in tqdm(test_data):\n",
385
+ " score = sim(item['X1'], item['X2'])\n",
386
+ " score_test.append((score, item['Y']))"
387
+ ]
388
+ },
389
+ {
390
+ "cell_type": "code",
391
+ "execution_count": 17,
392
+ "id": "47411f71-c774-4274-a1af-2a128589b559",
393
+ "metadata": {
394
+ "tags": []
395
+ },
396
+ "outputs": [
397
+ {
398
+ "data": {
399
+ "text/plain": [
400
+ "0.815"
401
+ ]
402
+ },
403
+ "execution_count": 17,
404
+ "metadata": {},
405
+ "output_type": "execute_result"
406
+ }
407
+ ],
408
+ "source": [
409
+ "_acc_thres(score_test, r['thres'])\n",
410
+ "#_acc_thres(score_test, 0.25)"
411
+ ]
412
+ },
413
+ {
414
+ "cell_type": "code",
415
+ "execution_count": null,
416
+ "id": "59b741bc-7a20-4ed0-bc9d-b82ec3edff34",
417
+ "metadata": {},
418
+ "outputs": [],
419
+ "source": []
420
+ }
421
+ ],
422
+ "metadata": {
423
+ "kernelspec": {
424
+ "display_name": "Python 3 (ipykernel)",
425
+ "language": "python",
426
+ "name": "python3"
427
+ },
428
+ "language_info": {
429
+ "codemirror_mode": {
430
+ "name": "ipython",
431
+ "version": 3
432
+ },
433
+ "file_extension": ".py",
434
+ "mimetype": "text/x-python",
435
+ "name": "python",
436
+ "nbconvert_exporter": "python",
437
+ "pygments_lexer": "ipython3",
438
+ "version": "3.10.0"
439
+ }
440
+ },
441
+ "nbformat": 4,
442
+ "nbformat_minor": 5
443
+ }