ToL-EDA / notebooks /ToL_catalog_EDA.py
egrace479's picture
Stats gen fix (#8)
d6b5838
raw
history blame
22.2 kB
# ---
# jupyter:
# jupytext:
# formats: ipynb,py:percent
# text_representation:
# extension: .py
# format_name: percent
# format_version: '1.3'
# jupytext_version: 1.16.0
# kernelspec:
# display_name: Python 3 (ipykernel)
# language: python
# name: python3
# ---
# %%
import pandas as pd
import seaborn as sns
sns.set_style("whitegrid")
sns.set(rc = {'figure.figsize': (10,10)})
# %%
df = pd.read_csv("../data/catalog.csv")
# %%
df.head()
# %%
df.info(show_counts = True)
# %% [markdown]
# The `train_small` is duplicates of `train`, so we will drop those to analyze the full training set plus val.
# %%
df = df.loc[df.split != 'train_small']
# %%
df.info(show_counts = True)
# %% [markdown]
# Original version had 10,436,521 entries; we expected loss of about 84K from the genera with label "unknown", but there's still another ~300K missing for this 10,065,576. It seems subspecies were not integrated back in under their species for this version, as we now have 269 less images than last time.
#
# Coverage for species also dropped by 269, genus is similar.
#
# Labeling definitely has far better coverage from original still.
# %%
df.nunique()
# %% [markdown]
# There are 503,589 unique EOL page IDs, suggesting 503,589 unique classes among the 6,250,420 images pulled from EOL (and maintained here). Presumably this would represent the number of species or other lowest rank taxa covered by EOL.
#
# This is only 6 less pages than v3.2, but 269 less images.
# %% [markdown]
# Notice that we now have 12 unique kingdoms, instead of the 7 we were sticking with.
# %%
df['kingdom'].value_counts()
# %% [markdown]
# `Viridiplantae`, `Protista`, `Orthornavirae`, `Bamfordvirae`, and `Shotokuvirae` are all new.
# %% [markdown]
# `Metazoa` and `Archaeplastida` have been replaced by `Animalia` and `Plantae`, setting them as the dominant kingdoms represented (which we'd expect).
#
# We now have other single-celled organisms for kingdom
# %%
taxa = list(df.columns[9:16])
taxa
# %% [markdown]
# Check the number of images with all 7 taxonomic labels.
# %%
df_all_taxa = df.dropna(subset = taxa)
df_all_taxa[taxa].info(show_counts = True)
# %% [markdown]
# We have 8,455,243 images with full taxonomic labels.
#
# Notice that we still have gaps in the taxonomic hierarchy (both higher and lower values), as this is less than the number of species labels in the dataset and species had the least non-null values, but the gap is closing!
#
# We're at 8.4M+ entries with full taxonomic labels, so that's really good, especially considering 1,043,863 of the BIOSCAN sourced images don't have species labels.
# %% [markdown]
# How about number of unique 7-tuples?
# %%
#number of unique 7-tuples in full dataset
df['duplicate'] = df.duplicated(subset = taxa, keep = 'first')
df_unique_taxa = df.loc[~df['duplicate']]
# %%
df_unique_taxa.info(show_counts = True)
# %% [markdown]
# And number of unique `genus-species` pairs?
# %%
#number of unique genus-species pairs in full dataset
df['sciName-duplicate'] = df.duplicated(subset = ['genus', 'species'], keep = 'first')
df_unique_sciName = df.loc[~df['sciName-duplicate']]
# %%
df_unique_sciName.info(show_counts = True)
# %% [markdown]
# More detail on these missing values from [`check_taxa` script](https://github.com/Imageomics/open_clip/blob/main/scripts/evobio10m/check_taxa.py) are displayed below. Note: full record of taxa check output is in `data/missing_taxa_output.txt`.
#
# ```
# [2023-10-30 17:31:38,357] [WARNING] [root] There are 12 kingdoms instead of 3.
# [2023-10-30 17:31:39,420] [WARNING] [root] 39574 entries are missing rank kingdom, but have genus label.
# [2023-10-30 17:31:39,681] [WARNING] [root] 38324 entries are missing rank phylum, but have genus label.
# [2023-10-30 17:31:39,942] [WARNING] [root] 44828 entries are missing rank class, but have genus label.
# [2023-10-30 17:31:40,199] [WARNING] [root] 42771 entries are missing rank order, but have genus label.
# [2023-10-30 17:31:40,456] [WARNING] [root] 40131 entries are missing rank family, but have genus label.
# [2023-10-30 17:31:40,733] [WARNING] [root] 232 entries are missing rank kingdom, but have family label.
# [2023-10-30 17:31:40,759] [WARNING] [root] 223 entries are missing rank phylum, but have family label.
# [2023-10-30 17:31:40,785] [WARNING] [root] 493 entries are missing rank class, but have family label.
# [2023-10-30 17:31:40,812] [WARNING] [root] 345 entries are missing rank order, but have family label.
# [2023-10-30 17:31:40,853] [WARNING] [root] 170 entries are missing rank kingdom, but have order label.
# [2023-10-30 17:31:40,854] [WARNING] [root] 105 entries are missing rank phylum, but have order label.
# [2023-10-30 17:31:40,855] [WARNING] [root] 1263 entries are missing rank class, but have order label.
# [2023-10-30 17:31:40,893] [WARNING] [root] 41 entries have kingdom and species labels but no genus.
# [2023-10-30 17:31:40,897] [WARNING] [root] 41 entries have phylum and species labels but no genus.
# [2023-10-30 17:31:40,901] [WARNING] [root] 41 entries have class and species labels but no genus.
# [2023-10-30 17:31:40,905] [WARNING] [root] 41 entries have order and species labels but no genus.
# [2023-10-30 17:31:40,908] [WARNING] [root] 41 entries have family and species labels but no genus.
# [2023-10-30 17:31:42,311] [WARNING] [root] There are 137661 samples with species label longer than one word.
# ```
# %% [markdown]
# Can we get some more information on those 41 entries that are still missing genus? (should be same as before)
# %%
missing_genus = df.dropna(subset = ['kingdom', 'phylum', 'class', 'order', 'family', 'species'])
missing_genus = missing_genus.loc[missing_genus.genus.isna()]
missing_genus[taxa].nunique()
# %% [markdown]
# So it's a handful of taxa, let's take a look.
# %%
print("The taxa missing genus are: ")
for taxon in taxa:
print(taxon, ": ", missing_genus[taxon].unique())
# %% [markdown]
# All the same as last time, will stay.
# %% [markdown]
# Let's add a column indicating the original data source so we can also get some stats by datasource.
# %%
# Add data_source column for easier slicing
df.loc[df['inat21_filename'].notna(), 'data_source'] = 'iNat21'
df.loc[df['bioscan_filename'].notna(), 'data_source'] = 'BIOSCAN'
df.loc[df['eol_content_id'].notna(), 'data_source'] = 'EOL'
# %%
# re-do missing genus with the data source to check if it's just EOL or Bioscan too
missing_genus = df.dropna(subset = ['kingdom', 'phylum', 'class', 'order', 'family', 'species'])
missing_genus = missing_genus.loc[missing_genus.genus.isna()]
missing_genus.data_source.unique()
# %% [markdown]
# Missing genus with all other taxa occurs only in EOL still. It's what it is for this version.
# %% [markdown]
# First, check their unique class values (`common`).
# %%
df.loc[df['data_source'] == 'EOL', 'common'].nunique()
# %%
df.loc[df['data_source'] == 'iNat21', 'common'].nunique()
# %%
df.loc[df['data_source'] == 'BIOSCAN', 'common'].nunique()
# %% [markdown]
# iNat's number of unique values in `common` is still up by 6 from the original --- probably pulled from ITIS instead and that has more listed?
#
# EOL's went back down, it's about 80K less than the original version.
#
# BIOSCAN's counts stabilized.
# %% [markdown]
# Make `df_taxa` with just taxa columns (+ `common` & `data_source`) so it's smaller to process faster.
# %%
taxa_com = list(df.columns[9:17]) # taxa + common
taxa_com.insert(0, 'data_source')
df_taxa = df[taxa_com]
# %%
df_taxa.head()
# %% [markdown]
# Let's look a little closer at each of our three data sources.
# %%
inat21_df = df_taxa.loc[df_taxa.data_source == 'iNat21']
bioscan_df = df_taxa.loc[df_taxa.data_source == 'BIOSCAN']
eol_df = df_taxa.loc[df_taxa.data_source == 'EOL']
# %% [markdown]
# ### iNat21
# %%
inat21_df.info(show_counts = True)
# %% [markdown]
# iNat21 isn't missing anything, as expected, and we have 2,686,843 images.
#
# Quick view of diversity in iNat21.
# %%
inat21_df.nunique()
# %% [markdown]
# Again, 6 more common values were added, but the diversity has not been altered (same numbers of unique values).
# %%
inat21_df['kingdom'].value_counts()
# %% [markdown]
# iNat21 uses `Animalia` and `Plantae`.
# %%
#number of unique 7-tuples in iNat21
inat21_df['duplicate'] = inat21_df.duplicated(subset = taxa, keep = 'first')
inat21_df_unique_taxa = inat21_df.loc[~inat21_df['duplicate']]
# %%
inat21_df_unique_taxa.info(show_counts = True)
# %% [markdown]
# There's the 10K unique `species` that we expect. Let's check the same information across BIOSCAN and EOL.
# %% [markdown]
# ### BIOSCAN
# %%
bioscan_df.info(show_counts = True)
# %% [markdown]
# All images are labeled down to `order`, most (98.6%) are labeled to the `family` level, but we only have 22.5% and 7.5% with `genus` or `species` level designation, respectively.
#
# There seems to be 1 less genus from the original and 3 less species...
# %%
bioscan_df.nunique()
# %% [markdown]
# We have half as many unique species and 3,000 less unique common names as in the original. Can this be accounted for by the adjustment in genus?
#
# We now seem to have gained an order over the last iteration--that would be the name resolver I guess.
# %%
bioscan_df['kingdom'].value_counts()
# %% [markdown]
# BIOSCAN is all `Animalia`, as expected.
# %% [markdown]
# Check we're not missing `family` designation when we have `genus`.
# %%
bioscan_df.loc[bioscan_df['genus'].notna()].info()
# %%
bioscan_df.loc[bioscan_df['genus'].notna()].sample(7)
# %% [markdown]
# We should not have instances where `common` is labeled as `Genus genus species` this time.
# %%
bioscan_df.loc[bioscan_df['genus'].isna()].sample(7)
# %% [markdown]
# When the `genus` is null, we again have `common` as a list of all higher order taxa available.
# %%
#number of unique 7-tuples in BIOSCAN
bioscan_df['duplicate'] = bioscan_df.duplicated(subset = taxa, keep = 'first')
bioscan_df_unique_taxa = bioscan_df.loc[~bioscan_df['duplicate']]
# %%
bioscan_df_unique_taxa.info(show_counts = True)
# %% [markdown]
# 7,831 unique.
# %% [markdown]
# We should be able to fill all in for all values of `species` that also have `genus` indicated since they are all in `Animalia`. Is `genus` labeled for all entries with `species` labeled?
# %%
bioscan_df.loc[bioscan_df.species.notna()].info(show_counts = True)
# %% [markdown]
# All resolved now.
# %% [markdown]
# In general, when the species is listed in BIOSCAN it is listed as `genus-species`.
#
# This should have been resolved.
#
# Let's check those stats again, we did confirm it earlier, but would also like to check EOL as it had a similar issue for some entries.
# %%
def check_sci_name(df):
"""
This function checks the number of words in the species column for each sample.
Logs a warning with the number that have more than one word indicating the potential for both genus and species to be recorded.
Warning is printed to terminal, not saved to file.
Parameters:
-----------
df - DataFrame with taxonomic hierarchy as columns.
Returns:
--------
df - DataFrame with taxonomic hierarchy and length of species entry as columns.
"""
# Set length of species column with default = 1
df["len_species"] = 1
# Check for scientific name in species column (i.e., genus speices in species column, may correspond to missing genus)
for species in list(df.loc[df["species"].notna(), "species"].unique()):
len_species = len(species.split(" "))
if len_species > 1:
df.loc[df["species"] == species, "len_species"] = len_species
return df
# %%
bioscan_species_len_df = check_sci_name(bioscan_df)
# %%
bioscan_species_len_df.info(show_counts = True)
# %%
bioscan_long_species = bioscan_species_len_df.loc[bioscan_species_len_df["len_species"] > 1]
bioscan_long_species.info(show_counts = True)
# %% [markdown]
# Not all species indicated have length greater than 1 now, consistent with the last iteration.
# %%
bioscan_species_len_df.len_species.value_counts()
# %% [markdown]
# It seems the genus may have been removed, but the remaining string retained as they previously ranged from 2 to 5 "words" long.
# %%
bioscan_long_species.sample(7)
# %% [markdown]
# Ah but the whole species indicator was moved into genus for some of these.
# %%
bioscan_long_species.loc[bioscan_long_species['len_species'] > 2].sample(10)
# %% [markdown]
# This looks like about what we expected.
# %% [markdown]
# It would seem the "sp. ..." is used to indicate they are likely the same species, though the actual species is not designated (either unnamed or undetermined). This is information we should retain, but the duplicated genus can be removed.
# %% [markdown]
# ### EOL
# %%
eol_df.info(show_counts = True)
# %%
eol_df.nunique()
# %% [markdown]
# `kingdom` through `family` gained new unique labels and greater coverage, while `genus` lost images, but did not lose representation (still the same number of unique genera). Both the number of `species` and `common` went down along with the number of unique such labels.
# %%
eol_df.loc[eol_df.species.isna()].nunique()
# %% [markdown]
# There are 503,589 unique page IDs from EOL in this dataset, which clearly represent varying levels of taxa.
#
# Unique species + unique common where species is null (39,232) does not reach this number. But we still added more phyla through family!
# %%
eol_df['kingdom'].value_counts()
# %% [markdown]
# We have much greater kingdom variety here.
#
# We have already observed that not all ranks are filled in at the higher levels, sometimes having just one gap. This has been greatly improved from the first iteration and again with this last one.
# %%
#number of unique 7-tuples in EOL
eol_df['duplicate'] = eol_df.duplicated(subset = taxa, keep = 'first')
eol_df_unique_taxa = eol_df.loc[~eol_df['duplicate']]
# %%
eol_df_unique_taxa.info(show_counts = True)
# %% [markdown]
# This is quite a good number of unqiue taxa.
#
# Is `genus` labeled for all entries with `species` labeled?
# %%
eol_df.loc[eol_df.species.notna()].info(show_counts = True)
# %% [markdown]
# Not all labeled species have higher order taxa, but they do all have `common` (likely because if there is no common name, it pulls scientific name (genus-species)).
#
# Still a 200-300K difference.
# %% [markdown]
# Let's get a quick sample of the `common` column for images both with and without `species` labels.
# %%
# existing species label
eol_df.loc[eol_df.species.notna()].sample(7)
# %% [markdown]
# Good, some of these do have common names. We could check numbers of `common` where it doesn't match the `genus-species` form for a better count, but our random sample is promising.
# %%
# No species label
eol_df.loc[eol_df.species.isna()].sample(7)
# %% [markdown]
# Let's check the `species` length in EOL as well, we know there are some that have genus-species. And others with hybrids that get VERY long.
# %%
eol_species_len = check_sci_name(eol_df)
eol_species_len.info(show_counts = True)
# %%
eol_long_species = eol_species_len.loc[eol_species_len["len_species"] > 1]
eol_long_species.info(show_counts = True)
# %% [markdown]
# That's quite a lot with species name longer than 1 word.
# %%
eol_long_species.len_species.value_counts()
# %% [markdown]
# We have length 2 all the way to 26.
#
# Why are some more than 10 words long?
# - Seem to be hybrids, getting genus added now
# - We have one that says "Bee"... it was "bee bees ntomology apoidea extrememarco insects..."
# %%
eol_long_species.loc[eol_long_species["len_species"] > 7].sample(7)
# %%
eol_long_species.nunique()
# %% [markdown]
# Genus was filled out much more from the last iteration (from only 47 to 8,587 unique instances), also doesn't have any nulls now (pulling that first word from species column).
# %%
eol_long_species.loc[eol_long_species["len_species"] < 7].sample(7)
# %% [markdown]
# There are inconsistencies we likely can't resolve, some have names following the species (in the scientific name standard format of genus-species-namer-year) while others have "sp. __ " which is often used to indicate unknown species (pronounced "spa"), but the following bit may be used to indicate multiple images with unknown species are likely of the same species.
#
#
# Ex from earlier: "Adelpha godmani" is a butterfly with species name given by Fruhstorfer in 1913 ([source](https://butterfliesofamerica.com/L/t/Adelpha_godmani_a.htm)), it was listed as "adelpha godmani fruhstorfer".
# %% [markdown]
# #### Check for webdataset loss
#
# Are we potentially losing entries that have a longer number of words in species column? Let's see if any of these have full taxa.
# %%
eol_long_all_taxa = eol_long_species.dropna(subset = taxa)
eol_long_all_taxa[taxa].info(show_counts = True)
# %% [markdown]
# That's a good number of images, so unlikely to be the cause.
# %% [markdown]
# ## Diversity Between Datasets
# %% [markdown]
# ### Label Overlap Check
# %% [markdown]
# Checking for overlap between the three data sources should give pretty good results, now that most inconsistencies have been addressed.
#
# For now, let's just take a quick look at genera across the datasets since they are more standardized (and listed more often in BIOSCAN).
# %%
eol_genera = list(eol_df.loc[eol_df['genus'].notna(), 'genus'].unique())
inat21_genera = list(inat21_df.loc[inat21_df['genus'].notna(), 'genus'].unique())
bioscan_genera = list(bioscan_df.loc[bioscan_df['genus'].notna(), 'genus'].unique())
print(f"there are {len(eol_genera)} genera in EOL")
print(f"there are {len(inat21_genera)} genera in inat21")
print(f"there are {len(bioscan_genera)} genera in bioscan")
# %%
gen_overlap = list(set(eol_genera) & set(inat21_genera))
print(f"There are {len(gen_overlap)} genera shared between EOL and iNat21.")
print(f"There are {len(list(set(eol_genera) & set(bioscan_genera)))} genera shared between EOL and BIOSCAN.")
print(f"There are {len(list(set(inat21_genera) & set(bioscan_genera)))} genera shared between iNat21 and BIOSCAN.")
print(f"There are {len(list(set(gen_overlap) & set(bioscan_genera)))} genera shared between all three data sources.")
# %% [markdown]
# BIOSCAN and iNat21's overlap of genera is almost completely contained in EOL.
#
# No changes here.
# %% [markdown]
# #### More thorough diversity check with 7-tuple taxa
#
# We'll first filter down to all unique 7-tuple taxa (by data source). Then, we'll reduce down to just EOL and iNat21 to determine how much EOL adds to iNat21's diversity. The remainder from the total is added by BIOSCAN.
# %%
source_taxa = ['data_source', 'kingdom', 'phylum', 'class', 'order', 'family', 'genus', 'species']
# %%
df['duplicate'] = df.duplicated(subset = source_taxa, keep = 'first')
df_unique_taxa = df.loc[~df['duplicate']]
df_unique_taxa.info(show_counts=True)
# %% [markdown]
# We have 466,741 unique taxa by source (i.e., the sum of unique 7-tuples within EOL, iNat21, and BIOSCAN, without considering overlaps between them). Our actual unique 7-tuple taxa count for the full dataset is 454,103, so we have about 12,600 taxa shared between our constituent parts.
#
# Now, let's reduce this down to just EOL and iNat21.
# %%
df_taxa_Enat = df_unique_taxa.loc[df_unique_taxa.data_source != "BIOSCAN"]
df_taxa_Enat.info(show_counts = True)
# %% [markdown]
# We have 458,910 for EOL and iNat21. Now, we remove taxa duplicates between the two datasets.
# %%
df_taxa_Enat['duplicate'] = df_taxa_Enat.duplicated(subset = taxa, keep = 'first')
df_unique_taxa_Enat = df_taxa_Enat.loc[~df_taxa_Enat['duplicate']]
df_unique_taxa_Enat.info(show_counts = True)
# %% [markdown]
# Between iNat21 and EOL we have 450,284 unique taxa. That means we have 3,819 unique 7-tuple taxa added by BIOSCAN, and there are 8,626 taxa (7-tuples) shared between EOL and iNat21 (86% of iNat21).
#
# EOL has 448,910 unique 7-tuple taxa, so it adds 440,284 more unique taxa to iNat21, then the addition of BIOSCAN adds another 3,819 unique taxa.
# %% [markdown]
# ## Overall Stats
#
# Keep in mind, this is without fixing remaining inconsistencies observed above.
# %%
import numpy as np
# %%
num_images = df.shape[0]
# %% [markdown]
# Process DataFrame with just taxa columns and focus on higher ranks for standard deviation (not `genus` and `species`).
# %%
avgs_all_images = []
std_all_images = []
avgs_labeled_images = []
std_labeled_images = []
for rank in taxa_com[1:]: #taxa + common
num_taxa = df_taxa[rank].nunique()
df_labeled = df_taxa.loc[df_taxa[rank].notna()]
num_img_rank = len(df_labeled)
# Get averages
avg_all = num_images/num_taxa
avg_labeled = num_img_rank/num_taxa
avgs_all_images.append(avg_all)
avgs_labeled_images.append(avg_labeled)
# Get standard deviation
std_rank_all = 0
std_rank_labeled = 0
if rank not in ["genus", "species"]:
for taxon in df_labeled[rank].unique():
num_img_at_taxon = len(df_taxa.loc[df_taxa[rank] == taxon])
dev_all = np.square(avg_all - num_img_at_taxon)
dev_labeled = np.square(avg_labeled - num_img_at_taxon)
std_rank_all = std_rank_all + dev_all
std_rank_labeled = std_rank_labeled + dev_labeled
std_rank_all = np.sqrt(std_rank_all/num_images)
std_rank_labeled = np.sqrt(std_rank_labeled/num_images)
else:
std_rank_all = np.nan
std_rank_labeled = np.nan
std_all_images.append(std_rank_all)
std_labeled_images.append(std_rank_labeled)
# %%
avg_std = pd.DataFrame(data = {'class': taxa_com[1:], 'average_all_imgs': avgs_all_images, 'standard_deviation': std_all_images,
'avg_labeled': avgs_labeled_images, 'std_dev_labeled': std_labeled_images })
avg_std
# %%
avg_std.to_csv("../data/stats_avg_std_byClass.csv", index = False)
# %% [markdown]
# Observe that the Plant and Animal `kingdom`s are actually much more heavily represented than Fungi (it didn't look this way before we standardized the kingdoms).
# %%
sns.set(rc = {'figure.figsize': (10,6)})
# %%
sns.histplot(df_taxa, x = 'kingdom')
# %%