Code
%load_ext lab_black
%load_ext autotime
import numpy as np
import pandas as pdtime: 368 ms (started: 2023-03-22 22:16:52 -07:00)
time: 368 ms (started: 2023-03-22 22:16:52 -07:00)
Samantha D’Alonzo and Max Tegmark (yes, the cosmologist) looked at characterizing various publications by counts of certain phrases and then applied a generalized PCA to get a 2D layout that creditably distributed both left-right and establishment bias. The paper is available at PLOS ONE (and arxiv) and the phrase counts are at kaggle and Max Tegmark’s own webpage.
The phrase counts are divided into different CSV files with different subjects, which incidentally make for a great list of things to not discuss with your relatives at any family gathering:
# note that the "police" subject has an extra trailing underscore
subjects = [
"abortion",
"affirmative_action",
"blm_movement",
"china",
"church_state",
"climate_change",
"cuba",
"espionage",
"guns",
"human_rights",
"islam",
"israel",
"judaism",
"military_spending",
"native_americans",
"nuclear_weapons",
"oil",
"palestine",
"police_",
"prisons",
"private_finance",
"public_finance",
"russia",
"sexual_harrassment",
"tech_censorship",
"universities",
"us_immigration",
"venezuela",
"yemen",
]Below is some code to download the tar file from Max Tegmark’s webpage. Note that I got an issue with the MIT web site not having the latest SSL ciphers. If that gets fixed (or whatever it is that is going on) you shouldn’t need to set the ssl_context and specify the verify argument.
import ssl
import tarfile
from io import BytesIO
import httpx
import pandas as pd
dfs = []
url = "https://space.mit.edu/home/tegmark/phrasebias_data.tar.gz"
# I get an SSLError with a DH_KEY_TOO_SMALL message
# Below is the httpx equivalent to the following requests code
# requests.packages.urllib3.util.ssl_.DEFAULT_CIPHERS += "@SECLEVEL=1"
# https://stackoverflow.com/a/75048832/4096483
ssl_context = ssl.create_default_context()
ssl_context.set_ciphers("DEFAULT:@SECLEVEL=1")
req = httpx.get(url, timeout=10, verify=ssl_context, follow_redirects=True)
with tarfile.open(fileobj=BytesIO(req.content), mode="r") as tar_obj:
for subject in subjects:
try:
fileobj = tar_obj.extractfile(
f"phrasebias_data/phrase_counts/{subject}_counts.csv"
)
if fileobj:
dfs.append(pd.read_csv(fileobj))
except KeyError:
print(f"File not found for {subject}")
continue
df = pd.concat(dfs, sort=True)
df| PHRASE | TOTAL | aljazeera | alternet | americanconservative | americanspectator | americanthinker | antiwar | ap | atlantic | ... | truthdig | usatoday | verge | veteranstoday | vice | voltairenetwork | vox | wapo | wired | wsj | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | pro life | 4849 | 12 | 13 | 68.0 | 10.0 | NaN | NaN | 7 | 16 | ... | 5.0 | 131 | NaN | NaN | 13.0 | NaN | 60 | 242 | NaN | 1.0 |
| 1 | abortion rights | 4851 | 97 | 42 | 15.0 | 5.0 | NaN | NaN | 43 | 63 | ... | 32.0 | 211 | NaN | NaN | 103.0 | NaN | 461 | 585 | NaN | 24.0 |
| 2 | anti abortion | 4067 | 53 | 54 | 4.0 | 0.0 | NaN | NaN | 37 | 49 | ... | 27.0 | 239 | NaN | NaN | 143.0 | NaN | 487 | 29 | NaN | 3.0 |
| 3 | anti choice | 705 | 0 | 54 | 0.0 | 0.0 | NaN | NaN | 0 | 1 | ... | 5.0 | 5 | NaN | NaN | 38.0 | NaN | 14 | 19 | NaN | 0.0 |
| 4 | abortion care | 1215 | 7 | 13 | 0.0 | 1.0 | NaN | NaN | 2 | 2 | ... | 7.0 | 52 | NaN | NaN | 60.0 | NaN | 76 | 64 | NaN | 1.0 |
| ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... |
| 24 | the IRGC | 346 | 21 | 1 | 21.0 | NaN | NaN | 0.0 | 0 | 2 | ... | 9.0 | 1 | NaN | 0.0 | 0.0 | NaN | 19 | 31 | NaN | 14.0 |
| 25 | the JCPOA | 725 | 27 | 10 | 49.0 | NaN | NaN | 6.0 | 3 | 12 | ... | 35.0 | 8 | NaN | 2.0 | 0.0 | NaN | 1 | 33 | NaN | 2.0 |
| 26 | the Yemeni | 1372 | 238 | 4 | 31.0 | NaN | NaN | 15.0 | 2 | 8 | ... | 17.0 | 7 | NaN | 14.0 | 2.0 | NaN | 13 | 86 | NaN | 3.0 |
| 27 | war on Yemen | 678 | 5 | 12 | 252.0 | NaN | NaN | 36.0 | 0 | 1 | ... | 20.0 | 0 | NaN | 2.0 | 0.0 | NaN | 7 | 4 | NaN | 0.0 |
| 28 | terrorism | 3432 | 169 | 30 | 89.0 | NaN | NaN | 21.0 | 25 | 49 | ... | 98.0 | 73 | NaN | 134.0 | 3.0 | NaN | 62 | 322 | NaN | 7.0 |
839 rows × 94 columns
import tarfile
from io import BytesIO
import requests
# Uncomment if you get a SSLError with a DH_KEY_TOO_SMALL message
# https://stackoverflow.com/a/75048832/4096483
requests.packages.urllib3.util.ssl_.DEFAULT_CIPHERS += "@SECLEVEL=1"
dfs = []
url = "https://space.mit.edu/home/tegmark/phrasebias_data.tar.gz"
req = requests.get(url, timeout=10)
with tarfile.open(fileobj=BytesIO(req.content), mode="r") as tar_obj:
for subject in subjects:
fileobj = tar_obj.extractfile(
f"phrasebias_data/phrase_counts/{subject}_counts.csv"
)
dfs.append(pd.read_csv(fileobj))
fileobj.close()
df = pd.concat(dfs, sort=True)
df| PHRASE | TOTAL | aljazeera | alternet | americanconservative | americanspectator | americanthinker | antiwar | ap | atlantic | ... | truthdig | usatoday | verge | veteranstoday | vice | voltairenetwork | vox | wapo | wired | wsj | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | pro life | 4849 | 12 | 13 | 68.0 | 10.0 | NaN | NaN | 7 | 16 | ... | 5.0 | 131 | NaN | NaN | 13.0 | NaN | 60 | 242 | NaN | 1.0 |
| 1 | abortion rights | 4851 | 97 | 42 | 15.0 | 5.0 | NaN | NaN | 43 | 63 | ... | 32.0 | 211 | NaN | NaN | 103.0 | NaN | 461 | 585 | NaN | 24.0 |
| 2 | anti abortion | 4067 | 53 | 54 | 4.0 | 0.0 | NaN | NaN | 37 | 49 | ... | 27.0 | 239 | NaN | NaN | 143.0 | NaN | 487 | 29 | NaN | 3.0 |
| 3 | anti choice | 705 | 0 | 54 | 0.0 | 0.0 | NaN | NaN | 0 | 1 | ... | 5.0 | 5 | NaN | NaN | 38.0 | NaN | 14 | 19 | NaN | 0.0 |
| 4 | abortion care | 1215 | 7 | 13 | 0.0 | 1.0 | NaN | NaN | 2 | 2 | ... | 7.0 | 52 | NaN | NaN | 60.0 | NaN | 76 | 64 | NaN | 1.0 |
| ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... |
| 24 | the IRGC | 346 | 21 | 1 | 21.0 | NaN | NaN | 0.0 | 0 | 2 | ... | 9.0 | 1 | NaN | 0.0 | 0.0 | NaN | 19 | 31 | NaN | 14.0 |
| 25 | the JCPOA | 725 | 27 | 10 | 49.0 | NaN | NaN | 6.0 | 3 | 12 | ... | 35.0 | 8 | NaN | 2.0 | 0.0 | NaN | 1 | 33 | NaN | 2.0 |
| 26 | the Yemeni | 1372 | 238 | 4 | 31.0 | NaN | NaN | 15.0 | 2 | 8 | ... | 17.0 | 7 | NaN | 14.0 | 2.0 | NaN | 13 | 86 | NaN | 3.0 |
| 27 | war on Yemen | 678 | 5 | 12 | 252.0 | NaN | NaN | 36.0 | 0 | 1 | ... | 20.0 | 0 | NaN | 2.0 | 0.0 | NaN | 7 | 4 | NaN | 0.0 |
| 28 | terrorism | 3432 | 169 | 30 | 89.0 | NaN | NaN | 21.0 | 25 | 49 | ... | 98.0 | 73 | NaN | 134.0 | 3.0 | NaN | 62 | 322 | NaN | 7.0 |
839 rows × 94 columns
time: 2.01 s (started: 2023-03-22 22:16:52 -07:00)
Now to do some clean-up:
NaNs in the data are because some publications aren’t included in the different subject analyses. In that case, I am going to set those values to 0.PHRASE column) should be the index.TOTAL (which won’t make sense after transposing). Also, I don’t actually know what it’s a total of, it doesn’t always match the sum of the counts in the publication columns.time: 8.51 ms (started: 2023-03-22 22:16:54 -07:00)
Finally, after transposing the PHRASE is now the name of the columns, rather than the name of the index, which should be publication now anyway. I am sure there is a better way to do this, but this works:
time: 1.15 ms (started: 2023-03-22 22:16:54 -07:00)
| pro life | abortion rights | anti abortion | anti choice | abortion care | pregnancy | kill | medical abortion | family planning | pro abortion | ... | Saudi led coalition | separatists | Special Operations | terrorist | the Houthis | the IRGC | the JCPOA | the Yemeni | war on Yemen | terrorism | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| publication | |||||||||||||||||||||
| aljazeera | 12.0 | 97.0 | 53.0 | 0.0 | 7.0 | 61.0 | 2.0 | 2.0 | 18.0 | 6.0 | ... | 261.0 | 172.0 | 0.0 | 143.0 | 832.0 | 21.0 | 27.0 | 238.0 | 5.0 | 169.0 |
| alternet | 13.0 | 42.0 | 54.0 | 54.0 | 13.0 | 69.0 | 5.0 | 0.0 | 15.0 | 1.0 | ... | 6.0 | 0.0 | 24.0 | 28.0 | 11.0 | 1.0 | 10.0 | 4.0 | 12.0 | 30.0 |
| americanconservative | 68.0 | 15.0 | 4.0 | 0.0 | 0.0 | 8.0 | 1.0 | 0.0 | 0.0 | 3.0 | ... | 44.0 | 14.0 | 5.0 | 82.0 | 121.0 | 21.0 | 49.0 | 31.0 | 252.0 | 89.0 |
| americanspectator | 10.0 | 5.0 | 0.0 | 0.0 | 1.0 | 3.0 | 1.0 | 0.0 | 1.0 | 4.0 | ... | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 |
| americanthinker | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | ... | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 |
| ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... |
| voltairenetwork | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | ... | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 |
| vox | 60.0 | 461.0 | 487.0 | 14.0 | 76.0 | 487.0 | 29.0 | 8.0 | 72.0 | 29.0 | ... | 25.0 | 3.0 | 0.0 | 87.0 | 15.0 | 19.0 | 1.0 | 13.0 | 7.0 | 62.0 |
| wapo | 242.0 | 585.0 | 29.0 | 19.0 | 64.0 | 531.0 | 14.0 | 9.0 | 130.0 | 28.0 | ... | 194.0 | 34.0 | 30.0 | 334.0 | 347.0 | 31.0 | 33.0 | 86.0 | 4.0 | 322.0 |
| wired | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | ... | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 |
| wsj | 1.0 | 24.0 | 3.0 | 0.0 | 1.0 | 26.0 | 0.0 | 0.0 | 9.0 | 2.0 | ... | 18.0 | 2.0 | 0.0 | 27.0 | 16.0 | 14.0 | 2.0 | 3.0 | 0.0 | 7.0 |
92 rows × 839 columns
time: 29.6 ms (started: 2023-03-22 22:16:54 -07:00)
Here are all the sampled publications:
Index(['aljazeera', 'alternet', 'americanconservative', 'americanspectator',
'americanthinker', 'antiwar', 'ap', 'atlantic', 'axios', 'bbc',
'bloomberg', 'breitbart', 'businessinsider', 'buzzfeed', 'canary',
'cbs', 'cnbc', 'cnn', 'commondreams', 'consortium', 'conversation',
'counterpunch', 'dailycaller', 'dailykos', 'dailymail', 'dailywire',
'defenseone', 'economist', 'eff', 'factcheck', 'federalist',
'fivethirtyeight', 'foreignaffairs', 'fox', 'freebeacon',
'globalresearch', 'grayzone', 'guardian', 'huffingtonpost',
'independent', 'infowars', 'intercept', 'jacobinmag', 'jpost',
'koreaherald', 'lewrockwell', 'mintpress', 'motherjones', 'msnbc',
'nationalreview', 'nbc', 'neweasternoutlook', 'newsbud', 'newyorker',
'npr', 'nypost', 'nytimes', 'observerny', 'offguardian', 'opednews',
'pbs', 'peoplesdaily', 'pjmedia', 'propublica', 'psychologytoday',
'rawstory', 'redstate', 'reuters', 'reveal', 'rt', 'science',
'scientificamerican', 'shadowproof', 'slate', 'snopes',
'socialistalternative', 'socialistproject', 'spectator',
'strategicculture', 'techcrunch', 'time', 'townhall', 'truthdig',
'usatoday', 'verge', 'veteranstoday', 'vice', 'voltairenetwork', 'vox',
'wapo', 'wired', 'wsj'],
dtype='object', name='publication')
time: 3.57 ms (started: 2023-03-22 22:16:54 -07:00)
Compared to the paper, the following publications are in the dataset but don’t appear in the generalized principle component plots there (Science and Defense One are mentioned as being included in a correlation analysis):
time: 2.05 ms (started: 2023-03-22 22:16:54 -07:00)
The authors identify two sources of bias:
In both cases they are classified into 5 levels. Unfortunately, these values aren’t provided as downloadable data and attempting to recreate it from the sources above is difficult because:
Instead I have done my best to recreate the values using the media legend of Figure 2 of the paper, which uses color for the left/right bias, and size for the establishment bias. The latter was substantially harder to do than I thought: distinguishing between the smallest two sizes and then within the larger three sizes was not always easy. So expect some mistakes. Also, publications not used in Figure 2 are removed.
| pro life | abortion rights | anti abortion | anti choice | abortion care | pregnancy | kill | medical abortion | family planning | pro abortion | ... | Saudi led coalition | separatists | Special Operations | terrorist | the Houthis | the IRGC | the JCPOA | the Yemeni | war on Yemen | terrorism | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| publication | |||||||||||||||||||||
| aljazeera | 12.0 | 97.0 | 53.0 | 0.0 | 7.0 | 61.0 | 2.0 | 2.0 | 18.0 | 6.0 | ... | 261.0 | 172.0 | 0.0 | 143.0 | 832.0 | 21.0 | 27.0 | 238.0 | 5.0 | 169.0 |
| alternet | 13.0 | 42.0 | 54.0 | 54.0 | 13.0 | 69.0 | 5.0 | 0.0 | 15.0 | 1.0 | ... | 6.0 | 0.0 | 24.0 | 28.0 | 11.0 | 1.0 | 10.0 | 4.0 | 12.0 | 30.0 |
| americanconservative | 68.0 | 15.0 | 4.0 | 0.0 | 0.0 | 8.0 | 1.0 | 0.0 | 0.0 | 3.0 | ... | 44.0 | 14.0 | 5.0 | 82.0 | 121.0 | 21.0 | 49.0 | 31.0 | 252.0 | 89.0 |
| americanspectator | 10.0 | 5.0 | 0.0 | 0.0 | 1.0 | 3.0 | 1.0 | 0.0 | 1.0 | 4.0 | ... | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 |
| americanthinker | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | ... | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 |
| ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... |
| vice | 13.0 | 103.0 | 143.0 | 38.0 | 60.0 | 262.0 | 6.0 | 2.0 | 12.0 | 3.0 | ... | 6.0 | 0.0 | 0.0 | 3.0 | 3.0 | 0.0 | 0.0 | 2.0 | 0.0 | 3.0 |
| voltairenetwork | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | ... | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 |
| vox | 60.0 | 461.0 | 487.0 | 14.0 | 76.0 | 487.0 | 29.0 | 8.0 | 72.0 | 29.0 | ... | 25.0 | 3.0 | 0.0 | 87.0 | 15.0 | 19.0 | 1.0 | 13.0 | 7.0 | 62.0 |
| wapo | 242.0 | 585.0 | 29.0 | 19.0 | 64.0 | 531.0 | 14.0 | 9.0 | 130.0 | 28.0 | ... | 194.0 | 34.0 | 30.0 | 334.0 | 347.0 | 31.0 | 33.0 | 86.0 | 4.0 | 322.0 |
| wsj | 1.0 | 24.0 | 3.0 | 0.0 | 1.0 | 26.0 | 0.0 | 0.0 | 9.0 | 2.0 | ... | 18.0 | 2.0 | 0.0 | 27.0 | 16.0 | 14.0 | 2.0 | 3.0 | 0.0 | 7.0 |
83 rows × 839 columns
time: 27 ms (started: 2023-03-22 22:16:54 -07:00)
time: 14.8 ms (started: 2023-03-22 22:16:54 -07:00)
time: 6.44 ms (started: 2023-03-22 22:16:54 -07:00)
array(['lean left', 'left', 'lean right', 'right', 'right', 'right',
'center', 'lean left', 'center', 'center', 'right', 'center',
'left', 'left', 'lean left', 'center', 'lean left', 'left',
'center', 'lean left', 'left', 'right', 'left', 'right', 'right',
'lean left', 'center', 'right', 'center', 'center', 'lean right',
'right', 'center', 'left', 'lean left', 'left', 'lean left',
'right', 'left', 'left', 'center', 'right', 'left', 'left',
'right', 'lean left', 'right', 'lean left', 'center', 'right',
'left', 'center', 'left', 'lean left', 'center', 'left',
'lean right', 'lean left', 'center', 'left', 'right', 'center',
'left', 'center', 'left', 'left', 'center', 'left', 'left',
'right', 'right', 'center', 'lean left', 'right', 'left', 'center',
'lean left', 'right', 'left', 'center', 'left', 'lean left',
'center'], dtype='<U10')
time: 7.61 ms (started: 2023-03-22 22:16:54 -07:00)
array(['slightly critical', 'slightly critical', 'slightly critical',
'pro', 'pro', 'critical', 'pro', 'slightly pro', 'slightly pro',
'pro', 'neutral', 'slightly pro', 'pro', 'critical', 'pro', 'pro',
'pro', 'slightly critical', 'critical', 'neutral',
'slightly critical', 'slightly pro', 'slightly critical', 'pro',
'neutral', 'pro', 'slightly critical', 'slightly pro',
'slightly pro', 'pro', 'slightly pro', 'pro', 'critical',
'slightly critical', 'pro', 'slightly pro', 'neutral',
'slightly critical', 'slightly critical', 'slightly critical',
'critical', 'slightly critical', 'slightly critical',
'slightly critical', 'pro', 'slightly pro', 'slightly critical',
'slightly critical', 'pro', 'pro', 'pro', 'slightly critical',
'critical', 'slightly critical', 'pro', 'critical', 'slightly pro',
'neutral', 'slightly pro', 'critical', 'slightly pro', 'pro',
'slightly critical', 'critical', 'slightly critical',
'slightly pro', 'slightly pro', 'slightly critical',
'slightly critical', 'pro', 'slightly critical',
'slightly critical', 'pro', 'neutral', 'slightly critical', 'pro',
'neutral', 'slightly critical', 'pro', 'critical', 'neutral',
'pro', 'pro'], dtype='<U17')
time: 4.27 ms (started: 2023-03-22 22:16:54 -07:00)
| establishment_bias | political_bias | |
|---|---|---|
| publication | ||
| aljazeera | slightly critical | lean left |
| alternet | slightly critical | left |
| americanconservative | slightly critical | lean right |
| americanspectator | pro | right |
| americanthinker | pro | right |
| ... | ... | ... |
| vice | pro | left |
| voltairenetwork | critical | center |
| vox | neutral | left |
| wapo | pro | lean left |
| wsj | pro | center |
83 rows × 2 columns
time: 11.9 ms (started: 2023-03-22 22:16:54 -07:00)
Let’s create a palette for the political and establishment bias. I will use 5-color palettes from ColorBrewer. Although outside of the USA it doesn’t make a ton of sense for left-wing to be blue and right-wing to be red, to avoid being confusing compared to the paper, I will stick with that color scheme for the political leaning. For establishment bias I will use the purple-to-green palette going from critical to pro (with no meaning to those colors beyond trying not to be too reminiscient of red to blue).
# The rdbu5 palette goes from red-to-blue, so we need to reverse it for the left-to-right categories
rdbu5 = ["#ca0020", "#f4a582", "#f7f7f7", "#92c5de", "#0571b0"]
rdbu5.reverse()
prgn5 = ["#7b3294", "#c2a5cf", "#f7f7f7", "#a6dba0", "#008837"]
media_bias_palette = dict(
establishment_bias=dict(zip(establishment_bias_categories, prgn5)),
political_bias=dict(zip(political_bias_categories, rdbu5)),
)time: 3.25 ms (started: 2023-03-22 22:16:54 -07:00)
Here’s an example of running UMAP on the data. Rather than use the raw counts, I’ll use the sklearn RobustScaler to give each phrase roughly equal importance. I’m not saying this is the optimal or even a good idea, but as a default option, it’s not the worst we could do. For the UMAP settings, I have reduced the value of n_neighbors due to the small size of the dataset: there is a risk of seeing false clusters with this, but I’ll take the risk. Also, I’ll use a larger value of n_epochs as again the small size of the dataset means this is affordable.
time: 17.1 s (started: 2023-03-22 22:16:54 -07:00)
And let’s put some data together to give a bubble plot display a bit like what’s in the paper.
time: 3.77 ms (started: 2023-03-22 22:17:11 -07:00)
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_style("dark")
sns.scatterplot(
data=result_df,
x="x",
y="y",
hue="political_bias",
size="establishment_bias",
palette=rdbu5,
sizes=[(x + 5) ** 2 for x in range(0, 5)],
)
plt.legend(bbox_to_anchor=(1.02, 1), loc="upper left", borderaxespad=0)
time: 1.1 s (started: 2023-03-22 22:17:11 -07:00)
The layout isn’t horrible, but I am sure some better scaling would give nicer results. Also, to see the actual names of the publication we should use something like plotly to put it in the tooltip. While plotly can do bubbleplots, mapping categorical values to sizes through the express API is a real pain.
import plotly.express as px
result_df["establishment_code"] = (
result_df["establishment_bias"].cat.as_ordered().cat.codes.values + 1
)
fig = px.scatter(
result_df,
x="x",
y="y",
color="political_bias",
size="establishment_code",
hover_data=["publication"],
color_discrete_map=media_bias_palette["political_bias"],
width=700,
height=500,
size_max=10,
category_orders={"political_bias": political_bias_categories},
)
fig.update_xaxes(showgrid=False, zeroline=False).update_yaxes(
showgrid=False, zeroline=False
)time: 647 ms (started: 2023-03-22 22:17:12 -07:00)
In the paper, the authors use a generalized SVD to produce a PCA-like output, except they replace the Froebenius norm that is usually used to optimize the decomposition with maximizing a likelihood of a Poisson distribution that generates the observed number of phrase counts. As I am a bit ambivalent about the UMAP results, let’s at least see what normal PCA does.
The generalized PC plots in the paper actually use the second and third PCs (although the authors label these PC1 and PC2). The first PC (or PC0 in the paper) is considered to be mainly concerned with the different number of articles associated with each publication, i.e. some publications have a higher phrase count just because they tend to publish more articles of all kinds compared to other publications. So we’ll extract 3 components and then see if PC1 vs PC2 or00 PC2 vs PC3 give better results.
time: 96.1 ms (started: 2023-03-22 22:17:13 -07:00)
sns.scatterplot(
data=pd.DataFrame(
dict(
PC1=coords_pca[:, 0],
PC2=coords_pca[:, 1],
publication=filtered_df.index,
establishment_bias=target.establishment_bias.cat.as_ordered(),
political_bias=target.political_bias.cat.as_ordered(),
)
),
x="PC1",
y="PC2",
hue="political_bias",
size="establishment_bias",
palette=rdbu5,
sizes=[(x + 5) ** 2 for x in range(0, 5)],
)
plt.legend(bbox_to_anchor=(1.02, 1), loc="upper left", borderaxespad=0)
time: 670 ms (started: 2023-03-22 22:17:13 -07:00)
Ok, not good. What about PC2 and PC3:
sns.scatterplot(
data=pd.DataFrame(
dict(
PC2=coords_pca[:, 1],
PC3=coords_pca[:, 2],
publication=filtered_df.index,
establishment_bias=target.establishment_bias.cat.as_ordered(),
political_bias=target.political_bias.cat.as_ordered(),
)
),
x="PC2",
y="PC3",
hue="political_bias",
size="establishment_bias",
palette=rdbu5,
sizes=[(x + 5) ** 2 for x in range(0, 5)],
)
plt.legend(bbox_to_anchor=(1.02, 1), loc="upper left", borderaxespad=0)
time: 542 ms (started: 2023-03-22 22:17:14 -07:00)
I think a bit better, but still bad. But maybe the problem was not trying to account for document size in the first place?
Usually in text processing some kind of transformation of counts is applied to take into account the different sizes of documents and frequency of terms. In this dataset, “important” phrases have already been selected for us, but the fact that some publications produce more articles than others is not accounted for in the UMAP above. As mentioned above, in the paper itself, the authors discard the first PC because of this.
I want to account for this in the initial processing, while also taking into account that some subject matter is more popular than others, and not having the contribution of those less frequent subjects be drowned out. So I want to also handle each “block” of data (i.e. each subject matter) separately, then combine them at the end. So here’s a different way of combining the separate subject matter counts:
time is part of the affirmative_action subject but apparently hasn’t used any of the phrases that were selected. This might actually be a useful signal, i.e. it’s a publication that manages to avoid either form of biased language, but it’s going to mess with the scaling I want to do in the next step, so that row gets dropped.cuba subject matter only has 10 relevant phrases, whereas abortion has 50. As I am using counts, it doesn’t seem that important in this case to subtract the mean, so in practice I end up merely dividing by the grand standard deviation of each subject block.cuba, human_rights, tech_censorship and venezuela subjects, so I add the subject with a colon as a prefix to each column, e.g. cuba:propaganda and human_rights:propaganda. Not very important for anything I do in this document but it’s good to avoid ambiguity in column names.def phrase_prep(df):
df = df.fillna(0.0).set_index("PHRASE").iloc[:, 1:].transpose()
df.columns.name = None
df.index.rename("publication", inplace=True)
return df
def rename_columns(df, prefix):
df.columns = [f"{prefix}:{x}" for x in df.columns]
return df
def remove_zero_rows(df):
return df[df.any(axis=1)]
def norm_rows(df):
return df.div(np.sum(df, axis=1), axis=0)
def block_scale(df, center=True):
dfv = df.values.ravel()
if center:
tmp = df - np.mean(dfv)
else:
tmp = df
return tmp / np.std(dfv)time: 6.11 ms (started: 2023-03-22 22:17:14 -07:00)
time: 193 ms (started: 2023-03-22 22:17:14 -07:00)
At this point I want to remove missing data. The obvious step is to use the mean of the non-missing data in each column. In the prior data handling, I replaced missing data with zeros before filtering out the rows that aren’t in the publication. Now that I want to make this missing data effectively “invisible” with respect to the mean of the columns, it makes more sense to filter first and then do the missing data replacement, so the missing data has the mean after filtering:
time: 4.88 ms (started: 2023-03-22 22:17:15 -07:00)
time: 258 ms (started: 2023-03-22 22:17:15 -07:00)
| abortion:pro life | abortion:abortion rights | abortion:anti abortion | abortion:anti choice | abortion:abortion care | abortion:pregnancy | abortion:kill | abortion:medical abortion | abortion:family planning | abortion:pro abortion | ... | yemen:Saudi led coalition | yemen:separatists | yemen:Special Operations | yemen:terrorist | yemen:the Houthis | yemen:the IRGC | yemen:the JCPOA | yemen:the Yemeni | yemen:war on Yemen | yemen:terrorism | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| publication | |||||||||||||||||||||
| aljazeera | 0.635903 | 5.140219 | 2.808573 | 0.000000 | 0.370944 | 3.232509 | 0.105984 | 0.105984 | 0.953855 | 0.317952 | ... | 1.236858 | 0.815094 | 0.000000 | 0.677665 | 3.942780 | 0.099517 | 0.127951 | 1.127863 | 0.023695 | 0.800877 |
| alternet | 0.588864 | 1.902483 | 2.446050 | 2.446050 | 0.588864 | 3.125508 | 0.226486 | 0.000000 | 0.679458 | 0.045297 | ... | 0.521603 | 0.000000 | 2.086413 | 2.434148 | 0.956272 | 0.086934 | 0.869339 | 0.347735 | 1.043206 | 2.608016 |
| americanconservative | 11.299267 | 2.492485 | 0.664663 | 0.000000 | 0.000000 | 1.329326 | 0.166166 | 0.000000 | 0.000000 | 0.498497 | ... | 0.493715 | 0.157091 | 0.056104 | 0.920104 | 1.357715 | 0.235637 | 0.549819 | 0.347844 | 2.827638 | 0.998650 |
| americanspectator | 4.294412 | 2.147206 | 0.000000 | 0.000000 | 0.429441 | 1.288324 | 0.429441 | 0.000000 | 0.429441 | 1.717765 | ... | 0.980652 | 0.154335 | 0.271216 | 2.371369 | 1.627015 | 0.236345 | 0.583933 | 0.620915 | 0.289207 | 2.300577 |
| americanthinker | 2.565642 | 2.612434 | 2.371492 | 0.370262 | 0.628731 | 3.832815 | 0.397781 | 0.155758 | 0.825834 | 0.513131 | ... | 0.980652 | 0.154335 | 0.271216 | 2.371369 | 1.627015 | 0.236345 | 0.583933 | 0.620915 | 0.289207 | 2.300577 |
| ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... |
| vice | 0.324431 | 2.570489 | 3.568737 | 0.948336 | 1.497372 | 6.538526 | 0.149737 | 0.049912 | 0.299474 | 0.074869 | ... | 2.620738 | 0.000000 | 0.000000 | 1.310369 | 1.310369 | 0.000000 | 0.000000 | 0.873579 | 0.000000 | 1.310369 |
| voltairenetwork | 2.565642 | 2.612434 | 2.371492 | 0.370262 | 0.628731 | 3.832815 | 0.397781 | 0.155758 | 0.825834 | 0.513131 | ... | 0.980652 | 0.154335 | 0.271216 | 2.371369 | 1.627015 | 0.236345 | 0.583933 | 0.620915 | 0.289207 | 2.300577 |
| vox | 0.547769 | 4.208690 | 4.446056 | 0.127813 | 0.693840 | 4.446056 | 0.264755 | 0.073036 | 0.657322 | 0.264755 | ... | 0.879586 | 0.105550 | 0.000000 | 3.060960 | 0.527752 | 0.668485 | 0.035183 | 0.457385 | 0.246284 | 2.181374 |
| wapo | 2.155767 | 5.211255 | 0.258336 | 0.169254 | 0.570120 | 4.730216 | 0.124714 | 0.080173 | 1.158057 | 0.249428 | ... | 1.316992 | 0.230813 | 0.203659 | 2.267398 | 2.355650 | 0.210447 | 0.224024 | 0.583821 | 0.027154 | 2.185935 |
| wsj | 0.241365 | 5.792754 | 0.724094 | 0.000000 | 0.241365 | 6.275484 | 0.000000 | 0.000000 | 2.172283 | 0.482730 | ... | 1.989819 | 0.221091 | 0.000000 | 2.984729 | 1.768728 | 1.547637 | 0.221091 | 0.331637 | 0.000000 | 0.773819 |
83 rows × 839 columns
time: 29.6 ms (started: 2023-03-22 22:17:15 -07:00)
Alright, let’s give this one a go with UMAP:
time: 5.67 s (started: 2023-03-22 22:17:15 -07:00)
time: 4.34 ms (started: 2023-03-22 22:17:21 -07:00)

