Spaces:
Sleeping
Sleeping
File size: 83,921 Bytes
cbce622 |
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 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 |
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Comparison of Twitter's model of viral tweets with other tweets"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In this notebook, we try to identify common features of Twitter's identified viral tweets found on the topic page \"Viral Tweets\".\n",
"\n",
"We also experiment to find if other tweets that have not figured on that topic page, can also be labeled as viral based on these common features. This should help homogeinize the data (those that are viral and those that are not) when training the model."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import pandas as pd\n",
"import seaborn as sns\n",
"import numpy as np\n",
"\n",
"import matplotlib.pyplot as plt\n",
"%matplotlib inline\n",
"\n",
"import plotly.express as px\n",
"import plotly.graph_objects as go\n",
"from plotly.subplots import make_subplots\n",
"\n",
"from helper.text_preprocessing import clear_reply_mentions\n",
"\n",
"from tqdm import tqdm\n",
"\n",
"#pd.set_option('display.max_rows', None)\n",
"pd.set_option('display.max_columns', None)\n",
"\n",
"DATA_PATH = \"../../data\"\n",
"VIRAL_TWEETS_PATH = f\"{DATA_PATH}/new/viral\"\n",
"COVID_TWEETS_PATH = f\"{DATA_PATH}/new/covid\"\n",
"\n",
"PROCESSED_PATH_VIRAL = f'{DATA_PATH}/new/processed/viral'\n",
"PROCESSED_PATH_COVID = f'{DATA_PATH}/new/processed/covid'"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 0. Preprocessing"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"viral_dataset = pd.read_parquet(f\"{VIRAL_TWEETS_PATH}/all_tweets.parquet.gzip\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"covid_dataset = pd.read_parquet(f\"{COVID_TWEETS_PATH}/all_tweets.parquet.gzip\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"covid_users = pd.read_parquet(f\"{COVID_TWEETS_PATH}/users.parquet.gzip\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"- Keep only original tweets from **covid dataset**. Viral dataset doesn't have retweets"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def is_retweeted(referenced_tweets):\n",
" for x in referenced_tweets:\n",
" if x['type'] == 'retweeted':\n",
" return True\n",
" return False\n",
"\n",
"# Keep only original tweets\n",
"referenced = covid_dataset.loc[~covid_dataset.referenced_tweets.isna()].copy()\n",
"referenced.loc[:, 'is_retweet'] = referenced.referenced_tweets.apply(is_retweeted)\n",
"retweeted = referenced[referenced.is_retweet]\n",
"retweeted"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"original_covid_tweets = covid_dataset[~covid_dataset.id.isin(retweeted.id)]\n",
"original_covid_tweets.to_parquet(f\"{COVID_TWEETS_PATH}/all_original_tweets.parquet.gzip\", index=False, compression=\"gzip\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Clear reply mentions at the beginning of tweets texts\n",
"original_covid_tweets.loc[:, \"text\"] = original_covid_tweets.text.apply(clear_reply_mentions)\n",
"viral_dataset.loc[:, \"text\"] = viral_dataset.text.apply(clear_reply_mentions)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 1. Exploration"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 1.1 - General Exploration"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"viral_dataset = pd.read_parquet(f\"{VIRAL_TWEETS_PATH}/all_tweets.parquet.gzip\")\n",
"viral_users = pd.read_parquet(f\"{VIRAL_TWEETS_PATH}/users.parquet.gzip\")\n",
"viral_tweets_ids = pd.read_parquet(f\"{VIRAL_TWEETS_PATH}/viral_tweets_ids.parquet.gzip\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"original_covid_tweets = pd.read_parquet(f\"{COVID_TWEETS_PATH}/all_original_tweets.parquet.gzip\")\n",
"covid_users = pd.read_parquet(f\"{COVID_TWEETS_PATH}/users.parquet.gzip\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"display(\"--- VIRAL DATASET ---\")\n",
"\n",
"display(f\"{len(viral_tweets_ids)} viral tweets collected\")\n",
"display(f\"{len(viral_users)} viral users\")\n",
"display(f\"{len(viral_dataset)} all tweets collected\")\n",
"\n",
"display(\"--- COVID DATASET ---\")\n",
"\n",
"display(f\"{len(original_covid_tweets)} original (not retweeted) covid tweets collected\")\n",
"display(f\"{len(original_covid_tweets.author_id.unique())} covid users collected\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# REMOVE THIS WHEN DONE COLLECTION (WARNING NOT NECESSARILY)\n",
"viral_dataset['viral'] = viral_dataset.id.isin(viral_tweets_ids.id)\n",
"\n",
"#viral_tweets = all_tweets[all_tweets.id.isin(viral_tweets.id)]\n",
"#viral_tweets\n",
"\n",
"len(viral_dataset[viral_dataset.viral])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"- merge tweets with user info"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"covid_users.columns"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"user_columns = ['author_id', 'followers_count', 'following_count', 'tweet_count', 'protected', 'verified', 'username']\n",
"viral_dataset_with_users = viral_dataset.merge(viral_users.rename(columns={'id': 'author_id'})[user_columns], on='author_id')\n",
"covid_dataset_with_users = original_covid_tweets.merge(covid_users.rename(columns={'id': 'author_id'})[user_columns], on='author_id')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### 1.1.1 - Correlation between public metrics"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"- Pearson Correlation between the different public metrics"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"public_metrics = ['retweet_count', 'like_count', 'reply_count', 'quote_count', 'followers_count', 'following_count']\n",
"display(viral_dataset_with_users[public_metrics].corr())\n",
"display(covid_dataset_with_users[public_metrics].corr())"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"px.scatter(viral_dataset, x='like_count', y='retweet_count')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### 1.1.2 - Exploring retweet count of viral vs non viral tweets"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Since we have a large number of tweets to plot, we'll only sample a few from each user"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def get_largest_n(all_tweets, by='retweet_count', n=100):\n",
" '''Get the largest 100 tweets by retweet count for every user\n",
" '''\n",
" top_n_per_user = all_tweets.groupby(by='author_id')[by].nlargest(n=100).reset_index(level=0, drop=True)\n",
" tweets_for_plot = all_tweets[all_tweets.index.isin(top_n_per_user.index)].reset_index()\n",
" return tweets_for_plot"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"tweets_plot_df = get_largest_n(viral_dataset, by='retweet_count')\n",
"fig = px.scatter(tweets_plot_df, x=tweets_plot_df.index, y='retweet_count', color='viral')\n",
"\n",
"fig.update_layout(title_text=\"Viral Dataset Scatter plot of the retweet count for the top 100 tweets per user\", xaxis_title=\"Index\", yaxis_title=\"retweet count\")\n",
"\n",
"fig.show()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"covid_tweets_plot_df = original_covid_tweets.sort_values(by='retweet_count', ascending=False)[:10000]\n",
"fig = px.scatter(covid_tweets_plot_df, x=covid_tweets_plot_df.reset_index().index, y='retweet_count')\n",
"\n",
"fig.update_layout(title_text=\"Covid Dataset Scatter plot of retweet count sorted by retweet count on a 10000 sample\", xaxis_title=\"Index\", yaxis_title=\"retweet count\")\n",
"\n",
"fig.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Finding**: Viral tweets identified by twitter are by no means more viral than other tweets tweeted by the same users. Are users who have tweeted viral tweets (as identified by Twitter) likely to have tweeted other viral tweets?"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Get the ratio for each tweet's retweet count wrt to the mean retweet count of the user's tweets\n",
"# Again since we're retrieved 3200 tweets per user, we're only taking the average over that\n",
"users_avg_retweets = viral_dataset.groupby(by='author_id').agg(mean_retweets=('retweet_count', 'mean'))\n",
"tweets_merged_avg_retweets = viral_dataset.merge(right=users_avg_retweets, left_on='author_id', right_index=True)\n",
"tweets_merged_avg_retweets['ratio_avg_retweets'] = tweets_merged_avg_retweets['retweet_count'] / tweets_merged_avg_retweets['mean_retweets']\n",
"tweets_merged_avg_retweets_sorted = tweets_merged_avg_retweets.sort_values(by='ratio_avg_retweets').reset_index()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"tweets_plot_df = get_largest_n(tweets_merged_avg_retweets_sorted, by='ratio_avg_retweets')\n",
"\n",
"fig = px.scatter(tweets_plot_df, x=tweets_plot_df.index, y='ratio_avg_retweets', color='viral')\n",
"\n",
"fig.update_layout(title_text=\"Scatter plot of the tweets sorted by the ratio #retweets/(the mean user avg #retweets)\", xaxis_title=\"Index\", yaxis_title=\"ratio\")\n",
"\n",
"fig.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Finding**: Cleaner separation. Viral tweets, as expected, are on the other end of the spectrum. However other tweets in the same range could qualify as viral as well. These tweets should be identified as viral by the Twitter model."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 1.2 Finding the right threshold for virality"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### 1.2.0 - Relabel viral tweets in the viral dataset by correcting the initial virality threshold (ONLY IN OLD PAPER SUBMITTED BY STUDENT)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Let's observe the retweet count of a user based on the tweet date."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"sample_user = viral_users.id[10]\n",
"author_tweets = viral_dataset[viral_dataset.author_id == sample_user]\n",
"fig = px.scatter(author_tweets, x='created_at', y='retweet_count', color='viral')\n",
"\n",
"fig.update_layout(title_text=\"Scatter plot of the retweet count wrt to the tweet date for a single user\")\n",
"\n",
"fig.show() "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Finding**: The above graph of a user's retweet count wrt the tweet date, shows that the viral tweets taken from the Twitter \"Viral Tweets\" topic page, have been taken at certain points in time. **Other tweets with higher retweet counts** may have been on that Topic page at different points in time as well. In any case, they **should be qualified as viral all the same**."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"One quick fix for that is, for each user, mark as viral all tweets that have higher retweet count than the viral tweet we scraped for that user. "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Get the minimum retweet count out of the viral tweets for each user\n",
"min_retweet_count_by_user = viral_dataset[viral_dataset.viral].groupby(by='author_id')[['retweet_count']].min()\n",
"\n",
"# Set as viral any tweet that has a retweet count higher or equal to the user's minimum retweet count we just computed\n",
"viral_dataset_labeled = viral_dataset.merge(min_retweet_count_by_user, left_on='author_id', right_index=True, suffixes=(None, \"_user_viral_threshold\"))\n",
"viral_dataset_labeled['viral'] = viral_dataset_labeled['retweet_count'] >= viral_dataset_labeled['retweet_count_user_viral_threshold']"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Save this result \n",
"#viral_dataset_labeled.to_parquet(f'{PROCESSED_PATH_VIRAL}/all_tweets.parquet.gzip', compression='gzip')"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"display(f\"Number of identified viral tweets increased from {len(viral_tweets_ids)} to {len(viral_dataset_labeled[viral_dataset_labeled.viral])}\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Another problem we're facing is that we're **missing historical data** on the number of followers of a user. So we cannot use the metric of:\n",
"$ \\frac{\\#retweets}{\\#followers}$ effectively. That's why we came up with the other metric: $\\frac{\\#retweets}{mean(\\#retweets)}$."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### 1.2.1 Applying the virality followers metric to both datasets"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Applying the first metric on the covid dataset\n",
"covid_dataset_with_users['virality_followers'] = covid_dataset_with_users['retweet_count'] / covid_dataset_with_users['followers_count'].astype(\"float64\")\n",
"# Handle division by zero if user has 0 followers\n",
"covid_dataset_with_users['virality_followers'] = covid_dataset_with_users.virality_followers.replace({np.inf: 0.0})"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"len(covid_dataset_with_users[(covid_dataset_with_users['virality_followers'] > 0.8)])"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Applying the second metric on the viral dataset\n",
"viral_dataset_with_users['virality_followers'] = viral_dataset_with_users['retweet_count'] / viral_dataset_with_users['followers_count'].astype(\"float64\")\n",
"# Handle division by zero if user has 0 followers\n",
"viral_dataset_with_users['virality_followers'] = viral_dataset_with_users.virality_followers.replace({np.inf: 0.0})"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"len(viral_dataset_with_users[(viral_dataset_with_users['virality_followers'] > 1)])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### 1.2.2 Applying the virality avg retweets metric to viral dataset "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"viral_users_retweet_statistics = viral_dataset_with_users.groupby(by='author_id').retweet_count.agg(['min', 'mean', 'max'])\n",
"viral_users_retweet_statistics = viral_users_retweet_statistics.rename(columns={\"min\": \"min_user_retweets\", \"max\": \"max_user_retweets\", \"mean\": \"mean_user_retweets\"})"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"viral_dataset_with_users = viral_dataset_with_users.merge(viral_users_retweet_statistics, on='author_id')"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Applying the first metric on the viral dataset\n",
"viral_dataset_with_users['virality_avg_retweets'] = viral_dataset_with_users['retweet_count'] / viral_dataset_with_users['mean_user_retweets'].astype(\"float64\")\n",
"# Handle division by zero if user has 0 followers\n",
"viral_dataset_with_users['virality_avg_retweets'] = viral_dataset_with_users.virality_avg_retweets.replace({np.inf: 0.0})"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"len(viral_dataset_with_users[(viral_dataset_with_users['virality_avg_retweets'] > 1)])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### 1.2.3 How many tweets are covered by metric 1?"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"temp = viral_dataset_with_users[viral_dataset_with_users.virality_followers > 0]\n",
"temp_2 = viral_dataset_with_users[viral_dataset_with_users.virality_avg_retweets > 0]\n",
"viral_temp = viral_dataset_with_users[viral_dataset_with_users.viral]"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"fig = px.ecdf(viral_dataset_with_users[viral_dataset_with_users.viral], x='virality_followers')\n",
"\n",
"# TODO: percentage y axis\n",
"# TODO: Only take the scraped tweets\n",
"fig.update_layout(title_text=\"Percentage of viral tweets recognized by Metric 1: number of followers\", xaxis_title=\"Metric 1: virality_followers\", yaxis_title=\"Percentage\")\n",
"\n",
"fig.show()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"fig1 = sns.displot(temp, x='virality_followers', kind='ecdf')\n",
"\n",
"plt.xscale('log')\n",
"plt.title(\"Proportion of tweets labeled as viral as function of Metric 1: number of followers (logscale)\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"temp_2 = viral_dataset_with_users[viral_dataset_with_users.virality_avg_retweets > 0]"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"fig = px.ecdf(viral_temp, x='virality_avg_retweets')\n",
"\n",
"fig.update_layout(title_text=\"Percentage of viral tweets recognized by Metric 2 avg retweets\", xaxis_title=\"Metric 2: avg retweets\", yaxis_title=\"Percentage\")\n",
"\n",
"fig.show()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"fig = sns.displot(temp_2, x='virality_avg_retweets', kind='ecdf')\n",
"\n",
"plt.xscale('log')\n",
"plt.title(\"Proportion of tweets labeled as viral as function of Metric 2: avg retweets (logscale)\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"TODO: Plot the percentage of viral tweets labeled vs the # of new tweets labeled wrt to the varying threshold of the metric we use. "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"#viral_dataset_with_users = viral_dataset_with_users.groupby(by='virality_followers').count()\n",
"viral_dataset_with_users = pd.read_parquet(f\"{PROCESSED_PATH_VIRAL}/all_tweets.parquet.gzip\")\n",
"# Applying the second metric on the viral dataset\n",
"viral_dataset_with_users['virality_followers'] = viral_dataset_with_users['retweet_count'] / viral_dataset_with_users['followers_count'].astype(\"float64\")\n",
"# Handle division by zero if user has 0 followers\n",
"viral_dataset_with_users['virality_followers'] = viral_dataset_with_users.virality_followers.replace({np.inf: 0.0})\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"viral_dataset_with_users"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"viral_dataset_with_users_truncated = viral_dataset_with_users[viral_dataset_with_users.virality_followers > 0.1]\n",
"#viral_dataset_with_users['viral_metric_1'] = viral_dataset_with_users['']\n",
"len(viral_dataset_with_users_truncated)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"ready_to_plot = viral_dataset_with_users_truncated.copy()\n",
"ready_to_plot['viral'] = ready_to_plot['viral'].replace({False: None})\n",
"ready_to_plot = ready_to_plot.groupby(by='virality_followers').count()[['text', 'viral']].cumsum().rename(columns={'text':'tweets'})"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"fig = px.line(ready_to_plot, x='viral', y='tweets', hover_data=[ready_to_plot.index])#, log_y=True)\n",
"\n",
"fig.update_layout(title_text=\"Line plot of #viral tweets labeled as viral vs # new tweets labeled as viral by varying threshold of Metric 1 (#followers)\", xaxis_title=\"Number of viral tweets labeled as viral\", yaxis_title=\"Number of new tweets labeled as viral\")\n",
"fig.show()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"ready_to_plot = viral_dataset_with_users_truncated.copy()\n",
"ready_to_plot['viral'] = ready_to_plot['viral'].replace({False: None})\n",
"ready_to_plot = ready_to_plot.groupby(by='virality_followers').count()[['text', 'viral']].cumsum().rename(columns={'text':'tweets'})\n",
"ready_to_plot['tweets'] = len(viral_dataset_with_users) - ready_to_plot.tweets"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"fig = px.line(ready_to_plot, x='viral', y='tweets', hover_data=[ready_to_plot.index])#, log_y=True)\n",
"\n",
"fig.update_layout(title_text=\"Line plot of #viral tweets labeled as viral vs # new tweets labeled as viral by varying threshold of Metric 1 (#followers)\", xaxis_title=\"Number of viral tweets labeled as viral\", yaxis_title=\"Number of new tweets labeled as viral\")\n",
"fig.show()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"'''\n",
"tempo3 = tempo2.copy()\n",
"tempo3['viral'] = tempo3['viral'].replace({False: None})\n",
"tempo3 = tempo3.groupby(by='virality_followers').count()[['text', 'viral']].rename(columns={'text':'tweets'})\n",
"tempo3['viral_cumsum'] = tempo3.viral.cumsum()\n",
"tempo3\n",
"'''"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"min_threshold = viral_dataset_with_users.virality_followers.min()\n",
"max_threshold = viral_dataset_with_users.virality_followers.max()\n",
"display(f\"sampling from {min_threshold} to {max_threshold}\")\n",
"thresholds_space = np.linspace(min_threshold, max_threshold, num=10000)\n",
"\n",
"number_of_viral_tweets = len(viral_dataset_with_users[viral_dataset_with_users.viral]) \n",
"\n",
"percentages_of_viral_covered = []\n",
"nb_of_tweets_labeled_as_viral = []\n",
"\n",
"for i in thresholds_space:\n",
" new_tweets_labeled = viral_dataset_with_users[viral_dataset_with_users.virality_followers >= i]\n",
" percentage_of_viral_covered = len(new_tweets_labeled[new_tweets_labeled.viral]) / number_of_viral_tweets\n",
" nb_of_tweets_labeled_as_viral.append(len(new_tweets_labeled))\n",
" percentages_of_viral_covered.append(percentage_of_viral_covered)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"result_to_plot = pd.DataFrame({'percentage_of_viral_covered':percentages_of_viral_covered, 'nb_of_tweets_labeled_as_viral':nb_of_tweets_labeled_as_viral, 'thresholds': thresholds_space})\n",
"\n",
"px.scatter(\n",
" result_to_plot,\n",
" x='percentage_of_viral_covered',\n",
" y='nb_of_tweets_labeled_as_viral', log_y=True, hover_name='thresholds')"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"result_to_plot.to_csv('new_tweets_labeled_vs_percentage_of_viral.csv', index=False)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### 1.2.4 Comparing several metrics wrt distributions of viral tweets covered"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def plot_distribution_for_metric(\n",
" df, metric='virality_followers', num_experiments=1000, generate_thresholds_from_viral_quantiles=True, min_threshold=None, max_threshold=None, remove_duplicates=True, output_filename=None):\n",
" viral_tweets = df[df.viral]\n",
" number_of_viral_tweets = len(viral_tweets)\n",
" \n",
" if not generate_thresholds_from_viral_quantiles: \n",
" # If not, generate a linear space of the thresholds between min and max of the metric values\n",
" if not min_threshold:\n",
" min_threshold = df[metric].min()\n",
" if not max_threshold:\n",
" max_threshold = df[metric].max()\n",
" display(f\"sampling from {min_threshold} to {max_threshold}\")\n",
" thresholds_space = np.linspace(min_threshold, max_threshold, num=num_experiments)\n",
" else:\n",
" # Take quantiles of metric for different percentages of viral tweets covered (from 0 to 100)\n",
" thresholds_space = viral_tweets[metric].quantile([i / 100 for i in range(101)]) \n",
" display(f\"sampling from {thresholds_space.min()} to {thresholds_space.max()}\")\n",
"\n",
" percentages_of_viral_covered = []\n",
" nb_of_tweets_labeled_as_viral = []\n",
"\n",
" for i in thresholds_space:\n",
" new_tweets_labeled = df[df[metric] >= i]\n",
" percentage_of_viral_covered = len(new_tweets_labeled[new_tweets_labeled.viral]) / number_of_viral_tweets\n",
" nb_of_tweets_labeled_as_viral.append(len(new_tweets_labeled))\n",
" percentages_of_viral_covered.append(percentage_of_viral_covered)\n",
" \n",
" results_to_plot = pd.DataFrame({\n",
" f'percentage_of_viral_covered_{metric}':percentages_of_viral_covered,\n",
" f'nb_of_tweets_labeled_as_viral_{metric}':nb_of_tweets_labeled_as_viral,\n",
" f'thresholds_{metric}': thresholds_space})\n",
"\n",
" #if remove_duplicates:\n",
" # results_to_plot = results_to_plot.sort_values(by='nb_of_tweets_labeled_as_viral').drop_duplicates(subset=['percentage_of_viral_covered'], keep='first')\n",
"\n",
" # Discard rows where 100% of viral tweets are covered\n",
" #results_to_plot = results_to_plot[results_to_plot.percentage_of_viral_covered < 1.0]\n",
" # TODO: take min of 100% coverage\n",
"\n",
" fig = px.scatter(\n",
" results_to_plot,\n",
" x=f'percentage_of_viral_covered_{metric}',\n",
" y=f'nb_of_tweets_labeled_as_viral_{metric}', hover_name=f'thresholds_{metric}')#log_y=True, trendline='ols' \n",
"\n",
" fig.update_layout(title_text=f\"Percentage of viral covered vs new tweets labeled as viral according to varying metric {metric}\")\n",
" fig.show()\n",
"\n",
" display(f\"Result length {len(results_to_plot)}\")\n",
" if not output_filename:\n",
" output_filename = metric\n",
" results_to_plot.to_csv(f'{output_filename}_viral_covered_vs_new_tweets_labeled.csv', index=False) \n",
" \n",
" return results_to_plot"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"#viral_dataset_with_users = viral_dataset_with_users.groupby(by='virality_followers').count()\n",
"METRIC_1 = 'virality_followers'\n",
"viral_dataset_with_users = pd.read_parquet(f\"{PROCESSED_PATH_VIRAL}/all_tweets.parquet.gzip\")\n",
"# Applying the second metric on the viral dataset\n",
"viral_dataset_with_users[METRIC_1] = viral_dataset_with_users['retweet_count'] / viral_dataset_with_users['followers_count'].astype(\"float64\")\n",
"# Handle division by zero if user has 0 followers\n",
"viral_dataset_with_users[METRIC_1] = viral_dataset_with_users[METRIC_1].replace({np.inf: 0.0})"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"df_1 = plot_distribution_for_metric(viral_dataset_with_users, metric='virality_followers', num_experiments=10000)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Metric 2: retweet / user avg retweets\n",
"METRIC_2 = 'virality_avg_retweets'\n",
"viral_users_retweet_statistics = viral_dataset_with_users.groupby(by='author_id').retweet_count.agg(['min', 'mean', 'max', 'median'])\n",
"viral_users_retweet_statistics = viral_users_retweet_statistics.rename(columns={\n",
" \"min\": \"min_user_retweets\", \"max\": \"max_user_retweets\", \"mean\": \"mean_user_retweets\", \"median\": \"median_user_retweets\"})\n",
"\n",
"viral_dataset_with_users = viral_dataset_with_users.merge(viral_users_retweet_statistics, on='author_id')\n",
"\n",
"viral_dataset_with_users[METRIC_2] = viral_dataset_with_users['retweet_count'] / viral_dataset_with_users['mean_user_retweets'].astype(\"float64\")\n",
"# Handle division by zero if user has 0 followers\n",
"viral_dataset_with_users[METRIC_2] = viral_dataset_with_users[METRIC_2].replace({np.inf: 0.0})"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"df_2 = plot_distribution_for_metric(viral_dataset_with_users, metric='virality_avg_retweets', num_experiments=10000)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Metric 3: Minimum retweet count (Hard threshold)\n",
"METRIC_3 = 'retweet_count'\n",
"\n",
"viral_tweets = viral_dataset_with_users[viral_dataset_with_users.viral]\n",
"min_viral_retweet_count = viral_tweets.retweet_count.min()\n",
"max_viral_retweet_count = viral_tweets.retweet_count.max()\n",
"\n",
"df_3 = plot_distribution_for_metric(\n",
" viral_dataset_with_users, metric=METRIC_3, num_experiments=10000,\n",
" min_threshold=min_viral_retweet_count, max_threshold=max_viral_retweet_count, generate_thresholds_from_viral_quantiles=False,\n",
" output_filename='hard_threshold')"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Metric 4 from Maldonado paper 'Virality Prediction for News Tweets Using RoBERTa'\n",
"def roberta_paper_metric(x):\n",
" g = x['retweet_count'] + x['like_count']\n",
" h = x['followers_count'] - x['following_count']\n",
" A = 10\n",
"\n",
" r = max(x['retweet_count'], 1)\n",
" f = max(x['like_count'], 1)\n",
" w = max(x['followers_count'], 1)\n",
" d = max(x['following_count'], 1)\n",
" h = max(h, 1)\n",
"\n",
" num = g * d * (A * r + f)\n",
" denom = w * r * (A * d + h)\n",
" #if denom == 0:\n",
" # return 0\n",
" return num / denom"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"METRIC_4 = 'roberta_paper_metric'\n",
"viral_dataset_with_users[METRIC_4] = viral_dataset_with_users.apply(lambda x: roberta_paper_metric(x), axis='columns')\n",
"\n",
"df_4 = plot_distribution_for_metric(\n",
" viral_dataset_with_users, metric=METRIC_4, num_experiments=100000)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"METRIC_5 = 'virality_retweet_percentile_per_user'\n",
"\n",
"# Take only tweets with positive retweet count, otherwise the quantiles will be very heavy-tailed\n",
"#tweets_with_retweets = viral_dataset_with_users[viral_dataset_with_users.retweet_count > 0]\n",
"\n",
"viral_tweets = viral_dataset_with_users[viral_dataset_with_users.viral]\n",
"percentiles = [i/100 for i in range(101)]\n",
"number_of_viral_tweets = len(viral_tweets)\n",
"\n",
"percentages_of_viral_covered = []\n",
"nb_of_tweets_labeled_as_viral = []\n",
"\n",
"for i in tqdm(percentiles):\n",
" temp = viral_dataset_with_users.groupby(by='author_id')[['retweet_count']].quantile(i).rename(columns={'retweet_count': f'percentile_{i}'})\n",
" temp = viral_dataset_with_users.merge(temp, on='author_id')\n",
"\n",
" new_tweets_labeled = temp[temp['retweet_count'] >= temp[f'percentile_{i}']]\n",
" percentage_of_viral_covered = len(new_tweets_labeled[new_tweets_labeled.viral]) / number_of_viral_tweets\n",
" nb_of_tweets_labeled_as_viral.append(len(new_tweets_labeled))\n",
" percentages_of_viral_covered.append(percentage_of_viral_covered)\n",
"\n",
"df_5 = pd.DataFrame({\n",
" f'percentage_of_viral_covered_{METRIC_5}':percentages_of_viral_covered,\n",
" f'nb_of_tweets_labeled_as_viral_{METRIC_5}':nb_of_tweets_labeled_as_viral,\n",
" f'thresholds_{METRIC_5}': percentiles})\n",
"\n",
"fig = px.scatter(\n",
" df_5,\n",
" x=f'percentage_of_viral_covered_{METRIC_5}',\n",
" y=f'nb_of_tweets_labeled_as_viral_{METRIC_5}', hover_name=f'thresholds_{METRIC_5}')#log_y=True, trendline='ols' \n",
"\n",
"fig.update_layout(title_text=f\"Percentage of viral covered vs new tweets labeled as viral according to varying metric {METRIC_5}\")\n",
"fig.show()\n",
"\n",
"display(f\"Result length {len(df_5)}\")\n",
"df_5.to_csv(f'{METRIC_5}_viral_covered_vs_new_tweets_labeled.csv', index=False)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Metric 6: Median\n",
"METRIC_6 = 'virality_median_retweets'\n",
"\n",
"positive_median_dataset = viral_dataset_with_users[viral_dataset_with_users['median_user_retweets'] > 0].copy()\n",
"positive_median_dataset.loc[:, METRIC_6] = positive_median_dataset['retweet_count'] / positive_median_dataset['median_user_retweets'].astype(\"float64\")\n",
"# Handle division by zero if user has 0 followers\n",
"positive_median_dataset.loc[:, METRIC_6] = positive_median_dataset[METRIC_6].replace({np.inf: 0.0, np.nan:0.0})"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"df_6 = plot_distribution_for_metric(\n",
" positive_median_dataset, metric=METRIC_6, num_experiments=10000, remove_duplicates=True)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# log(retweet_counts) / followers_count\n",
"METRIC_7 = 'log_retweets_over_followers'\n",
"\n",
"positive_retweet_and_follower_count = viral_dataset_with_users[(viral_dataset_with_users.retweet_count > 0) & (viral_dataset_with_users.followers_count > 0)].copy()\n",
"\n",
"positive_retweet_and_follower_count.loc[:, METRIC_7] = (np.log(positive_retweet_and_follower_count['retweet_count']) / positive_retweet_and_follower_count['followers_count']).astype(\"float64\")\n",
"positive_retweet_and_follower_count.loc[:, METRIC_7] = positive_retweet_and_follower_count[METRIC_7].replace({np.inf: 0.0, np.nan:0.0})\n",
"\n",
"df_7 = plot_distribution_for_metric(\n",
" positive_retweet_and_follower_count, metric=METRIC_7, num_experiments=10000, remove_duplicates=True)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"METRIC_8 = 'retweets_over_log_followers'\n",
"\n",
"positive_retweet_and_follower_count.loc[:, METRIC_8] = (positive_retweet_and_follower_count['retweet_count'] / np.log(positive_retweet_and_follower_count['followers_count'])).astype(\"float64\")\n",
"positive_retweet_and_follower_count.loc[:, METRIC_8] = positive_retweet_and_follower_count[METRIC_8].replace({np.inf: 0.0, np.nan:0.0})\n",
"\n",
"df_8 = plot_distribution_for_metric(\n",
" positive_retweet_and_follower_count, metric=METRIC_8, num_experiments=10000, remove_duplicates=True)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"METRIC_9 = 'log_retweets_over_log_followers'\n",
"\n",
"positive_retweet_and_follower_count.loc[:, METRIC_9] = (np.log(positive_retweet_and_follower_count['retweet_count']) / np.log(positive_retweet_and_follower_count['followers_count'])).astype(\"float64\")\n",
"positive_retweet_and_follower_count.loc[:, METRIC_9] = positive_retweet_and_follower_count[METRIC_9].replace({np.inf: 0.0, np.nan:0.0})\n",
"\n",
"df_9 = plot_distribution_for_metric(\n",
" positive_retweet_and_follower_count, metric=METRIC_9, num_experiments=10000, remove_duplicates=True)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"final_result = pd.concat([df_1, df_2, df_3, df_4, df_5, df_6, df_7, df_8, df_9], axis=1)\n",
"final_result.to_csv('final_result_viral_coverage.csv')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 1.3 Viral Dataset Exploration: Comparison between viral and non viral tweets using other features "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# TODO: Only take viral tweets from scraped. Since sentiment is already computed on the other dataset, we relabel dataset viral by checking if in scraped ids \n",
"# (DONE)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"viral_dataset_labeled = pd.read_parquet(f'{PROCESSED_PATH_VIRAL}/all_tweets.parquet.gzip')"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"display(f\"{len(viral_dataset_labeled[viral_dataset_labeled.viral])} viral tweets out of {len(viral_dataset_labeled)}\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### 1.3.1 - Language"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"languages_aggregates = viral_dataset_labeled.groupby(by='lang', as_index=False)[['id']].count().rename(columns={'id': 'count'})\n",
"languages_aggregates = languages_aggregates.sort_values(by='count', ascending=False)\n",
"languages_aggregates.loc[languages_aggregates['count'] < 10000, 'lang'] = 'Other Languages'\n",
"fig = px.pie(languages_aggregates, values='count', names='lang', title='Distribution of Tweets languages')\n",
"\n",
"fig.update_layout(\n",
" autosize=False,\n",
" width=500,\n",
" height=500\n",
")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"pd.crosstab(index = viral_dataset_labeled['lang'] == 'en', columns=viral_dataset_labeled['viral']) "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### 1.3.2 - Media"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Has media\n",
"labels = [\"Media\", \"No Media\"]\n",
"viral_has_media = len(viral_dataset_labeled[(viral_dataset_labeled.viral == True) & (viral_dataset_labeled.has_media == True)])\n",
"viral_no_media = len(viral_dataset_labeled[(viral_dataset_labeled.viral == True) & (viral_dataset_labeled.has_media == False)])\n",
"normal_has_media = len(viral_dataset_labeled[(viral_dataset_labeled.viral == False) & (viral_dataset_labeled.has_media == True)])\n",
"normal_no_media = len(viral_dataset_labeled[(viral_dataset_labeled.viral == False) & (viral_dataset_labeled.has_media == False)])\n",
"\n",
"\n",
"# Create subplots: use 'domain' type for Pie subplot\n",
"fig = make_subplots(rows=1, cols=2, specs=[[{'type':'domain'}, {'type':'domain'}]])\n",
"fig.add_trace(go.Pie(labels=labels, values=[viral_has_media, viral_no_media], name=\"Viral with Media\"),\n",
" 1, 1)\n",
"fig.add_trace(go.Pie(labels=labels, values=[normal_has_media, normal_no_media], name=\"Tweet with Media\"),\n",
" 1, 2)\n",
"\n",
"# Use `hole` to create a donut-like pie chart\n",
"fig.update_traces(hole=.4, hoverinfo=\"label+percent+name\")\n",
"\n",
"fig.update_layout(\n",
" width=1000,\n",
" height=500,\n",
" title_text=\"Percentage of tweets with some kind of media\",\n",
" # Add annotations in the center of the donut pies.\n",
" annotations=[dict(text='Viral', x=0.18, y=0.5, font_size=20, showarrow=False),\n",
" dict(text='Non-Viral', x=0.82, y=0.5, font_size=20, showarrow=False)])\n",
"fig.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Calculating the p-value between the target `viral` and `has_media`\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from scipy.stats import chi2_contingency \n",
"\n",
"# Calculating the p-value\n",
"contingency_media = pd.crosstab(index = viral_dataset_labeled['has_media'], columns=viral_dataset_labeled['viral']) \n",
"display(contingency_media)\n",
"# Display with percentages\n",
"display(pd.crosstab(index = viral_dataset_labeled['has_media'], columns=viral_dataset_labeled['viral'], normalize='columns') )\n",
"\n",
"c, p, dof, expected = chi2_contingency(contingency_media) \n",
"display(f'p-value {p}')\n",
"c, p, dof, expected"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Finding**: Viral tweets have more chance of having some kind of media (Video, Image, GIF..) embedded than non viral tweets."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### 1.3.2 - Context annotations (Topics)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"viral_tweets_topic_domains = viral_dataset_labeled[viral_dataset_labeled.viral == True] \\\n",
" .explode('topic_domains') \\\n",
" .dropna(axis=0, subset=['topic_domains']) \\\n",
" .topic_domains \n",
"\n",
"tweets_topic_domains = viral_dataset_labeled[viral_dataset_labeled.viral == False] \\\n",
" .explode('topic_domains') \\\n",
" .dropna(axis=0, subset=['topic_domains']) \\\n",
" .topic_domains\n",
"\n",
"viral_topics_domains_sorted = viral_tweets_topic_domains.groupby(viral_tweets_topic_domains).count().sort_values(ascending=False)\n",
"tweet_topics_domains_sorted = tweets_topic_domains.groupby(tweets_topic_domains).count().sort_values(ascending=False)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import pickle\n",
"\n",
"with open(f'{DATA_PATH}/topic_domains.pickle', 'rb') as handle:\n",
" topic_domains = pickle.load(handle)\n",
"\n",
"top_10_viral_topic_domains = viral_topics_domains_sorted[:10]\n",
"top_10_tweet_topic_domains = tweet_topics_domains_sorted[:10]\n",
"\n",
"display(f\"Top 10 topic domains in viral tweets: \\n {[topic_domains.get(x)['name'] for x in top_10_viral_topic_domains.index.values]}\")\n",
"display(f\"Top 10 topic domains in general tweets: \\n {[topic_domains.get(x)['name'] for x in top_10_tweet_topic_domains.index.values]}\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"viral_labels = [topic_domains.get(x)['name'] for x in top_10_viral_topic_domains.index.values]\n",
"non_viral_labels = [topic_domains.get(x)['name'] for x in top_10_tweet_topic_domains.index.values]\n",
"\n",
"# Create subplots: use 'domain' type for Pie subplot\n",
"fig2 = make_subplots(rows=1, cols=2, specs=[[{'type':'domain'}, {'type':'domain'}]])\n",
"fig2.add_trace(go.Pie(labels=viral_labels, values=top_10_viral_topic_domains.values, name=\"Viral Tweet Topic domain\"),\n",
" 1, 1)\n",
"fig2.add_trace(go.Pie(labels=non_viral_labels, values=top_10_tweet_topic_domains.values, name=\"Non-Viral Tweet Topic domain\"),\n",
" 1, 2)\n",
"\n",
"# Use `hole` to create a donut-like pie chart\n",
"fig2.update_traces(hole=.4, hoverinfo=\"label+percent+name\")\n",
"\n",
"fig2.update_layout(\n",
" width=1000,\n",
" height=500,\n",
" title_text=\"Top 10 topic domains for viral vs non-viral tweets\",\n",
" # Add annotations in the center of the donut pies.\n",
" annotations=[dict(text='Viral', x=0.18, y=0.5, font_size=20, showarrow=False),\n",
" dict(text='Non-Viral', x=0.82, y=0.5, font_size=20, showarrow=False)])\n",
"fig2.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### 1.3.3 - Tweet Length"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"viral_dataset_labeled.loc[:, 'tweet_length'] = viral_dataset_labeled.text.apply(len)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"display(viral_dataset_labeled[['tweet_length', 'retweet_count']].corr())\n",
"\n",
"avg_tweet_length_viral = viral_dataset_labeled[viral_dataset_labeled.viral].tweet_length.mean()\n",
"avg_tweet_length_non_viral = viral_dataset_labeled[~viral_dataset_labeled.viral].tweet_length.mean()\n",
"\n",
"display(f'viral avg tweet length: {avg_tweet_length_viral} \\n non-viral avg tweet length: {avg_tweet_length_non_viral}')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Some tweets are replies to others so **mentions are automatically inserted at the beginning of the tweet**, but they do not count in the Twitter max character count, so we should discard them."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"viral_dataset_labeled.loc[:, \"text\"] = viral_dataset_labeled.text.apply(clear_reply_mentions)\n",
"viral_dataset_labeled.loc[:, 'tweet_length'] = viral_dataset_labeled.text.apply(len)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"display(viral_dataset_labeled[['tweet_length', 'retweet_count']].corr())\n",
"\n",
"avg_tweet_length_viral = viral_dataset_labeled[viral_dataset_labeled.viral].tweet_length.mean()\n",
"avg_tweet_length_non_viral = viral_dataset_labeled[~viral_dataset_labeled.viral].tweet_length.mean()\n",
"\n",
"display(f'viral avg tweet length: {avg_tweet_length_viral} \\n non-viral avg tweet length: {avg_tweet_length_non_viral}')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Calculating the welch’s t-test (scipy t-test) for continuous variable `tweet_length`"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from scipy.stats import ttest_ind\n",
"\n",
"ttest_ind(viral_dataset_labeled[viral_dataset_labeled.viral].tweet_length, viral_dataset_labeled[~viral_dataset_labeled.viral].tweet_length, equal_var=False)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### 1.3.4 - Sentiment "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"For the sentiment analysis, we used huggingface's [default sentiment analysis model](https://huggingface.co/distilbert-base-uncased-finetuned-sst-2-english?text=I+like+you.+I+love+you). We instantiate a huggingface pipeline using that default model, and we pass the tweets text to it, outputting a **label** (e.g. POSITIVE, NEGATIVE) alongside a **confidence score**. This will only be applied to english tweets.\n",
"\n",
"**NOTE**: Feel free to skip the following cells if you already have the processed data. Sentiment analysis takes some time (around 2 hours on the whole data). "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from transformers import pipeline\n",
"\n",
"# Device = 0 means it will use the Cuda at index 0\n",
"sentiment_classifier = pipeline(\"sentiment-analysis\", device=0)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This will only be applied to **english tweets**. All the viral tweets we scraped are in English, so we won't be losing viral data when filtering."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"english_viral_dataset = viral_dataset_labeled[viral_dataset_labeled.lang == 'en']\n",
"english_viral_dataset"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Here we use the pandas `apply` function, with `result_type` to *expand*, so that the sentiment scores and label will be output into different columns."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"applied = english_viral_dataset.apply(lambda x: sentiment_classifier(x.text)[0], axis=1, result_type='expand')\n",
"#pd.concat([small_test_set, applied], axis='columns')\n",
"applied"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"sentiment_features = pd.concat([english_viral_dataset, applied], axis=1)\n",
"sentiment_features"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"sentiment_features = sentiment_features.rename(columns={\"label\": \"sentiment\", \"score\": \"sentiment_score\"})"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"sentiment_features.to_parquet(f\"{PROCESSED_PATH_VIRAL}/all_english_tweets_with_users_with_sentiment.parquet.gzip\", index=False, compression=\"gzip\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Get the processed data already"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"sentiment_features = pd.read_parquet(f\"{PROCESSED_PATH_VIRAL}/all_english_tweets_with_users_with_sentiment.parquet.gzip\")\n",
"display(f\"{len(sentiment_features[sentiment_features.viral])} viral tweets out of {len(sentiment_features)}\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Tweets with sentiment scores over 70%\n",
"display(f\"Tweets with sentiment analysis confidence scores above 0.7: {len(sentiment_features[sentiment_features.sentiment_score > 0.7])}\")\n",
"display(f\"{len(sentiment_features[sentiment_features.sentiment == 'POSITIVE'])} positive tweets\")\n",
"display(f\"{len(sentiment_features[sentiment_features.sentiment == 'NEGATIVE'])} negative tweets\")\n",
"\n",
"confident_sentiment_tweets = sentiment_features[sentiment_features.sentiment_score > 0.7]"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# We keep only retweeted tweets to pan out tweets with zero retweets with little utility.\n",
"#retweeted_tweets = confident_sentiment_tweets[confident_sentiment_tweets.retweet_count > 0]\n",
"\n",
"labels = [\"Positive\", \"Negative\"]\n",
"viral_positive = len(confident_sentiment_tweets[(confident_sentiment_tweets.viral == True) & (confident_sentiment_tweets.sentiment == 'POSITIVE')])\n",
"viral_negative = len(confident_sentiment_tweets[(confident_sentiment_tweets.viral == True) & (confident_sentiment_tweets.sentiment == 'NEGATIVE')])\n",
"normal_positive = len(confident_sentiment_tweets[(confident_sentiment_tweets.viral == False) & (confident_sentiment_tweets.sentiment == 'POSITIVE')])\n",
"normal_negative = len(confident_sentiment_tweets[(confident_sentiment_tweets.viral == False) & (confident_sentiment_tweets.sentiment == 'NEGATIVE')])\n",
"\n",
"\n",
"# Create subplots: use 'domain' type for Pie subplot\n",
"fig = make_subplots(rows=1, cols=2, specs=[[{'type':'domain'}, {'type':'domain'}]])\n",
"fig.add_trace(go.Pie(labels=labels, values=[viral_positive, viral_negative], name=\"Positive Viral Tweets\"),\n",
" 1, 1)\n",
"fig.add_trace(go.Pie(labels=labels, values=[normal_positive, normal_negative], name=\"Positive Non-Viral Tweets\"),\n",
" 1, 2)\n",
"\n",
"# Use `hole` to create a donut-like pie chart\n",
"fig.update_traces(hole=.4, hoverinfo=\"label+percent+name\")\n",
"\n",
"fig.update_layout(\n",
" width=1000,\n",
" height=500,\n",
" title_text=\"Distribution of positive and negative sentiment in viral vs non-viral tweets\",\n",
" # Add annotations in the center of the donut pies.\n",
" annotations=[dict(text='Viral', x=0.18, y=0.5, font_size=20, showarrow=False),\n",
" dict(text='Non-Viral', x=0.82, y=0.5, font_size=20, showarrow=False)])\n",
"fig.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Calculating the p-value between the target `viral` and positive sentiment\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from scipy.stats import chi2_contingency \n",
"\n",
"#confident_sentiment_tweets.loc[:, 'is_positive'] = confident_sentiment_tweets.sentiment == 'POSITIVE'\n",
"\n",
"# Calculating the p-value\n",
"contingency_sentiment = pd.crosstab(index = confident_sentiment_tweets['sentiment'], columns=confident_sentiment_tweets['viral']) \n",
"# Display with percentages\n",
"contingency_sentiment_normalized_percentage = pd.crosstab(\n",
" index = confident_sentiment_tweets['sentiment'], columns=confident_sentiment_tweets['viral'], normalize='columns') \n",
"display(contingency_sentiment_normalized_percentage)\n",
"\n",
"c, p, dof, expected = chi2_contingency(contingency_sentiment) \n",
"display(f'p-value {p}')\n",
"c, p, dof, expected"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Calculating the p-value between the target `viral` and negative sentiment\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from scipy.stats import chi2_contingency \n",
"\n",
"confident_sentiment_tweets.loc[:, 'is_negative'] = confident_sentiment_tweets.sentiment == 'NEGATIVE'\n",
"\n",
"# Calculating the p-value\n",
"contingency_negative_sentiment = pd.crosstab(index = confident_sentiment_tweets['is_negative'], columns=confident_sentiment_tweets['viral']) \n",
"# Display with percentages\n",
"contingency_negative_sentiment_normalized_percentage = pd.crosstab(\n",
" index = confident_sentiment_tweets['is_negative'], columns=confident_sentiment_tweets['viral'], normalize='columns') \n",
"display(contingency_negative_sentiment_normalized_percentage)\n",
"\n",
"c, p, dof, expected = chi2_contingency(contingency_negative_sentiment) \n",
"display(f'p-value {p}')\n",
"c, p, dof, expected"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"'''\n",
"import spacy\n",
"import vaderSentiment\n",
"from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer\n",
"\n",
"nlp = spacy.load(\"en_core_web_sm\")\n",
"\n",
"spacy_stopwords = spacy.lang.en.stop_words.STOP_WORDS\n",
"print('Number of stop words: %d' % len(spacy_stopwords))\n",
"print('First ten stop words:',list(spacy_stopwords)[:10])\n",
"'''"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"'''\n",
"# Remove new lines \n",
"remove_new_lines = lambda x: \" \".join(x.split())\n",
"viral_dataset_labeled['processed_text'] = viral_dataset_labeled['text'].apply(remove_new_lines)\n",
"\n",
"\n",
"english_tweets = viral_dataset_labeled[viral_dataset_labeled.lang == 'en']\n",
"'''"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### 1.3.5 - Number of hashtags "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"viral_dataset_labeled.loc[:, \"nb_of_hashtags\"] = viral_dataset_labeled.hashtags.apply(lambda x: len(x) if np.all(x) else 0)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"labels = [\"Hashtags\", \"No Hashtags\"]\n",
"viral_has_hashtags = len(viral_dataset_labeled[(viral_dataset_labeled.viral) & (viral_dataset_labeled.nb_of_hashtags >= 1)])\n",
"viral_no_hashtags = len(viral_dataset_labeled[(viral_dataset_labeled.viral) & (viral_dataset_labeled.nb_of_hashtags == 0)])\n",
"normal_has_hashtags = len(viral_dataset_labeled[(~viral_dataset_labeled.viral) & (viral_dataset_labeled.nb_of_hashtags >= 1)])\n",
"normal_no_hashtags = len(viral_dataset_labeled[(~viral_dataset_labeled.viral) & (viral_dataset_labeled.nb_of_hashtags == 0)])\n",
"\n",
"\n",
"# Create subplots: use 'domain' type for Pie subplot\n",
"fig = make_subplots(rows=1, cols=2, specs=[[{'type':'domain'}, {'type':'domain'}]])\n",
"fig.add_trace(go.Pie(labels=labels, values=[viral_has_hashtags, viral_no_hashtags], name=\"Viral with Hashtags\"),\n",
" 1, 1)\n",
"fig.add_trace(go.Pie(labels=labels, values=[normal_has_hashtags, normal_no_hashtags], name=\"Tweet with No Hashtags\"),\n",
" 1, 2)\n",
"\n",
"# Use `hole` to create a donut-like pie chart\n",
"fig.update_traces(hole=.4, hoverinfo=\"label+percent+name\")\n",
"\n",
"fig.update_layout(\n",
" width=1000,\n",
" height=500,\n",
" title_text=\"Percentage of tweets with hashtags\",\n",
" # Add annotations in the center of the donut pies.\n",
" annotations=[dict(text='Viral', x=0.18, y=0.5, font_size=20, showarrow=False),\n",
" dict(text='Non-Viral', x=0.82, y=0.5, font_size=20, showarrow=False)])\n",
"fig.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Calculating the p-value between the target `viral` and `has_hashtags`\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from scipy.stats import chi2_contingency \n",
"\n",
"viral_dataset_labeled['has_hashtags'] = viral_dataset_labeled.nb_of_hashtags >= 1\n",
"\n",
"# Calculating the p-value\n",
"contingency_has_hashtags = pd.crosstab(index = viral_dataset_labeled['has_hashtags'], columns=viral_dataset_labeled['viral']) \n",
"# Display with percentages\n",
"contingency_has_hashtags_normalized_percentage = pd.crosstab(\n",
" index = viral_dataset_labeled['has_hashtags'], columns=viral_dataset_labeled['viral'], normalize='columns') \n",
"display(contingency_has_hashtags_normalized_percentage)\n",
"\n",
"c, p, dof, expected = chi2_contingency(contingency_has_hashtags) \n",
"display(f'p-value {p}')\n",
"c, p, dof, expected"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### 1.3.6 - Verified account"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Verified account\n",
"labels = [\"Verified\", \"Not verified\"]\n",
"viral_is_verified = len(viral_dataset_labeled[(viral_dataset_labeled.viral) & (viral_dataset_labeled.verified)])\n",
"viral_not_verified = len(viral_dataset_labeled[(viral_dataset_labeled.viral) & (~viral_dataset_labeled.verified)])\n",
"normal_is_verified = len(viral_dataset_labeled[(~viral_dataset_labeled.viral) & (viral_dataset_labeled.verified)])\n",
"normal_not_verified = len(viral_dataset_labeled[(~viral_dataset_labeled.viral) & (~viral_dataset_labeled.verified)])\n",
"\n",
"\n",
"# Create subplots: use 'domain' type for Pie subplot\n",
"fig = make_subplots(rows=1, cols=2, specs=[[{'type':'domain'}, {'type':'domain'}]])\n",
"fig.add_trace(go.Pie(labels=labels, values=[viral_is_verified, viral_not_verified], name=\"Viral with verified accounts\"),\n",
" 1, 1)\n",
"fig.add_trace(go.Pie(labels=labels, values=[normal_is_verified, normal_not_verified], name=\"Tweet with an unverified account\"),\n",
" 1, 2)\n",
"\n",
"# Use `hole` to create a donut-like pie chart\n",
"fig.update_traces(hole=.4, hoverinfo=\"label+percent+name\")\n",
"\n",
"fig.update_layout(\n",
" width=1000,\n",
" height=500,\n",
" title_text=\"Percentage of tweets from verified accounts\",\n",
" # Add annotations in the center of the donut pies.\n",
" annotations=[dict(text='Viral', x=0.18, y=0.5, font_size=20, showarrow=False),\n",
" dict(text='Non-Viral', x=0.82, y=0.5, font_size=20, showarrow=False)])\n",
"fig.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Calculating the p-value between the target `viral` and `is_verified`\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from scipy.stats import chi2_contingency \n",
"\n",
"# Calculating the p-value\n",
"contingency_verified = pd.crosstab(index = viral_dataset_labeled['verified'], columns=viral_dataset_labeled['viral']) \n",
"# Display with percentages\n",
"contingency_verified_normalized_percentage = pd.crosstab(\n",
" index = viral_dataset_labeled['verified'], columns=viral_dataset_labeled['viral'], normalize='columns') \n",
"display(contingency_verified_normalized_percentage)\n",
"\n",
"c, p, dof, expected = chi2_contingency(contingency_verified) \n",
"display(f'p-value {p}')\n",
"c, p, dof, expected"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### 1.3.7 - Has mentions"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"viral_dataset_labeled.loc[:, \"nb_of_mentions\"] = viral_dataset_labeled.mentions.apply(lambda x: len(x) if np.all(x) else 0)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from scipy.stats import chi2_contingency \n",
"\n",
"# Calculating the p-value\n",
"contingency_has_mentions = pd.crosstab(index = viral_dataset_labeled['nb_of_mentions'] > 0, columns=viral_dataset_labeled['viral']) \n",
"display(contingency_has_mentions)\n",
"# Display with percentages\n",
"display(pd.crosstab(index = viral_dataset_labeled['nb_of_mentions'] > 0, columns=viral_dataset_labeled['viral'], normalize='columns') )\n",
"\n",
"c, p, dof, expected = chi2_contingency(contingency_has_mentions) \n",
"display(f'p-value {p}')\n",
"c, p, dof, expected"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### 1.3.8 - Save result of preprocessing to disk"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"viral_dataset_labeled.to_parquet(f'{PROCESSED_PATH_VIRAL}/all_english_tweets_with_users_with_sentiment.parquet.gzip', index=False, compression=\"gzip\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"viral_dataset_labeled.columns\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 1.4 - Covid dataset Exploration"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Here we concern ourselves only with original tweets (no retweets)."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"original_covid_tweets = pd.read_parquet(f\"{COVID_TWEETS_PATH}/all_original_tweets.parquet.gzip\")\n",
"original_covid_tweets.loc[:, \"text\"] = original_covid_tweets.text.apply(clear_reply_mentions)\n",
"\n",
"covid_users = pd.read_parquet(f\"{COVID_TWEETS_PATH}/users.parquet.gzip\")\n",
"\n",
"display(\"--- COVID DATASET ---\")\n",
"\n",
"display(f\"{len(original_covid_tweets)} original (not retweeted) covid tweets collected\")\n",
"display(f\"{len(original_covid_tweets.author_id.unique())} covid users collected\")\n",
"\n",
"original_covid_tweets"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"user_columns = ['author_id', 'followers_count', 'following_count', 'tweet_count', 'protected', 'verified', 'username']\n",
"covid_dataset_with_users = original_covid_tweets.merge(covid_users.rename(columns={'id': 'author_id'})[user_columns], on='author_id')"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Applying the first metric on the covid dataset\n",
"covid_dataset_with_users['virality_followers'] = covid_dataset_with_users['retweet_count'] / covid_dataset_with_users['followers_count'].astype(\"float64\")\n",
"# Handle division by zero if user has 0 followers\n",
"covid_dataset_with_users['virality_followers'] = covid_dataset_with_users.virality_followers.replace({np.inf: 0.0})"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"covid_dataset_with_users"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"px.histogram(covid_dataset_with_users, x='followers_count', y = 'virality_followers', log_y=True)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"covid_dataset_with_users['viral'] = covid_dataset_with_users.virality_followers > 1\n",
"covid_dataset_with_users[covid_dataset_with_users.viral]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 1.4.1 - Language"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"languages_aggregates = covid_dataset_with_users.groupby(by='lang', as_index=False)[['id']].count().rename(columns={'id': 'count'})\n",
"languages_aggregates = languages_aggregates.sort_values(by='count', ascending=False)\n",
"languages_aggregates.loc[languages_aggregates['count'] < 10000, 'lang'] = 'Other Languages'\n",
"fig = px.pie(languages_aggregates, values='count', names='lang', title='Distribution of Tweets languages')\n",
"\n",
"fig.update_layout(\n",
" autosize=False,\n",
" width=500,\n",
" height=500\n",
")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"english_covid_tweets = covid_dataset_with_users[covid_dataset_with_users.lang == 'en']\n",
"display(f\"{len(english_covid_tweets)} english covid tweets\")\n",
"\n",
"english_viral_covid_tweets = english_covid_tweets[english_covid_tweets.viral]\n",
"display(f\"{len(english_viral_covid_tweets)} viral english covid tweets\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 1.4.2 - Media"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Has media\n",
"labels = [\"Media\", \"No Media\"]\n",
"viral_has_media = len(covid_dataset_with_users[(covid_dataset_with_users.viral == True) & (covid_dataset_with_users.has_media == True)])\n",
"viral_no_media = len(covid_dataset_with_users[(covid_dataset_with_users.viral == True) & (covid_dataset_with_users.has_media == False)])\n",
"normal_has_media = len(covid_dataset_with_users[(covid_dataset_with_users.viral == False) & (covid_dataset_with_users.has_media == True)])\n",
"normal_no_media = len(covid_dataset_with_users[(covid_dataset_with_users.viral == False) & (covid_dataset_with_users.has_media == False)])\n",
"\n",
"\n",
"# Create subplots: use 'domain' type for Pie subplot\n",
"fig = make_subplots(rows=1, cols=2, specs=[[{'type':'domain'}, {'type':'domain'}]])\n",
"fig.add_trace(go.Pie(labels=labels, values=[viral_has_media, viral_no_media], name=\"Viral with Media\"),\n",
" 1, 1)\n",
"fig.add_trace(go.Pie(labels=labels, values=[normal_has_media, normal_no_media], name=\"Tweet with Media\"),\n",
" 1, 2)\n",
"\n",
"# Use `hole` to create a donut-like pie chart\n",
"fig.update_traces(hole=.4, hoverinfo=\"label+percent+name\")\n",
"\n",
"fig.update_layout(\n",
" width=1000,\n",
" height=500,\n",
" title_text=\"Percentage of tweets with some kind of media\",\n",
" # Add annotations in the center of the donut pies.\n",
" annotations=[dict(text='Viral', x=0.18, y=0.5, font_size=20, showarrow=False),\n",
" dict(text='Non-Viral', x=0.82, y=0.5, font_size=20, showarrow=False)])\n",
"fig.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 1.4.3 - Tweet Length"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"covid_dataset_with_users.loc[:, 'tweet_length'] = covid_dataset_with_users.text.apply(len)\n",
"covid_dataset_with_users[['tweet_length', 'retweet_count']].corr()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 1.4.4 - Sentiment"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from transformers import pipeline\n",
"\n",
"# Device = 0 means it will use the Cuda at index 0\n",
"sentiment_classifier = pipeline(\"sentiment-analysis\", device=0)\n",
"\n",
"english_covid_dataset = covid_dataset_with_users[covid_dataset_with_users.lang == 'en']\n",
"english_covid_dataset"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Here we compute sentiments again. To avoid having to compute the sentiments again, we've already preprocessed the data and computed the sentiments and saved it to parquet. Feel free to skip the next 2 cells."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"applied = english_covid_dataset.apply(lambda x: sentiment_classifier(x.text)[0], axis=1, result_type='expand')\n",
"#pd.concat([small_test_set, applied], axis='columns')\n",
"applied"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"sentiment_features = pd.concat([english_covid_dataset, applied], axis=1)\n",
"sentiment_features = sentiment_features.rename(columns={\"label\": \"sentiment\", \"score\": \"sentiment_score\"})"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"sentiment_features = pd.read_parquet(f\"{PROCESSED_PATH_COVID}/english_tweets_with_users_with_sentiment.parquet.gzip\")\n",
"sentiment_features"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Tweets with sentiment scores over 70%\n",
"display(f\"Tweets with sentiment analysis confidence scores above 0.7: {len(sentiment_features[sentiment_features.sentiment_score > 0.7])}\")\n",
"display(f\"{len(sentiment_features[sentiment_features.sentiment == 'POSITIVE'])} positive tweets\")\n",
"display(f\"{len(sentiment_features[sentiment_features.sentiment == 'NEGATIVE'])} negative tweets\")\n",
"\n",
"confident_sentiment_tweets = sentiment_features[sentiment_features.sentiment_score > 0.7]"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# We keep only retweeted tweets to pan out tweets with zero retweets with little utility.\n",
"labels = [\"Positive\", \"Negative\"]\n",
"viral_positive = len(confident_sentiment_tweets[(confident_sentiment_tweets.viral == True) & (confident_sentiment_tweets.sentiment == 'POSITIVE')])\n",
"viral_negative = len(confident_sentiment_tweets[(confident_sentiment_tweets.viral == True) & (confident_sentiment_tweets.sentiment == 'NEGATIVE')])\n",
"normal_positive = len(confident_sentiment_tweets[(confident_sentiment_tweets.viral == False) & (confident_sentiment_tweets.sentiment == 'POSITIVE')])\n",
"normal_negative = len(confident_sentiment_tweets[(confident_sentiment_tweets.viral == False) & (confident_sentiment_tweets.sentiment == 'NEGATIVE')])\n",
"\n",
"\n",
"# Create subplots: use 'domain' type for Pie subplot\n",
"fig = make_subplots(rows=1, cols=2, specs=[[{'type':'domain'}, {'type':'domain'}]])\n",
"fig.add_trace(go.Pie(labels=labels, values=[viral_positive, viral_negative], name=\"Positive Viral Tweets\"),\n",
" 1, 1)\n",
"fig.add_trace(go.Pie(labels=labels, values=[normal_positive, normal_negative], name=\"Positive Non-Viral Tweets\"),\n",
" 1, 2)\n",
"\n",
"# Use `hole` to create a donut-like pie chart\n",
"fig.update_traces(hole=.4, hoverinfo=\"label+percent+name\")\n",
"\n",
"fig.update_layout(\n",
" width=1000,\n",
" height=500,\n",
" title_text=\"Distribution of positive and negative sentiment in viral vs non-viral tweets\",\n",
" # Add annotations in the center of the donut pies.\n",
" annotations=[dict(text='Viral', x=0.18, y=0.5, font_size=20, showarrow=False),\n",
" dict(text='Non-Viral', x=0.82, y=0.5, font_size=20, showarrow=False)])\n",
"fig.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 1.4.5 - Number of Hashtags"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"covid_dataset_with_users.loc[:, \"nb_of_hashtags\"] = covid_dataset_with_users.hashtags.apply(lambda x: len(x) if np.all(x) else 0)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"labels = [\"Hashtags\", \"No Hashtags\"]\n",
"viral_has_hashtags = len(covid_dataset_with_users[(covid_dataset_with_users.viral) & (covid_dataset_with_users.nb_of_hashtags >= 1)])\n",
"viral_no_hashtags = len(covid_dataset_with_users[(covid_dataset_with_users.viral) & (covid_dataset_with_users.nb_of_hashtags == 0)])\n",
"normal_has_hashtags = len(covid_dataset_with_users[(~covid_dataset_with_users.viral) & (covid_dataset_with_users.nb_of_hashtags > 1)])\n",
"normal_no_hashtags = len(covid_dataset_with_users[(~covid_dataset_with_users.viral) & (covid_dataset_with_users.nb_of_hashtags == 0)])\n",
"\n",
"\n",
"# Create subplots: use 'domain' type for Pie subplot\n",
"fig = make_subplots(rows=1, cols=2, specs=[[{'type':'domain'}, {'type':'domain'}]])\n",
"fig.add_trace(go.Pie(labels=labels, values=[viral_has_hashtags, viral_no_hashtags], name=\"Viral with Hashtags\"),\n",
" 1, 1)\n",
"fig.add_trace(go.Pie(labels=labels, values=[normal_has_hashtags, normal_no_hashtags], name=\"Tweet with No Hashtags\"),\n",
" 1, 2)\n",
"\n",
"# Use `hole` to create a donut-like pie chart\n",
"fig.update_traces(hole=.4, hoverinfo=\"label+percent+name\")\n",
"\n",
"fig.update_layout(\n",
" width=1000,\n",
" height=500,\n",
" title_text=\"Percentage of tweets with hashtags\",\n",
" # Add annotations in the center of the donut pies.\n",
" annotations=[dict(text='Viral', x=0.18, y=0.5, font_size=20, showarrow=False),\n",
" dict(text='Non-Viral', x=0.82, y=0.5, font_size=20, showarrow=False)])\n",
"fig.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### 1.4.6 - Verified Account"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Has media\n",
"labels = [\"Verified\", \"Not verified\"]\n",
"viral_is_verified = len(covid_dataset_with_users[(covid_dataset_with_users.viral) & (covid_dataset_with_users.verified)])\n",
"viral_not_verified = len(covid_dataset_with_users[(covid_dataset_with_users.viral) & (~covid_dataset_with_users.verified)])\n",
"normal_is_verified = len(covid_dataset_with_users[(~covid_dataset_with_users.viral) & (covid_dataset_with_users.verified)])\n",
"normal_not_verified = len(covid_dataset_with_users[(~covid_dataset_with_users.viral) & (~covid_dataset_with_users.verified)])\n",
"\n",
"\n",
"# Create subplots: use 'domain' type for Pie subplot\n",
"fig = make_subplots(rows=1, cols=2, specs=[[{'type':'domain'}, {'type':'domain'}]])\n",
"fig.add_trace(go.Pie(labels=labels, values=[viral_is_verified, viral_not_verified], name=\"Viral with verified accounts\"),\n",
" 1, 1)\n",
"fig.add_trace(go.Pie(labels=labels, values=[normal_is_verified, normal_not_verified], name=\"Tweet with an unverified account\"),\n",
" 1, 2)\n",
"\n",
"# Use `hole` to create a donut-like pie chart\n",
"fig.update_traces(hole=.4, hoverinfo=\"label+percent+name\")\n",
"\n",
"fig.update_layout(\n",
" width=1000,\n",
" height=500,\n",
" title_text=\"Percentage of tweets from verified accounts\",\n",
" # Add annotations in the center of the donut pies.\n",
" annotations=[dict(text='Viral', x=0.18, y=0.5, font_size=20, showarrow=False),\n",
" dict(text='Non-Viral', x=0.82, y=0.5, font_size=20, showarrow=False)])\n",
"fig.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 1.4.7 - Save dataframe with analysis to disk"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"covid_dataset_with_users.to_parquet(f'{PROCESSED_PATH_COVID}/all_english_tweets_with_users_with_sentiment.parquet.gzip', index=False, compression=\"gzip\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Questions for TJ:\n",
"\n",
"Learn threshold? Use unsupervised learning (anomaly detection), x axis date y retweet count, isolation coordinate\n",
"Ratio\n",
"Try to come up with Different metrics (one cannot be used for second dataset)\n",
"\n",
"Preprocessing:\n",
" - Remove tweets with no retweets or likes? NO\n",
" - Define threshold using the metric? DONE (label above viral tweet)\n",
" - Skewed distribution if we use only Twitter viral tweets (1000) DONE\n",
"- Which features? (Any new ideas)\n",
" - Topic\n",
" - Hashtags relevant? (Most likely different from coronavirus and we already have topics).\n",
" - Has media\n",
" - Sentiment? [TODO]\n",
" - Tweet length [TODO]\n",
" - RETRIEVE USERS THAT LIKED OR RETWEETED USING API [TODO]\n",
" - Word cloud of entities [TODO]\n",
"- Check bigrams and trigrams distribution\n",
"- Normalize features (like, retweets, reply etc...)? DEPENDS, Included in first model, will be removed from second model with covid set.\n",
"- BertTweet [DO NOT REMOVE STOP WORDS FOR LANGUAGE MODELS, FOR ]\n",
"- Next steps (now that data collection part is done and data analysis almost done)\n",
" - Hydrate Covid dataset id\n",
"- Viral generator (Trump generator)\n",
"\n",
"1st classifier: hashtags, twitter entities (context annotations, domain annotations, entities), mentions, domain of urls (youtube.com let’s say)\n",
"2nd classifier: bag of words with tf-idf, remove stopwords and other entities that you used in the 1st classifier\n",
"3rd: language model\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"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.8.15"
},
"vscode": {
"interpreter": {
"hash": "71d2f77bccee14ca7852d7b7a1fa8ea4708b81087104d93973081337557f0ee6"
}
}
},
"nbformat": 4,
"nbformat_minor": 4
}
|