Spaces:
Sleeping
Sleeping
File size: 73,203 Bytes
169057e |
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 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 |
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# TF-IDF"
]
},
{
"cell_type": "code",
"execution_count": 50,
"metadata": {},
"outputs": [],
"source": [
"import numpy as np\n",
"import pandas as pd\n",
"import re\n",
"import string\n",
"from collections import defaultdict\n",
"from sklearn import metrics\n",
"from time import time\n",
"from nltk.corpus import stopwords\n",
"from nltk.stem import WordNetLemmatizer\n",
"from nltk.tokenize import RegexpTokenizer\n",
"from sklearn.feature_extraction.text import TfidfVectorizer\n",
"from sklearn.cluster import KMeans\n",
"from sklearn.datasets import fetch_20newsgroups\n",
"from sklearn.decomposition import TruncatedSVD\n",
"from sklearn.pipeline import make_pipeline\n",
"from sklearn.preprocessing import Normalizer\n",
"import pymorphy2\n",
"from sklearn.model_selection import train_test_split\n",
"from sklearn.linear_model import LogisticRegression\n",
"from sklearn.metrics import classification_report, accuracy_score, f1_score"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Загрузка данных"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [],
"source": [
"df = pd.read_json('data/healthcare_facilities_reviews.jsonl', lines=True)"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"<div>\n",
"<style scoped>\n",
" .dataframe tbody tr th:only-of-type {\n",
" vertical-align: middle;\n",
" }\n",
"\n",
" .dataframe tbody tr th {\n",
" vertical-align: top;\n",
" }\n",
"\n",
" .dataframe thead th {\n",
" text-align: right;\n",
" }\n",
"</style>\n",
"<table border=\"1\" class=\"dataframe\">\n",
" <thead>\n",
" <tr style=\"text-align: right;\">\n",
" <th></th>\n",
" <th>review_id</th>\n",
" <th>category</th>\n",
" <th>title</th>\n",
" <th>content</th>\n",
" <th>sentiment</th>\n",
" <th>source_url</th>\n",
" </tr>\n",
" </thead>\n",
" <tbody>\n",
" <tr>\n",
" <th>0</th>\n",
" <td>0</td>\n",
" <td>Поликлиники стоматологические</td>\n",
" <td>Классный мастер</td>\n",
" <td>Огромное спасибо за чудесное удаление двух зуб...</td>\n",
" <td>positive</td>\n",
" <td>http://www.spr.ru/forum_vyvod.php?id_tema=2727539</td>\n",
" </tr>\n",
" <tr>\n",
" <th>1</th>\n",
" <td>1</td>\n",
" <td>Поликлиники стоматологические</td>\n",
" <td>Замечательный врач</td>\n",
" <td>Хочу выразить особую благодарность замечательн...</td>\n",
" <td>positive</td>\n",
" <td>http://www.spr.ru/forum_vyvod.php?id_tema=2302877</td>\n",
" </tr>\n",
" <tr>\n",
" <th>2</th>\n",
" <td>2</td>\n",
" <td>Поликлиники стоматологические</td>\n",
" <td>Благодарность работникам рентгена</td>\n",
" <td>Добрый вечер! Хотелось бы поблагодарить сотруд...</td>\n",
" <td>positive</td>\n",
" <td>http://www.spr.ru/forum_vyvod.php?id_tema=2815031</td>\n",
" </tr>\n",
" <tr>\n",
" <th>3</th>\n",
" <td>3</td>\n",
" <td>Поликлиники стоматологические</td>\n",
" <td>Доктор Рабинович</td>\n",
" <td>Женщины советского образца в регистратуре не и...</td>\n",
" <td>negative</td>\n",
" <td>http://www.spr.ru/forum_vyvod.php?id_tema=3443161</td>\n",
" </tr>\n",
" <tr>\n",
" <th>4</th>\n",
" <td>4</td>\n",
" <td>Поликлиники стоматологические</td>\n",
" <td>Есть кому сказать спасибо</td>\n",
" <td>У меня с детства очень плохие зубы (тонкая и х...</td>\n",
" <td>positive</td>\n",
" <td>http://www.spr.ru/forum_vyvod.php?id_tema=2592430</td>\n",
" </tr>\n",
" <tr>\n",
" <th>...</th>\n",
" <td>...</td>\n",
" <td>...</td>\n",
" <td>...</td>\n",
" <td>...</td>\n",
" <td>...</td>\n",
" <td>...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>70592</th>\n",
" <td>70592</td>\n",
" <td>Водительские комиссии</td>\n",
" <td>Хуже районной поликлиники</td>\n",
" <td>Заведение ужасное. Врачи делят 1 кабинет на 2х...</td>\n",
" <td>negative</td>\n",
" <td>http://www.spr.ru/forum_vyvod.php?id_tema=273326</td>\n",
" </tr>\n",
" <tr>\n",
" <th>70593</th>\n",
" <td>70593</td>\n",
" <td>Водительские комиссии</td>\n",
" <td>Справки</td>\n",
" <td>Люди, не обращайтесь в эту фирму! Муж проходил...</td>\n",
" <td>negative</td>\n",
" <td>http://www.spr.ru/forum_vyvod.php?id_tema=3401583</td>\n",
" </tr>\n",
" <tr>\n",
" <th>70594</th>\n",
" <td>70594</td>\n",
" <td>Водительские комиссии</td>\n",
" <td>Мед-Альфа - это наше будущее</td>\n",
" <td>Дорогие посетители медицинского центра ООО \"Ме...</td>\n",
" <td>positive</td>\n",
" <td>http://www.spr.ru/forum_vyvod.php?id_tema=326078</td>\n",
" </tr>\n",
" <tr>\n",
" <th>70595</th>\n",
" <td>70595</td>\n",
" <td>Водительские комиссии</td>\n",
" <td>Хамское поведение</td>\n",
" <td>В регистратуре сидит хамка, такое отношение и ...</td>\n",
" <td>negative</td>\n",
" <td>http://www.spr.ru/forum_vyvod.php?id_tema=3171911</td>\n",
" </tr>\n",
" <tr>\n",
" <th>70596</th>\n",
" <td>70596</td>\n",
" <td>Водительские комиссии</td>\n",
" <td>Только хорошие впечатления</td>\n",
" <td>Хочу поблагодарить весь персонал \"МедАльфаПроф...</td>\n",
" <td>positive</td>\n",
" <td>http://www.spr.ru/forum_vyvod.php?id_tema=3391562</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>\n",
"<p>70597 rows × 6 columns</p>\n",
"</div>"
],
"text/plain": [
" review_id category \\\n",
"0 0 Поликлиники стоматологические \n",
"1 1 Поликлиники стоматологические \n",
"2 2 Поликлиники стоматологические \n",
"3 3 Поликлиники стоматологические \n",
"4 4 Поликлиники стоматологические \n",
"... ... ... \n",
"70592 70592 Водительские комиссии \n",
"70593 70593 Водительские комиссии \n",
"70594 70594 Водительские комиссии \n",
"70595 70595 Водительские комиссии \n",
"70596 70596 Водительские комиссии \n",
"\n",
" title \\\n",
"0 Классный мастер \n",
"1 Замечательный врач \n",
"2 Благодарность работникам рентгена \n",
"3 Доктор Рабинович \n",
"4 Есть кому сказать спасибо \n",
"... ... \n",
"70592 Хуже районной поликлиники \n",
"70593 Справки \n",
"70594 Мед-Альфа - это наше будущее \n",
"70595 Хамское поведение \n",
"70596 Только хорошие впечатления \n",
"\n",
" content sentiment \\\n",
"0 Огромное спасибо за чудесное удаление двух зуб... positive \n",
"1 Хочу выразить особую благодарность замечательн... positive \n",
"2 Добрый вечер! Хотелось бы поблагодарить сотруд... positive \n",
"3 Женщины советского образца в регистратуре не и... negative \n",
"4 У меня с детства очень плохие зубы (тонкая и х... positive \n",
"... ... ... \n",
"70592 Заведение ужасное. Врачи делят 1 кабинет на 2х... negative \n",
"70593 Люди, не обращайтесь в эту фирму! Муж проходил... negative \n",
"70594 Дорогие посетители медицинского центра ООО \"Ме... positive \n",
"70595 В регистратуре сидит хамка, такое отношение и ... negative \n",
"70596 Хочу поблагодарить весь персонал \"МедАльфаПроф... positive \n",
"\n",
" source_url \n",
"0 http://www.spr.ru/forum_vyvod.php?id_tema=2727539 \n",
"1 http://www.spr.ru/forum_vyvod.php?id_tema=2302877 \n",
"2 http://www.spr.ru/forum_vyvod.php?id_tema=2815031 \n",
"3 http://www.spr.ru/forum_vyvod.php?id_tema=3443161 \n",
"4 http://www.spr.ru/forum_vyvod.php?id_tema=2592430 \n",
"... ... \n",
"70592 http://www.spr.ru/forum_vyvod.php?id_tema=273326 \n",
"70593 http://www.spr.ru/forum_vyvod.php?id_tema=3401583 \n",
"70594 http://www.spr.ru/forum_vyvod.php?id_tema=326078 \n",
"70595 http://www.spr.ru/forum_vyvod.php?id_tema=3171911 \n",
"70596 http://www.spr.ru/forum_vyvod.php?id_tema=3391562 \n",
"\n",
"[70597 rows x 6 columns]"
]
},
"execution_count": 8,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"df"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [],
"source": [
"df = df[['sentiment', 'content']]"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"<div>\n",
"<style scoped>\n",
" .dataframe tbody tr th:only-of-type {\n",
" vertical-align: middle;\n",
" }\n",
"\n",
" .dataframe tbody tr th {\n",
" vertical-align: top;\n",
" }\n",
"\n",
" .dataframe thead th {\n",
" text-align: right;\n",
" }\n",
"</style>\n",
"<table border=\"1\" class=\"dataframe\">\n",
" <thead>\n",
" <tr style=\"text-align: right;\">\n",
" <th></th>\n",
" <th>sentiment</th>\n",
" <th>content</th>\n",
" </tr>\n",
" </thead>\n",
" <tbody>\n",
" <tr>\n",
" <th>0</th>\n",
" <td>positive</td>\n",
" <td>Огромное спасибо за чудесное удаление двух зуб...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>1</th>\n",
" <td>positive</td>\n",
" <td>Хочу выразить особую благодарность замечательн...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>2</th>\n",
" <td>positive</td>\n",
" <td>Добрый вечер! Хотелось бы поблагодарить сотруд...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>3</th>\n",
" <td>negative</td>\n",
" <td>Женщины советского образца в регистратуре не и...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>4</th>\n",
" <td>positive</td>\n",
" <td>У меня с детства очень плохие зубы (тонкая и х...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>...</th>\n",
" <td>...</td>\n",
" <td>...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>70592</th>\n",
" <td>negative</td>\n",
" <td>Заведение ужасное. Врачи делят 1 кабинет на 2х...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>70593</th>\n",
" <td>negative</td>\n",
" <td>Люди, не обращайтесь в эту фирму! Муж проходил...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>70594</th>\n",
" <td>positive</td>\n",
" <td>Дорогие посетители медицинского центра ООО \"Ме...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>70595</th>\n",
" <td>negative</td>\n",
" <td>В регистратуре сидит хамка, такое отношение и ...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>70596</th>\n",
" <td>positive</td>\n",
" <td>Хочу поблагодарить весь персонал \"МедАльфаПроф...</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>\n",
"<p>70597 rows × 2 columns</p>\n",
"</div>"
],
"text/plain": [
" sentiment content\n",
"0 positive Огромное спасибо за чудесное удаление двух зуб...\n",
"1 positive Хочу выразить особую благодарность замечательн...\n",
"2 positive Добрый вечер! Хотелось бы поблагодарить сотруд...\n",
"3 negative Женщины советского образца в регистратуре не и...\n",
"4 positive У меня с детства очень плохие зубы (тонкая и х...\n",
"... ... ...\n",
"70592 negative Заведение ужасное. Врачи делят 1 кабинет на 2х...\n",
"70593 negative Люди, не обращайтесь в эту фирму! Муж проходил...\n",
"70594 positive Дорогие посетители медицинского центра ООО \"Ме...\n",
"70595 negative В регистратуре сидит хамка, такое отношение и ...\n",
"70596 positive Хочу поблагодарить весь персонал \"МедАльфаПроф...\n",
"\n",
"[70597 rows x 2 columns]"
]
},
"execution_count": 10,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"df"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'Добрый вечер! Хотелось бы поблагодарить сотрудников рентгена! Протезируюсь, отношусь к поликлинике № 189. Там меня отфутболили! Подходила к Кочину, зам. гл. врачу, заведующей просто сделать 3 снимка (пол-ка рядом с домом)- мне грубо отказали! А сотрудник рентгена просто сидела кроссворд разгадывала! Они видите ли, не принимают с протезирования! Сказали, где протезируетесь, там и делайте, а я говорю, мне у Вас удобно. Побоялись они! Первый раз попала к молодой девушке, она меня выслушала и сделала 1 снимок, а потом записала на другие дни, мне это удобно. Конечно, народу полно было! Бедные сотрудники. Все, кто читает отзыв (особенно жители Люблино 189 пол-ки), давайте жаловаться в департамент! Спасибо еще раз, за рентген (слышала в очереди, что народу у Вас было много и вы уже перебрали с нормой). Спасибо.'"
]
},
"execution_count": 12,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"df['content'][2]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Очистка текста"
]
},
{
"cell_type": "code",
"execution_count": 25,
"metadata": {},
"outputs": [],
"source": [
"morph = pymorphy2.MorphAnalyzer()\n",
"russian_stopwords = stopwords.words(\"russian\")"
]
},
{
"cell_type": "code",
"execution_count": 26,
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"/tmp/ipykernel_75887/650983554.py:12: SettingWithCopyWarning: \n",
"A value is trying to be set on a copy of a slice from a DataFrame.\n",
"Try using .loc[row_indexer,col_indexer] = value instead\n",
"\n",
"See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n",
" df['cleaned_text'] = df['content'].apply(clean_text)\n"
]
}
],
"source": [
"def clean_text(text):\n",
" # Удаление всего, что не является буквами или знаками препинания\n",
" clean_pattern = re.compile(r'[^a-zA-Zа-яА-ЯёЁ0-9.,!?;:\\s]')\n",
" text = clean_pattern.sub('', text)\n",
" url_pattern = re.compile(r'http\\S+|www\\S+|https\\S+')\n",
" text = url_pattern.sub(r'', text)\n",
" text = text.translate(str.maketrans('', '', string.punctuation))\n",
" text = text.lower()\n",
" lemmatized_text = ' '.join([morph.parse(word)[0].normal_form for word in text.split() if word not in russian_stopwords])\n",
" return lemmatized_text\n",
"\n",
"df['cleaned_text'] = df['content'].apply(clean_text)"
]
},
{
"cell_type": "code",
"execution_count": 28,
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"<div>\n",
"<style scoped>\n",
" .dataframe tbody tr th:only-of-type {\n",
" vertical-align: middle;\n",
" }\n",
"\n",
" .dataframe tbody tr th {\n",
" vertical-align: top;\n",
" }\n",
"\n",
" .dataframe thead th {\n",
" text-align: right;\n",
" }\n",
"</style>\n",
"<table border=\"1\" class=\"dataframe\">\n",
" <thead>\n",
" <tr style=\"text-align: right;\">\n",
" <th></th>\n",
" <th>sentiment</th>\n",
" <th>content</th>\n",
" <th>cleaned_text</th>\n",
" </tr>\n",
" </thead>\n",
" <tbody>\n",
" <tr>\n",
" <th>0</th>\n",
" <td>positive</td>\n",
" <td>Огромное спасибо за чудесное удаление двух зуб...</td>\n",
" <td>огромный спасибо чудесный удаление два зуб муд...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>1</th>\n",
" <td>positive</td>\n",
" <td>Хочу выразить особую благодарность замечательн...</td>\n",
" <td>хотеть выразить особый благодарность замечател...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>2</th>\n",
" <td>positive</td>\n",
" <td>Добрый вечер! Хотелось бы поблагодарить сотруд...</td>\n",
" <td>добрый вечер хотеться поблагодарить сотрудник ...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>3</th>\n",
" <td>negative</td>\n",
" <td>Женщины советского образца в регистратуре не и...</td>\n",
" <td>женщина советский образец регистратура иметь п...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>4</th>\n",
" <td>positive</td>\n",
" <td>У меня с детства очень плохие зубы (тонкая и х...</td>\n",
" <td>детство очень плохой зуб тонкий хрупкий эмаль ...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>...</th>\n",
" <td>...</td>\n",
" <td>...</td>\n",
" <td>...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>70592</th>\n",
" <td>negative</td>\n",
" <td>Заведение ужасное. Врачи делят 1 кабинет на 2х...</td>\n",
" <td>заведение ужасный врач делить 1 кабинет 2х спе...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>70593</th>\n",
" <td>negative</td>\n",
" <td>Люди, не обращайтесь в эту фирму! Муж проходил...</td>\n",
" <td>человек обращаться фирма муж проходить анализ ...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>70594</th>\n",
" <td>positive</td>\n",
" <td>Дорогие посетители медицинского центра ООО \"Ме...</td>\n",
" <td>дорогой посетитель медицинский центр ооо медал...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>70595</th>\n",
" <td>negative</td>\n",
" <td>В регистратуре сидит хамка, такое отношение и ...</td>\n",
" <td>регистратура сидеть хамка такой отношение мане...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>70596</th>\n",
" <td>positive</td>\n",
" <td>Хочу поблагодарить весь персонал \"МедАльфаПроф...</td>\n",
" <td>хотеть поблагодарить весь персонал медальфапро...</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>\n",
"<p>70597 rows × 3 columns</p>\n",
"</div>"
],
"text/plain": [
" sentiment content \\\n",
"0 positive Огромное спасибо за чудесное удаление двух зуб... \n",
"1 positive Хочу выразить особую благодарность замечательн... \n",
"2 positive Добрый вечер! Хотелось бы поблагодарить сотруд... \n",
"3 negative Женщины советского образца в регистратуре не и... \n",
"4 positive У меня с детства очень плохие зубы (тонкая и х... \n",
"... ... ... \n",
"70592 negative Заведение ужасное. Врачи делят 1 кабинет на 2х... \n",
"70593 negative Люди, не обращайтесь в эту фирму! Муж проходил... \n",
"70594 positive Дорогие посетители медицинского центра ООО \"Ме... \n",
"70595 negative В регистратуре сидит хамка, такое отношение и ... \n",
"70596 positive Хочу поблагодарить весь персонал \"МедАльфаПроф... \n",
"\n",
" cleaned_text \n",
"0 огромный спасибо чудесный удаление два зуб муд... \n",
"1 хотеть выразить особый благодарность замечател... \n",
"2 добрый вечер хотеться поблагодарить сотрудник ... \n",
"3 женщина советский образец регистратура иметь п... \n",
"4 детство очень плохой зуб тонкий хрупкий эмаль ... \n",
"... ... \n",
"70592 заведение ужасный врач делить 1 кабинет 2х спе... \n",
"70593 человек обращаться фирма муж проходить анализ ... \n",
"70594 дорогой посетитель медицинский центр ооо медал... \n",
"70595 регистратура сидеть хамка такой отношение мане... \n",
"70596 хотеть поблагодарить весь персонал медальфапро... \n",
"\n",
"[70597 rows x 3 columns]"
]
},
"execution_count": 28,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"df"
]
},
{
"cell_type": "code",
"execution_count": 29,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'добрый вечер хотеться поблагодарить сотрудник рентген протезироваться относиться поликлиника 189 отфутболить подходить кочин зам гл врач заведовать просто сделать 3 снимок полка рядом дом грубо отказать сотрудник рентген просто сидеть кроссворд разгадывать видеть принимать протезирование сказать протезироваться делать говорить удобно побояться первый попасть молодой девушка выслушать сделать 1 снимка записать другой день это удобно народ полно бедный сотрудник читать отзыв особенно житель люблино 189 полка давать жаловаться департамент спасибо рентген слышать очередь народ перебрать норма спасибо'"
]
},
"execution_count": 29,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"df['cleaned_text'][2]"
]
},
{
"cell_type": "code",
"execution_count": 34,
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"/tmp/ipykernel_75887/3526150694.py:1: SettingWithCopyWarning: \n",
"A value is trying to be set on a copy of a slice from a DataFrame.\n",
"Try using .loc[row_indexer,col_indexer] = value instead\n",
"\n",
"See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n",
" df['sentiment'] = df['sentiment'].apply(lambda x: 1 if x == 'negative' else 0)\n"
]
}
],
"source": [
"df['sentiment'] = df['sentiment'].apply(lambda x: 1 if x == 'negative' else 0)"
]
},
{
"cell_type": "code",
"execution_count": 35,
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"<div>\n",
"<style scoped>\n",
" .dataframe tbody tr th:only-of-type {\n",
" vertical-align: middle;\n",
" }\n",
"\n",
" .dataframe tbody tr th {\n",
" vertical-align: top;\n",
" }\n",
"\n",
" .dataframe thead th {\n",
" text-align: right;\n",
" }\n",
"</style>\n",
"<table border=\"1\" class=\"dataframe\">\n",
" <thead>\n",
" <tr style=\"text-align: right;\">\n",
" <th></th>\n",
" <th>sentiment</th>\n",
" <th>content</th>\n",
" <th>cleaned_text</th>\n",
" </tr>\n",
" </thead>\n",
" <tbody>\n",
" <tr>\n",
" <th>0</th>\n",
" <td>0</td>\n",
" <td>Огромное спасибо за чудесное удаление двух зуб...</td>\n",
" <td>огромный спасибо чудесный удаление два зуб муд...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>1</th>\n",
" <td>0</td>\n",
" <td>Хочу выразить особую благодарность замечательн...</td>\n",
" <td>хотеть выразить особый благодарность замечател...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>2</th>\n",
" <td>0</td>\n",
" <td>Добрый вечер! Хотелось бы поблагодарить сотруд...</td>\n",
" <td>добрый вечер хотеться поблагодарить сотрудник ...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>3</th>\n",
" <td>1</td>\n",
" <td>Женщины советского образца в регистратуре не и...</td>\n",
" <td>женщина советский образец регистратура иметь п...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>4</th>\n",
" <td>0</td>\n",
" <td>У меня с детства очень плохие зубы (тонкая и х...</td>\n",
" <td>детство очень плохой зуб тонкий хрупкий эмаль ...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>...</th>\n",
" <td>...</td>\n",
" <td>...</td>\n",
" <td>...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>70592</th>\n",
" <td>1</td>\n",
" <td>Заведение ужасное. Врачи делят 1 кабинет на 2х...</td>\n",
" <td>заведение ужасный врач делить 1 кабинет 2х спе...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>70593</th>\n",
" <td>1</td>\n",
" <td>Люди, не обращайтесь в эту фирму! Муж проходил...</td>\n",
" <td>человек обращаться фирма муж проходить анализ ...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>70594</th>\n",
" <td>0</td>\n",
" <td>Дорогие посетители медицинского центра ООО \"Ме...</td>\n",
" <td>дорогой посетитель медицинский центр ооо медал...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>70595</th>\n",
" <td>1</td>\n",
" <td>В регистратуре сидит хамка, такое отношение и ...</td>\n",
" <td>регистратура сидеть хамка такой отношение мане...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>70596</th>\n",
" <td>0</td>\n",
" <td>Хочу поблагодарить весь персонал \"МедАльфаПроф...</td>\n",
" <td>хотеть поблагодарить весь персонал медальфапро...</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>\n",
"<p>70597 rows × 3 columns</p>\n",
"</div>"
],
"text/plain": [
" sentiment content \\\n",
"0 0 Огромное спасибо за чудесное удаление двух зуб... \n",
"1 0 Хочу выразить особую благодарность замечательн... \n",
"2 0 Добрый вечер! Хотелось бы поблагодарить сотруд... \n",
"3 1 Женщины советского образца в регистратуре не и... \n",
"4 0 У меня с детства очень плохие зубы (тонкая и х... \n",
"... ... ... \n",
"70592 1 Заведение ужасное. Врачи делят 1 кабинет на 2х... \n",
"70593 1 Люди, не обращайтесь в эту фирму! Муж проходил... \n",
"70594 0 Дорогие посетители медицинского центра ООО \"Ме... \n",
"70595 1 В регистратуре сидит хамка, такое отношение и ... \n",
"70596 0 Хочу поблагодарить весь персонал \"МедАльфаПроф... \n",
"\n",
" cleaned_text \n",
"0 огромный спасибо чудесный удаление два зуб муд... \n",
"1 хотеть выразить особый благодарность замечател... \n",
"2 добрый вечер хотеться поблагодарить сотрудник ... \n",
"3 женщина советский образец регистратура иметь п... \n",
"4 детство очень плохой зуб тонкий хрупкий эмаль ... \n",
"... ... \n",
"70592 заведение ужасный врач делить 1 кабинет 2х спе... \n",
"70593 человек обращаться фирма муж проходить анализ ... \n",
"70594 дорогой посетитель медицинский центр ооо медал... \n",
"70595 регистратура сидеть хамка такой отношение мане... \n",
"70596 хотеть поблагодарить весь персонал медальфапро... \n",
"\n",
"[70597 rows x 3 columns]"
]
},
"execution_count": 35,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"df"
]
},
{
"cell_type": "code",
"execution_count": 46,
"metadata": {},
"outputs": [],
"source": [
"X_train, X_test, y_train, y_test = train_test_split(df['cleaned_text'], df['sentiment'], test_size=0.2, random_state=42)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Векторизация и сжатие"
]
},
{
"cell_type": "code",
"execution_count": 47,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"vectorization done in 4.084 s\n",
"n_samples train: 56477, n_features: 1010\n",
"n_samples test: 14120, n_features: 1010\n"
]
}
],
"source": [
"vectorizer = TfidfVectorizer(\n",
" max_df=0.9,\n",
" min_df=500,\n",
" # ngram_range=(1, 2), # Использование униграмм и биграмм\n",
" # max_features=5000,\n",
" stop_words=stopwords.words('russian'),\n",
")\n",
"t0 = time()\n",
"X_train_tfidf = vectorizer.fit_transform(X_train)\n",
"X_test_tfidf = vectorizer.transform(X_test)\n",
"\n",
"print(f\"vectorization done in {time() - t0:.3f} s\")\n",
"print(f\"n_samples train: {X_train_tfidf.shape[0]}, n_features: {X_train_tfidf.shape[1]}\")\n",
"print(f\"n_samples test: {X_test_tfidf.shape[0]}, n_features: {X_test_tfidf.shape[1]}\")"
]
},
{
"cell_type": "code",
"execution_count": 48,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"LSA done in 14.485 s\n",
"Explained variance of the SVD step: 74.3%\n"
]
}
],
"source": [
"lsa = make_pipeline(TruncatedSVD(n_components=500), Normalizer(copy=False))\n",
"t0 = time()\n",
"X_train_lsa = lsa.fit_transform(X_train_tfidf)\n",
"\n",
"# Применение обученной модели LSA к тестовым данным\n",
"X_test_lsa = lsa.transform(X_test_tfidf)\n",
"explained_variance = lsa[0].explained_variance_ratio_.sum()\n",
"\n",
"print(f\"LSA done in {time() - t0:.3f} s\")\n",
"print(f\"Explained variance of the SVD step: {explained_variance * 100:.1f}%\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Логистическая регрессия"
]
},
{
"cell_type": "code",
"execution_count": 51,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
" precision recall f1-score support\n",
"\n",
" 0 0.94 0.94 0.94 8342\n",
" 1 0.91 0.92 0.91 5778\n",
"\n",
" accuracy 0.93 14120\n",
" macro avg 0.92 0.93 0.93 14120\n",
"weighted avg 0.93 0.93 0.93 14120\n",
"\n",
"Accuracy: 0.9277620396600567\n",
"F1 score: 0.9120689655172414\n"
]
}
],
"source": [
"model = LogisticRegression()\n",
"\n",
"# Обучение модели\n",
"model.fit(X_train_lsa, y_train)\n",
"\n",
"# Прогнозирование на тестовой выборке\n",
"y_pred = model.predict(X_test_lsa)\n",
"\n",
"# Вывод результатов\n",
"print(classification_report(y_test, y_pred))\n",
"print(f'Accuracy: {accuracy_score(y_test, y_pred)}')\n",
"print(f'F1 score: {f1_score(y_test, y_pred)}')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Создание пайплайна"
]
},
{
"cell_type": "code",
"execution_count": 54,
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"[nltk_data] Downloading package stopwords to /home/vera/nltk_data...\n",
"[nltk_data] Package stopwords is already up-to-date!\n",
"[nltk_data] Downloading package punkt to /home/vera/nltk_data...\n",
"[nltk_data] Package punkt is already up-to-date!\n"
]
},
{
"data": {
"text/html": [
"<style>#sk-container-id-1 {\n",
" /* Definition of color scheme common for light and dark mode */\n",
" --sklearn-color-text: black;\n",
" --sklearn-color-line: gray;\n",
" /* Definition of color scheme for unfitted estimators */\n",
" --sklearn-color-unfitted-level-0: #fff5e6;\n",
" --sklearn-color-unfitted-level-1: #f6e4d2;\n",
" --sklearn-color-unfitted-level-2: #ffe0b3;\n",
" --sklearn-color-unfitted-level-3: chocolate;\n",
" /* Definition of color scheme for fitted estimators */\n",
" --sklearn-color-fitted-level-0: #f0f8ff;\n",
" --sklearn-color-fitted-level-1: #d4ebff;\n",
" --sklearn-color-fitted-level-2: #b3dbfd;\n",
" --sklearn-color-fitted-level-3: cornflowerblue;\n",
"\n",
" /* Specific color for light theme */\n",
" --sklearn-color-text-on-default-background: var(--sg-text-color, var(--theme-code-foreground, var(--jp-content-font-color1, black)));\n",
" --sklearn-color-background: var(--sg-background-color, var(--theme-background, var(--jp-layout-color0, white)));\n",
" --sklearn-color-border-box: var(--sg-text-color, var(--theme-code-foreground, var(--jp-content-font-color1, black)));\n",
" --sklearn-color-icon: #696969;\n",
"\n",
" @media (prefers-color-scheme: dark) {\n",
" /* Redefinition of color scheme for dark theme */\n",
" --sklearn-color-text-on-default-background: var(--sg-text-color, var(--theme-code-foreground, var(--jp-content-font-color1, white)));\n",
" --sklearn-color-background: var(--sg-background-color, var(--theme-background, var(--jp-layout-color0, #111)));\n",
" --sklearn-color-border-box: var(--sg-text-color, var(--theme-code-foreground, var(--jp-content-font-color1, white)));\n",
" --sklearn-color-icon: #878787;\n",
" }\n",
"}\n",
"\n",
"#sk-container-id-1 {\n",
" color: var(--sklearn-color-text);\n",
"}\n",
"\n",
"#sk-container-id-1 pre {\n",
" padding: 0;\n",
"}\n",
"\n",
"#sk-container-id-1 input.sk-hidden--visually {\n",
" border: 0;\n",
" clip: rect(1px 1px 1px 1px);\n",
" clip: rect(1px, 1px, 1px, 1px);\n",
" height: 1px;\n",
" margin: -1px;\n",
" overflow: hidden;\n",
" padding: 0;\n",
" position: absolute;\n",
" width: 1px;\n",
"}\n",
"\n",
"#sk-container-id-1 div.sk-dashed-wrapped {\n",
" border: 1px dashed var(--sklearn-color-line);\n",
" margin: 0 0.4em 0.5em 0.4em;\n",
" box-sizing: border-box;\n",
" padding-bottom: 0.4em;\n",
" background-color: var(--sklearn-color-background);\n",
"}\n",
"\n",
"#sk-container-id-1 div.sk-container {\n",
" /* jupyter's `normalize.less` sets `[hidden] { display: none; }`\n",
" but bootstrap.min.css set `[hidden] { display: none !important; }`\n",
" so we also need the `!important` here to be able to override the\n",
" default hidden behavior on the sphinx rendered scikit-learn.org.\n",
" See: https://github.com/scikit-learn/scikit-learn/issues/21755 */\n",
" display: inline-block !important;\n",
" position: relative;\n",
"}\n",
"\n",
"#sk-container-id-1 div.sk-text-repr-fallback {\n",
" display: none;\n",
"}\n",
"\n",
"div.sk-parallel-item,\n",
"div.sk-serial,\n",
"div.sk-item {\n",
" /* draw centered vertical line to link estimators */\n",
" background-image: linear-gradient(var(--sklearn-color-text-on-default-background), var(--sklearn-color-text-on-default-background));\n",
" background-size: 2px 100%;\n",
" background-repeat: no-repeat;\n",
" background-position: center center;\n",
"}\n",
"\n",
"/* Parallel-specific style estimator block */\n",
"\n",
"#sk-container-id-1 div.sk-parallel-item::after {\n",
" content: \"\";\n",
" width: 100%;\n",
" border-bottom: 2px solid var(--sklearn-color-text-on-default-background);\n",
" flex-grow: 1;\n",
"}\n",
"\n",
"#sk-container-id-1 div.sk-parallel {\n",
" display: flex;\n",
" align-items: stretch;\n",
" justify-content: center;\n",
" background-color: var(--sklearn-color-background);\n",
" position: relative;\n",
"}\n",
"\n",
"#sk-container-id-1 div.sk-parallel-item {\n",
" display: flex;\n",
" flex-direction: column;\n",
"}\n",
"\n",
"#sk-container-id-1 div.sk-parallel-item:first-child::after {\n",
" align-self: flex-end;\n",
" width: 50%;\n",
"}\n",
"\n",
"#sk-container-id-1 div.sk-parallel-item:last-child::after {\n",
" align-self: flex-start;\n",
" width: 50%;\n",
"}\n",
"\n",
"#sk-container-id-1 div.sk-parallel-item:only-child::after {\n",
" width: 0;\n",
"}\n",
"\n",
"/* Serial-specific style estimator block */\n",
"\n",
"#sk-container-id-1 div.sk-serial {\n",
" display: flex;\n",
" flex-direction: column;\n",
" align-items: center;\n",
" background-color: var(--sklearn-color-background);\n",
" padding-right: 1em;\n",
" padding-left: 1em;\n",
"}\n",
"\n",
"\n",
"/* Toggleable style: style used for estimator/Pipeline/ColumnTransformer box that is\n",
"clickable and can be expanded/collapsed.\n",
"- Pipeline and ColumnTransformer use this feature and define the default style\n",
"- Estimators will overwrite some part of the style using the `sk-estimator` class\n",
"*/\n",
"\n",
"/* Pipeline and ColumnTransformer style (default) */\n",
"\n",
"#sk-container-id-1 div.sk-toggleable {\n",
" /* Default theme specific background. It is overwritten whether we have a\n",
" specific estimator or a Pipeline/ColumnTransformer */\n",
" background-color: var(--sklearn-color-background);\n",
"}\n",
"\n",
"/* Toggleable label */\n",
"#sk-container-id-1 label.sk-toggleable__label {\n",
" cursor: pointer;\n",
" display: block;\n",
" width: 100%;\n",
" margin-bottom: 0;\n",
" padding: 0.5em;\n",
" box-sizing: border-box;\n",
" text-align: center;\n",
"}\n",
"\n",
"#sk-container-id-1 label.sk-toggleable__label-arrow:before {\n",
" /* Arrow on the left of the label */\n",
" content: \"▸\";\n",
" float: left;\n",
" margin-right: 0.25em;\n",
" color: var(--sklearn-color-icon);\n",
"}\n",
"\n",
"#sk-container-id-1 label.sk-toggleable__label-arrow:hover:before {\n",
" color: var(--sklearn-color-text);\n",
"}\n",
"\n",
"/* Toggleable content - dropdown */\n",
"\n",
"#sk-container-id-1 div.sk-toggleable__content {\n",
" max-height: 0;\n",
" max-width: 0;\n",
" overflow: hidden;\n",
" text-align: left;\n",
" /* unfitted */\n",
" background-color: var(--sklearn-color-unfitted-level-0);\n",
"}\n",
"\n",
"#sk-container-id-1 div.sk-toggleable__content.fitted {\n",
" /* fitted */\n",
" background-color: var(--sklearn-color-fitted-level-0);\n",
"}\n",
"\n",
"#sk-container-id-1 div.sk-toggleable__content pre {\n",
" margin: 0.2em;\n",
" border-radius: 0.25em;\n",
" color: var(--sklearn-color-text);\n",
" /* unfitted */\n",
" background-color: var(--sklearn-color-unfitted-level-0);\n",
"}\n",
"\n",
"#sk-container-id-1 div.sk-toggleable__content.fitted pre {\n",
" /* unfitted */\n",
" background-color: var(--sklearn-color-fitted-level-0);\n",
"}\n",
"\n",
"#sk-container-id-1 input.sk-toggleable__control:checked~div.sk-toggleable__content {\n",
" /* Expand drop-down */\n",
" max-height: 200px;\n",
" max-width: 100%;\n",
" overflow: auto;\n",
"}\n",
"\n",
"#sk-container-id-1 input.sk-toggleable__control:checked~label.sk-toggleable__label-arrow:before {\n",
" content: \"▾\";\n",
"}\n",
"\n",
"/* Pipeline/ColumnTransformer-specific style */\n",
"\n",
"#sk-container-id-1 div.sk-label input.sk-toggleable__control:checked~label.sk-toggleable__label {\n",
" color: var(--sklearn-color-text);\n",
" background-color: var(--sklearn-color-unfitted-level-2);\n",
"}\n",
"\n",
"#sk-container-id-1 div.sk-label.fitted input.sk-toggleable__control:checked~label.sk-toggleable__label {\n",
" background-color: var(--sklearn-color-fitted-level-2);\n",
"}\n",
"\n",
"/* Estimator-specific style */\n",
"\n",
"/* Colorize estimator box */\n",
"#sk-container-id-1 div.sk-estimator input.sk-toggleable__control:checked~label.sk-toggleable__label {\n",
" /* unfitted */\n",
" background-color: var(--sklearn-color-unfitted-level-2);\n",
"}\n",
"\n",
"#sk-container-id-1 div.sk-estimator.fitted input.sk-toggleable__control:checked~label.sk-toggleable__label {\n",
" /* fitted */\n",
" background-color: var(--sklearn-color-fitted-level-2);\n",
"}\n",
"\n",
"#sk-container-id-1 div.sk-label label.sk-toggleable__label,\n",
"#sk-container-id-1 div.sk-label label {\n",
" /* The background is the default theme color */\n",
" color: var(--sklearn-color-text-on-default-background);\n",
"}\n",
"\n",
"/* On hover, darken the color of the background */\n",
"#sk-container-id-1 div.sk-label:hover label.sk-toggleable__label {\n",
" color: var(--sklearn-color-text);\n",
" background-color: var(--sklearn-color-unfitted-level-2);\n",
"}\n",
"\n",
"/* Label box, darken color on hover, fitted */\n",
"#sk-container-id-1 div.sk-label.fitted:hover label.sk-toggleable__label.fitted {\n",
" color: var(--sklearn-color-text);\n",
" background-color: var(--sklearn-color-fitted-level-2);\n",
"}\n",
"\n",
"/* Estimator label */\n",
"\n",
"#sk-container-id-1 div.sk-label label {\n",
" font-family: monospace;\n",
" font-weight: bold;\n",
" display: inline-block;\n",
" line-height: 1.2em;\n",
"}\n",
"\n",
"#sk-container-id-1 div.sk-label-container {\n",
" text-align: center;\n",
"}\n",
"\n",
"/* Estimator-specific */\n",
"#sk-container-id-1 div.sk-estimator {\n",
" font-family: monospace;\n",
" border: 1px dotted var(--sklearn-color-border-box);\n",
" border-radius: 0.25em;\n",
" box-sizing: border-box;\n",
" margin-bottom: 0.5em;\n",
" /* unfitted */\n",
" background-color: var(--sklearn-color-unfitted-level-0);\n",
"}\n",
"\n",
"#sk-container-id-1 div.sk-estimator.fitted {\n",
" /* fitted */\n",
" background-color: var(--sklearn-color-fitted-level-0);\n",
"}\n",
"\n",
"/* on hover */\n",
"#sk-container-id-1 div.sk-estimator:hover {\n",
" /* unfitted */\n",
" background-color: var(--sklearn-color-unfitted-level-2);\n",
"}\n",
"\n",
"#sk-container-id-1 div.sk-estimator.fitted:hover {\n",
" /* fitted */\n",
" background-color: var(--sklearn-color-fitted-level-2);\n",
"}\n",
"\n",
"/* Specification for estimator info (e.g. \"i\" and \"?\") */\n",
"\n",
"/* Common style for \"i\" and \"?\" */\n",
"\n",
".sk-estimator-doc-link,\n",
"a:link.sk-estimator-doc-link,\n",
"a:visited.sk-estimator-doc-link {\n",
" float: right;\n",
" font-size: smaller;\n",
" line-height: 1em;\n",
" font-family: monospace;\n",
" background-color: var(--sklearn-color-background);\n",
" border-radius: 1em;\n",
" height: 1em;\n",
" width: 1em;\n",
" text-decoration: none !important;\n",
" margin-left: 1ex;\n",
" /* unfitted */\n",
" border: var(--sklearn-color-unfitted-level-1) 1pt solid;\n",
" color: var(--sklearn-color-unfitted-level-1);\n",
"}\n",
"\n",
".sk-estimator-doc-link.fitted,\n",
"a:link.sk-estimator-doc-link.fitted,\n",
"a:visited.sk-estimator-doc-link.fitted {\n",
" /* fitted */\n",
" border: var(--sklearn-color-fitted-level-1) 1pt solid;\n",
" color: var(--sklearn-color-fitted-level-1);\n",
"}\n",
"\n",
"/* On hover */\n",
"div.sk-estimator:hover .sk-estimator-doc-link:hover,\n",
".sk-estimator-doc-link:hover,\n",
"div.sk-label-container:hover .sk-estimator-doc-link:hover,\n",
".sk-estimator-doc-link:hover {\n",
" /* unfitted */\n",
" background-color: var(--sklearn-color-unfitted-level-3);\n",
" color: var(--sklearn-color-background);\n",
" text-decoration: none;\n",
"}\n",
"\n",
"div.sk-estimator.fitted:hover .sk-estimator-doc-link.fitted:hover,\n",
".sk-estimator-doc-link.fitted:hover,\n",
"div.sk-label-container:hover .sk-estimator-doc-link.fitted:hover,\n",
".sk-estimator-doc-link.fitted:hover {\n",
" /* fitted */\n",
" background-color: var(--sklearn-color-fitted-level-3);\n",
" color: var(--sklearn-color-background);\n",
" text-decoration: none;\n",
"}\n",
"\n",
"/* Span, style for the box shown on hovering the info icon */\n",
".sk-estimator-doc-link span {\n",
" display: none;\n",
" z-index: 9999;\n",
" position: relative;\n",
" font-weight: normal;\n",
" right: .2ex;\n",
" padding: .5ex;\n",
" margin: .5ex;\n",
" width: min-content;\n",
" min-width: 20ex;\n",
" max-width: 50ex;\n",
" color: var(--sklearn-color-text);\n",
" box-shadow: 2pt 2pt 4pt #999;\n",
" /* unfitted */\n",
" background: var(--sklearn-color-unfitted-level-0);\n",
" border: .5pt solid var(--sklearn-color-unfitted-level-3);\n",
"}\n",
"\n",
".sk-estimator-doc-link.fitted span {\n",
" /* fitted */\n",
" background: var(--sklearn-color-fitted-level-0);\n",
" border: var(--sklearn-color-fitted-level-3);\n",
"}\n",
"\n",
".sk-estimator-doc-link:hover span {\n",
" display: block;\n",
"}\n",
"\n",
"/* \"?\"-specific style due to the `<a>` HTML tag */\n",
"\n",
"#sk-container-id-1 a.estimator_doc_link {\n",
" float: right;\n",
" font-size: 1rem;\n",
" line-height: 1em;\n",
" font-family: monospace;\n",
" background-color: var(--sklearn-color-background);\n",
" border-radius: 1rem;\n",
" height: 1rem;\n",
" width: 1rem;\n",
" text-decoration: none;\n",
" /* unfitted */\n",
" color: var(--sklearn-color-unfitted-level-1);\n",
" border: var(--sklearn-color-unfitted-level-1) 1pt solid;\n",
"}\n",
"\n",
"#sk-container-id-1 a.estimator_doc_link.fitted {\n",
" /* fitted */\n",
" border: var(--sklearn-color-fitted-level-1) 1pt solid;\n",
" color: var(--sklearn-color-fitted-level-1);\n",
"}\n",
"\n",
"/* On hover */\n",
"#sk-container-id-1 a.estimator_doc_link:hover {\n",
" /* unfitted */\n",
" background-color: var(--sklearn-color-unfitted-level-3);\n",
" color: var(--sklearn-color-background);\n",
" text-decoration: none;\n",
"}\n",
"\n",
"#sk-container-id-1 a.estimator_doc_link.fitted:hover {\n",
" /* fitted */\n",
" background-color: var(--sklearn-color-fitted-level-3);\n",
"}\n",
"</style><div id=\"sk-container-id-1\" class=\"sk-top-container\"><div class=\"sk-text-repr-fallback\"><pre>Pipeline(steps=[('preprocessor', TextPreprocessor()),\n",
" ('vectorizer',\n",
" TfidfVectorizer(max_df=0.9, min_df=500,\n",
" stop_words=['и', 'в', 'во', 'не', 'что', 'он',\n",
" 'на', 'я', 'с', 'со', 'как', 'а',\n",
" 'то', 'все', 'она', 'так', 'его',\n",
" 'но', 'да', 'ты', 'к', 'у', 'же',\n",
" 'вы', 'за', 'бы', 'по', 'только',\n",
" 'ее', 'мне', ...])),\n",
" ('lsa',\n",
" Pipeline(steps=[('truncatedsvd',\n",
" TruncatedSVD(n_components=500)),\n",
" ('normalizer', Normalizer(copy=False))])),\n",
" ('classifier', LogisticRegression())])</pre><b>In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook. <br />On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.</b></div><div class=\"sk-container\" hidden><div class=\"sk-item sk-dashed-wrapped\"><div class=\"sk-label-container\"><div class=\"sk-label fitted sk-toggleable\"><input class=\"sk-toggleable__control sk-hidden--visually\" id=\"sk-estimator-id-1\" type=\"checkbox\" ><label for=\"sk-estimator-id-1\" class=\"sk-toggleable__label fitted sk-toggleable__label-arrow fitted\"> Pipeline<a class=\"sk-estimator-doc-link fitted\" rel=\"noreferrer\" target=\"_blank\" href=\"https://scikit-learn.org/1.4/modules/generated/sklearn.pipeline.Pipeline.html\">?<span>Documentation for Pipeline</span></a><span class=\"sk-estimator-doc-link fitted\">i<span>Fitted</span></span></label><div class=\"sk-toggleable__content fitted\"><pre>Pipeline(steps=[('preprocessor', TextPreprocessor()),\n",
" ('vectorizer',\n",
" TfidfVectorizer(max_df=0.9, min_df=500,\n",
" stop_words=['и', 'в', 'во', 'не', 'что', 'он',\n",
" 'на', 'я', 'с', 'со', 'как', 'а',\n",
" 'то', 'все', 'она', 'так', 'его',\n",
" 'но', 'да', 'ты', 'к', 'у', 'же',\n",
" 'вы', 'за', 'бы', 'по', 'только',\n",
" 'ее', 'мне', ...])),\n",
" ('lsa',\n",
" Pipeline(steps=[('truncatedsvd',\n",
" TruncatedSVD(n_components=500)),\n",
" ('normalizer', Normalizer(copy=False))])),\n",
" ('classifier', LogisticRegression())])</pre></div> </div></div><div class=\"sk-serial\"><div class=\"sk-item\"><div class=\"sk-estimator fitted sk-toggleable\"><input class=\"sk-toggleable__control sk-hidden--visually\" id=\"sk-estimator-id-2\" type=\"checkbox\" ><label for=\"sk-estimator-id-2\" class=\"sk-toggleable__label fitted sk-toggleable__label-arrow fitted\">TextPreprocessor</label><div class=\"sk-toggleable__content fitted\"><pre>TextPreprocessor()</pre></div> </div></div><div class=\"sk-item\"><div class=\"sk-estimator fitted sk-toggleable\"><input class=\"sk-toggleable__control sk-hidden--visually\" id=\"sk-estimator-id-3\" type=\"checkbox\" ><label for=\"sk-estimator-id-3\" class=\"sk-toggleable__label fitted sk-toggleable__label-arrow fitted\"> TfidfVectorizer<a class=\"sk-estimator-doc-link fitted\" rel=\"noreferrer\" target=\"_blank\" href=\"https://scikit-learn.org/1.4/modules/generated/sklearn.feature_extraction.text.TfidfVectorizer.html\">?<span>Documentation for TfidfVectorizer</span></a></label><div class=\"sk-toggleable__content fitted\"><pre>TfidfVectorizer(max_df=0.9, min_df=500,\n",
" stop_words=['и', 'в', 'во', 'не', 'что', 'он', 'на', 'я', 'с',\n",
" 'со', 'как', 'а', 'то', 'все', 'она', 'так', 'его',\n",
" 'но', 'да', 'ты', 'к', 'у', 'же', 'вы', 'за', 'бы',\n",
" 'по', 'только', 'ее', 'мне', ...])</pre></div> </div></div><div class=\"sk-item\"><div class=\"sk-label-container\"><div class=\"sk-label fitted sk-toggleable\"><input class=\"sk-toggleable__control sk-hidden--visually\" id=\"sk-estimator-id-4\" type=\"checkbox\" ><label for=\"sk-estimator-id-4\" class=\"sk-toggleable__label fitted sk-toggleable__label-arrow fitted\"> lsa: Pipeline<a class=\"sk-estimator-doc-link fitted\" rel=\"noreferrer\" target=\"_blank\" href=\"https://scikit-learn.org/1.4/modules/generated/sklearn.pipeline.Pipeline.html\">?<span>Documentation for lsa: Pipeline</span></a></label><div class=\"sk-toggleable__content fitted\"><pre>Pipeline(steps=[('truncatedsvd', TruncatedSVD(n_components=500)),\n",
" ('normalizer', Normalizer(copy=False))])</pre></div> </div></div><div class=\"sk-serial\"><div class=\"sk-item\"><div class=\"sk-estimator fitted sk-toggleable\"><input class=\"sk-toggleable__control sk-hidden--visually\" id=\"sk-estimator-id-5\" type=\"checkbox\" ><label for=\"sk-estimator-id-5\" class=\"sk-toggleable__label fitted sk-toggleable__label-arrow fitted\"> TruncatedSVD<a class=\"sk-estimator-doc-link fitted\" rel=\"noreferrer\" target=\"_blank\" href=\"https://scikit-learn.org/1.4/modules/generated/sklearn.decomposition.TruncatedSVD.html\">?<span>Documentation for TruncatedSVD</span></a></label><div class=\"sk-toggleable__content fitted\"><pre>TruncatedSVD(n_components=500)</pre></div> </div></div><div class=\"sk-item\"><div class=\"sk-estimator fitted sk-toggleable\"><input class=\"sk-toggleable__control sk-hidden--visually\" id=\"sk-estimator-id-6\" type=\"checkbox\" ><label for=\"sk-estimator-id-6\" class=\"sk-toggleable__label fitted sk-toggleable__label-arrow fitted\"> Normalizer<a class=\"sk-estimator-doc-link fitted\" rel=\"noreferrer\" target=\"_blank\" href=\"https://scikit-learn.org/1.4/modules/generated/sklearn.preprocessing.Normalizer.html\">?<span>Documentation for Normalizer</span></a></label><div class=\"sk-toggleable__content fitted\"><pre>Normalizer(copy=False)</pre></div> </div></div></div></div><div class=\"sk-item\"><div class=\"sk-estimator fitted sk-toggleable\"><input class=\"sk-toggleable__control sk-hidden--visually\" id=\"sk-estimator-id-7\" type=\"checkbox\" ><label for=\"sk-estimator-id-7\" class=\"sk-toggleable__label fitted sk-toggleable__label-arrow fitted\"> LogisticRegression<a class=\"sk-estimator-doc-link fitted\" rel=\"noreferrer\" target=\"_blank\" href=\"https://scikit-learn.org/1.4/modules/generated/sklearn.linear_model.LogisticRegression.html\">?<span>Documentation for LogisticRegression</span></a></label><div class=\"sk-toggleable__content fitted\"><pre>LogisticRegression()</pre></div> </div></div></div></div></div></div>"
],
"text/plain": [
"Pipeline(steps=[('preprocessor', TextPreprocessor()),\n",
" ('vectorizer',\n",
" TfidfVectorizer(max_df=0.9, min_df=500,\n",
" stop_words=['и', 'в', 'во', 'не', 'что', 'он',\n",
" 'на', 'я', 'с', 'со', 'как', 'а',\n",
" 'то', 'все', 'она', 'так', 'его',\n",
" 'но', 'да', 'ты', 'к', 'у', 'же',\n",
" 'вы', 'за', 'бы', 'по', 'только',\n",
" 'ее', 'мне', ...])),\n",
" ('lsa',\n",
" Pipeline(steps=[('truncatedsvd',\n",
" TruncatedSVD(n_components=500)),\n",
" ('normalizer', Normalizer(copy=False))])),\n",
" ('classifier', LogisticRegression())])"
]
},
"execution_count": 54,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"import re\n",
"import pandas as pd\n",
"import numpy as np\n",
"from sklearn.base import BaseEstimator, TransformerMixin\n",
"from sklearn.feature_extraction.text import TfidfVectorizer\n",
"from sklearn.decomposition import TruncatedSVD\n",
"from sklearn.pipeline import Pipeline, FeatureUnion\n",
"from sklearn.linear_model import LogisticRegression\n",
"from sklearn.preprocessing import Normalizer\n",
"import joblib\n",
"import nltk\n",
"from nltk.corpus import stopwords\n",
"from pymorphy2 import MorphAnalyzer\n",
"\n",
"nltk.download('stopwords')\n",
"nltk.download('punkt')\n",
"\n",
"class TextPreprocessor(BaseEstimator, TransformerMixin):\n",
" def __init__(self):\n",
" self.stop_words = set(stopwords.words('russian'))\n",
" self.morph = MorphAnalyzer()\n",
"\n",
" def preprocess_text(self, text):\n",
" # Удаление всего, что не является буквами или знаками препинания\n",
" clean_pattern = re.compile(r'[^a-zA-Zа-яА-ЯёЁ0-9.,!?;:\\s]')\n",
" text = clean_pattern.sub('', text)\n",
" url_pattern = re.compile(r'http\\S+|www\\S+|https\\S+')\n",
" text = url_pattern.sub(r'', text)\n",
" text = text.translate(str.maketrans('', '', string.punctuation))\n",
" text = text.lower()\n",
" tokens = text.split()\n",
" lemmatized_text = ' '.join([self.morph.parse(word)[0].normal_form for word in tokens if word not in self.stop_words])\n",
" return lemmatized_text\n",
"\n",
" def fit(self, X, y=None):\n",
" return self\n",
"\n",
" def transform(self, X, y=None):\n",
" return X.apply(self.preprocess_text)\n",
"\n",
"\n",
"# Load and preprocess the dataset\n",
"df = pd.read_json('data/healthcare_facilities_reviews.jsonl', lines=True)\n",
"df = df[['sentiment', 'content']]\n",
"df['cleaned_text'] = df['content'].apply(TextPreprocessor().preprocess_text)\n",
"df['sentiment'] = df['sentiment'].apply(lambda x: 1 if x == 'negative' else 0)\n",
"\n",
"# Split the dataset (this is only for training purposes)\n",
"from sklearn.model_selection import train_test_split\n",
"train_df, test_df = train_test_split(df, test_size=0.2, random_state=42)\n",
"\n",
"# Create the pipeline\n",
"vectorizer = TfidfVectorizer(\n",
" max_df=0.9,\n",
" min_df=500,\n",
" stop_words=stopwords.words('russian')\n",
")\n",
"\n",
"lsa = TruncatedSVD(n_components=500)\n",
"\n",
"pipeline = Pipeline([\n",
" ('preprocessor', TextPreprocessor()),\n",
" ('vectorizer', vectorizer),\n",
" ('lsa', make_pipeline(lsa, Normalizer(copy=False))),\n",
" ('classifier', LogisticRegression())\n",
"])\n",
"\n",
"# Train the model\n",
"X_train = train_df['cleaned_text']\n",
"y_train = train_df['sentiment']\n",
"pipeline.fit(X_train, y_train)\n",
"\n",
"# Save the model\n",
"# joblib.dump(pipeline, 'logistic_regression_pipeline.pkl')\n"
]
},
{
"cell_type": "code",
"execution_count": 55,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"['logistic_regression_pipeline.pkl']"
]
},
"execution_count": 55,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Save the model for future use\n",
"joblib.dump(pipeline, 'logistic_regression_pipeline.pkl')"
]
},
{
"cell_type": "code",
"execution_count": 56,
"metadata": {},
"outputs": [],
"source": [
"# Load the model (if not already loaded)\n",
"pipeline_test= joblib.load('logistic_regression_pipeline.pkl')"
]
},
{
"cell_type": "code",
"execution_count": 61,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Predicted class: 1\n",
"Predicted proba: 0.898\n"
]
}
],
"source": [
"# Sample text for prediction\n",
"sample_text = \"Ужасная клиника, обслуживание из рук вон плохое, хотеловь бы выразить свое разочарование данным заведением. Советую обходить его мимо.\"\n",
"\n",
"# Use the pipeline to predict the class\n",
"predicted_class = pipeline_test.predict(pd.Series([sample_text]))\n",
"predicted_prob = pipeline_test.predict_proba(pd.Series([sample_text]))\n",
"print(f\"Predicted class: {predicted_class[0]}\")\n",
"print(f\"Predicted proba: {round(predicted_prob[0][1], 3)}\")"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "base",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.10.14"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
|