time: 477 ms (started: 2023-03-22 22:17:21 -07:00)
I think that’s done an ok job. Better than the plain Z-scaled version? I don’t know about that. Here’s the plotly version:
result_dfb["establishment_code"] = (
result_dfb["establishment_bias"].cat.as_ordered().cat.codes.values + 1
)
fig = px.scatter(
result_dfb,
x="x",
y="y",
color="political_bias",
size="establishment_code",
hover_data=["publication"],
color_discrete_map=media_bias_palette["political_bias"],
width=700,
height=500,
size_max=10,
category_orders={"political_bias": political_bias_categories},
)
fig.update_xaxes(showgrid=False, zeroline=False).update_yaxes(
showgrid=False, zeroline=False
)time: 74.9 ms (started: 2023-03-22 22:17:21 -07:00)
Let’s see if PCA does any better with this dataset. No need for the RobustScaler scaling here.
time: 139 ms (started: 2023-03-22 22:17:21 -07:00)
sns.scatterplot(
data=pd.DataFrame(
dict(
PC1=coordsb_pca[:, 0],
PC2=coordsb_pca[:, 1],
publication=filtered_df.index,
establishment_bias=target.establishment_bias.cat.as_ordered(),
political_bias=target.political_bias.cat.as_ordered(),
)
),
x="PC1",
y="PC2",
hue="political_bias",
size="establishment_bias",
palette=rdbu5,
sizes=[(x + 5) ** 2 for x in range(0, 5)],
)
plt.legend(bbox_to_anchor=(1.02, 1), loc="upper left", borderaxespad=0)
time: 554 ms (started: 2023-03-22 22:17:21 -07:00)
Certainly better than the previous PCA output. If we have managed to account for document size sufficiently already, I wouldn’t necessarily expect PC2 and PC3 to be an improvement here:
sns.scatterplot(
data=pd.DataFrame(
dict(
PC2=coordsb_pca[:, 1],
PC3=coordsb_pca[:, 2],
publication=filtered_df.index,
establishment_bias=target.establishment_bias.cat.as_ordered(),
political_bias=target.political_bias.cat.as_ordered(),
)
),
x="PC2",
y="PC3",
hue="political_bias",
size="establishment_bias",
palette=rdbu5,
sizes=[(x + 5) ** 2 for x in range(0, 5)],
)
plt.legend(bbox_to_anchor=(1.02, 1), loc="upper left", borderaxespad=0)
time: 513 ms (started: 2023-03-22 22:17:22 -07:00)
…and I am not sure it is. I still prefer UMAP over this one, though.
At least from the PCA results, maybe the row-normalized, block-scaled approach was an improvement. If you leave out the block-scaling the results look slightly different but not in any revelatory way, so I won’t show them, and we can conclude that that bit is probably less important than the row-normalization.
I’ll use the block-scaled version of the data for this.
[22:17:22] INFO Requesting one extra neighbor to account for self-neighbor __init__.py:560
INFO Initial data shape: (83, 839) pipeline.py:75
INFO Keeping all columns preprocess.py:67
INFO Data shape after filtering columns: (83, 839) pipeline.py:146
INFO Removing rows with NAs pipeline.py:130
INFO Data shape after filtering NAs: (83, 839) pipeline.py:141
INFO Checked for duplicates: found 0 pipeline.py:153
INFO No scaling preprocess.py:25
INFO Converting to numpy with {'dtype': 'float32', 'layout': 'c'} pipeline.py:158
INFO Writing data for mediabias pipeline.py:226
INFO Processing target with initial shape (83, 2) pipeline.py:197
INFO Keeping all columns preprocess.py:67
INFO Writing target for mediabias pipeline.py:226
[22:17:23] INFO Writing pkl format to data/mediabias-target-palette.pkl __init__.py:265
INFO Calculating nearest neighbors pipeline.py:241
WARNING 151 neighbors requested but only 83 items in the data __init__.py:68
INFO Could not load library with AVX2 support due to: loader.py:58 ModuleNotFoundError("No module named 'faiss.swigfaiss_avx2'")
INFO Using 'faiss' to find nearest neighbors __init__.py:81
INFO Finding 83 neighbors using faiss with euclidean metric and params: {} __init__.py:94
[22:17:25] INFO Writing numpy format to nn/mediabias.16.euclidean.exact.faiss.idx.npy __init__.py:247
INFO Writing csv format to nn/mediabias.16.euclidean.exact.faiss.idx.csv __init__.py:224
INFO Writing numpy format to nn/mediabias.16.euclidean.exact.faiss.dist.npy __init__.py:247
INFO Writing csv format to nn/mediabias.16.euclidean.exact.faiss.dist.csv __init__.py:224
INFO Writing numpy format to nn/mediabias.51.euclidean.exact.faiss.idx.npy __init__.py:247
INFO Writing csv format to nn/mediabias.51.euclidean.exact.faiss.idx.csv __init__.py:224
INFO Writing numpy format to nn/mediabias.51.euclidean.exact.faiss.dist.npy __init__.py:247
INFO Writing csv format to nn/mediabias.51.euclidean.exact.faiss.dist.csv __init__.py:224
INFO Writing numpy format to nn/mediabias.151.euclidean.exact.faiss.idx.npy __init__.py:247
INFO Writing csv format to nn/mediabias.151.euclidean.exact.faiss.idx.csv __init__.py:224
INFO Writing numpy format to nn/mediabias.151.euclidean.exact.faiss.dist.npy __init__.py:247
[22:17:26] INFO Writing csv format to nn/mediabias.151.euclidean.exact.faiss.dist.csv __init__.py:224
INFO Calculating triplets pipeline.py:252
INFO Writing csv format to triplets/mediabias.5.1337.idx.csv __init__.py:224
INFO Writing csv format to triplets/mediabias.5.1337.euclidean.csv __init__.py:224
INFO Writing numpy format to triplets/mediabias.5.1337.idx.npy __init__.py:247
INFO Writing numpy format to triplets/mediabias.5.1337.euclidean.npy __init__.py:247
INFO Writing pipeline result for mediabias pipeline.py:123
time: 4.12 s (started: 2023-03-22 22:17:22 -07:00)