climabench / climabench.py
tanmaylaud's picture
added scidcc
1efaea4
raw
history blame
32.1 kB
# coding=utf-8
# Copyright 2020 The HuggingFace Datasets Authors and the current dataset script contributor.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""ClimaBench: A Benchmark Dataset For Climate Change Text Understanding in English"""
import os
import datasets
import csv
import textwrap
import json
_CITATION = """
@misc{laud2023Climabench,
title={ClimaBench: A Benchmark Dataset For Climate Change Text Understanding in English},
author={Tanmay Laud and Daniel Spokoyny and Tom Corringham and Taylor Berg-Kirkpatrick},
year={2023},
eprint={2301.04253},
archivePrefix={arXiv},
primaryClass={cs.CL}
}
"""
_DESCRIPTION = """\
The topic of Climate Change (CC) has received limited attention in NLP despite its real world urgency.
Activists and policy-makers need NLP tools in order to effectively process the vast and rapidly growing textual data produced on CC.
Their utility, however, primarily depends on whether the current state-of-the-art models can generalize across various tasks in the CC domain.
In order to address this gap, we introduce Climate Change Benchmark (Climabench), a benchmark collection of existing disparate datasets for evaluating model performance across a diverse set of CC NLU tasks systematically.
Further, we enhance the benchmark by releasing two large-scale labelled text classification and question-answering datasets curated from publicly available environmental disclosures.
Lastly, we provide an analysis of several generic and CC-oriented models answering whether fine-tuning on domain text offers any improvements across these tasks. We hope this work provides a standard assessment tool for research on CC text data.
"""
_HOMEPAGE = "https://arxiv.org/abs/2301.04253"
_LICENSE = ""
_Climabench_BASE_KWARGS = dict(
citation=_CITATION,
url=_HOMEPAGE,
)
class ClimabenchConfig(datasets.BuilderConfig):
"""BuilderConfig for Climabench."""
def __init__(
self,
data_dir,
citation,
url=None,
text_features=None,
label_column=None,
label_classes=None,
process_label=lambda x: x,
**kwargs,
):
"""BuilderConfig for Climabench.
Args:
text_features: `dict[string, string]`, map from the name of the feature
dict for each text field to the name of the column in the tsv file
label_column: `string`, name of the column in the tsv file corresponding
to the label
data_dir: `string`, the path to the folder containing the tsv files in the
downloaded zip
citation: `string`, citation for the data set
url: `string`, url for information about the data set
label_classes: `list[string]`, the list of classes if the label is
categorical. If not provided, then the label will be of type
`datasets.Value('float32')`.
process_label: `Function[string, any]`, function taking in the raw value
of the label and processing it to the form required by the label feature
**kwargs: keyword arguments forwarded to super.
"""
super(ClimabenchConfig, self).__init__(
version=datasets.Version("1.0.0", ""), **kwargs
)
self.text_features = text_features
self.label_column = label_column
self.label_classes = label_classes
self.data_dir = data_dir
self.citation = citation
self.url = url
self.process_label = process_label
class Climabench(datasets.GeneratorBasedBuilder):
"""FLORES-200 dataset."""
BUILDER_CONFIGS = [
ClimabenchConfig(
name="climate_stance",
description=textwrap.dedent(
"""\
With climate change becoming a cause of concern worldwide, it becomes essential to gauge people{'}s reactions. This can help educate and spread awareness about it and help leaders improve decision-making. This work explores the fine-grained classification and Stance detection of climate change-related social media text. Firstly, we create two datasets, ClimateStance and ClimateEng, consisting of 3777 tweets each, posted during the 2019 United Nations Framework Convention on Climate Change and comprehensively outline the dataset collection, annotation methodology, and dataset composition. Secondly, we propose the task of Climate Change stance detection based on our proposed ClimateStance dataset. Thirdly, we propose a fine-grained classification based on the ClimateEng dataset, classifying social media text into five categories: Disaster, Ocean/Water, Agriculture/Forestry, Politics, and General. We benchmark both the datasets for climate change stance detection and fine-grained classification using state-of-the-art methods in text classification. We also create a Reddit-based dataset for both the tasks, ClimateReddit, consisting of 6262 pseudo-labeled comments along with 329 manually annotated comments for the label. We then perform semi-supervised experiments for both the tasks and benchmark their results using the best-performing model for the supervised experiments. Lastly, we provide insights into the ClimateStance and ClimateReddit using part-of-speech tagging and named-entity recognition."""
),
text_features={"text": "text"},
label_classes=[0, 1, 2],
label_column="label",
data_dir="all_data/ClimateStance",
citation=textwrap.dedent(
"""\
@inproceedings{vaid-etal-2022-towards,
title = "Towards Fine-grained Classification of Climate Change related Social Media Text",
author = "Vaid, Roopal and
Pant, Kartikey and
Shrivastava, Manish",
booktitle = "Proceedings of the 60th Annual Meeting of the Association for Computational Linguistics: Student Research Workshop",
month = may,
year = "2022",
address = "Dublin, Ireland",
publisher = "Association for Computational Linguistics",
url = "https://aclanthology.org/2022.acl-srw.35",
doi = "10.18653/v1/2022.acl-srw.35",
pages = "434--443",
abstract = "With climate change becoming a cause of concern worldwide, it becomes essential to gauge people{'}s reactions. This can help educate and spread awareness about it and help leaders improve decision-making. This work explores the fine-grained classification and Stance detection of climate change-related social media text. Firstly, we create two datasets, ClimateStance and ClimateEng, consisting of 3777 tweets each, posted during the 2019 United Nations Framework Convention on Climate Change and comprehensively outline the dataset collection, annotation methodology, and dataset composition. Secondly, we propose the task of Climate Change stance detection based on our proposed ClimateStance dataset. Thirdly, we propose a fine-grained classification based on the ClimateEng dataset, classifying social media text into five categories: Disaster, Ocean/Water, Agriculture/Forestry, Politics, and General. We benchmark both the datasets for climate change stance detection and fine-grained classification using state-of-the-art methods in text classification. We also create a Reddit-based dataset for both the tasks, ClimateReddit, consisting of 6262 pseudo-labeled comments along with 329 manually annotated comments for the label. We then perform semi-supervised experiments for both the tasks and benchmark their results using the best-performing model for the supervised experiments. Lastly, we provide insights into the ClimateStance and ClimateReddit using part-of-speech tagging and named-entity recognition.",
}
}"""
),
url="https://github.com/roopalv54/finegrained-climate-change-social-media",
),
ClimabenchConfig(
name="climate_eng",
description=textwrap.dedent(
"""\
With climate change becoming a cause of concern worldwide, it becomes essential to gauge people{'}s reactions. This can help educate and spread awareness about it and help leaders improve decision-making. This work explores the fine-grained classification and Stance detection of climate change-related social media text. Firstly, we create two datasets, ClimateStance and ClimateEng, consisting of 3777 tweets each, posted during the 2019 United Nations Framework Convention on Climate Change and comprehensively outline the dataset collection, annotation methodology, and dataset composition. Secondly, we propose the task of Climate Change stance detection based on our proposed ClimateStance dataset. Thirdly, we propose a fine-grained classification based on the ClimateEng dataset, classifying social media text into five categories: Disaster, Ocean/Water, Agriculture/Forestry, Politics, and General. We benchmark both the datasets for climate change stance detection and fine-grained classification using state-of-the-art methods in text classification. We also create a Reddit-based dataset for both the tasks, ClimateReddit, consisting of 6262 pseudo-labeled comments along with 329 manually annotated comments for the label. We then perform semi-supervised experiments for both the tasks and benchmark their results using the best-performing model for the supervised experiments. Lastly, we provide insights into the ClimateStance and ClimateReddit using part-of-speech tagging and named-entity recognition."""
),
text_features={"text": "text"},
label_classes=["0", "1", "2", "3", "4"],
label_column="label",
data_dir="all_data/ClimateEng",
citation=textwrap.dedent(
"""\
@inproceedings{vaid-etal-2022-towards,
title = "Towards Fine-grained Classification of Climate Change related Social Media Text",
author = "Vaid, Roopal and
Pant, Kartikey and
Shrivastava, Manish",
booktitle = "Proceedings of the 60th Annual Meeting of the Association for Computational Linguistics: Student Research Workshop",
month = may,
year = "2022",
address = "Dublin, Ireland",
publisher = "Association for Computational Linguistics",
url = "https://aclanthology.org/2022.acl-srw.35",
doi = "10.18653/v1/2022.acl-srw.35",
pages = "434--443",
abstract = "With climate change becoming a cause of concern worldwide, it becomes essential to gauge people{'}s reactions. This can help educate and spread awareness about it and help leaders improve decision-making. This work explores the fine-grained classification and Stance detection of climate change-related social media text. Firstly, we create two datasets, ClimateStance and ClimateEng, consisting of 3777 tweets each, posted during the 2019 United Nations Framework Convention on Climate Change and comprehensively outline the dataset collection, annotation methodology, and dataset composition. Secondly, we propose the task of Climate Change stance detection based on our proposed ClimateStance dataset. Thirdly, we propose a fine-grained classification based on the ClimateEng dataset, classifying social media text into five categories: Disaster, Ocean/Water, Agriculture/Forestry, Politics, and General. We benchmark both the datasets for climate change stance detection and fine-grained classification using state-of-the-art methods in text classification. We also create a Reddit-based dataset for both the tasks, ClimateReddit, consisting of 6262 pseudo-labeled comments along with 329 manually annotated comments for the label. We then perform semi-supervised experiments for both the tasks and benchmark their results using the best-performing model for the supervised experiments. Lastly, we provide insights into the ClimateStance and ClimateReddit using part-of-speech tagging and named-entity recognition.",
}
}"""
),
url="https://github.com/roopalv54/finegrained-climate-change-social-media",
),
ClimabenchConfig(
name="climate_fever",
description=textwrap.dedent(
"""\
A dataset adopting the FEVER methodology that consists of 1,535 real-world claims regarding climate-change collected on the internet. Each claim is accompanied by five manually annotated evidence sentences retrieved from the English Wikipedia that support, refute or do not give enough information to validate the claim totalling in 7,675 claim-evidence pairs. The dataset features challenging claims that relate multiple facets and disputed cases of claims where both supporting and refuting evidence are present."""
),
data_dir="all_data/ClimateFEVER/test-data",
citation=textwrap.dedent(
"""\
@misc{diggelmann2020climatefever,
title={CLIMATE-FEVER: A Dataset for Verification of Real-World Climate Claims},
author={Thomas Diggelmann and Jordan Boyd-Graber and Jannis Bulian and Massimiliano Ciaramita and Markus Leippold},
year={2020},
eprint={2012.00614},
archivePrefix={arXiv},
primaryClass={cs.CL}
}
}"""
),
url="http://climatefever.ai",
),
ClimabenchConfig(
name="climatext",
description=textwrap.dedent(
"""\
Climatext is a dataset for sentence-based climate change topic detection. The dataset explores different approaches to identify the climate change topic in various text sources"""
),
text_features={"text": "sentence"},
label_classes=["0", "1", "2", "3", "4"],
label_column="label",
data_dir="all_data/ClimaText",
citation=textwrap.dedent(
"""\
@misc{varini2021climatext,
title={ClimaText: A Dataset for Climate Change Topic Detection},
author={Francesco S. Varini and Jordan Boyd-Graber and Massimiliano Ciaramita and Markus Leippold},
year={2021},
eprint={2012.00483},
archivePrefix={arXiv},
primaryClass={cs.CL}
}
}"""
),
url="https://www.sustainablefinance.uzh.ch/en/research/climate-fever/climatext.html",
),
ClimabenchConfig(
name="clima_insurance",
description=textwrap.dedent(
"""\
We create two tasks based on the responses to the NAIC survey, first being a binary Yes/No classification task
(CLIMA-INSURANCE) and the other one being a question type classification problem (CLIMAINSURANCE+).
The data is web scraped from all the annual survey responses between 2012-2021 giving a total of 17K labelled passages.
We remove the first sentence in each response as it contains obvious markers (like "Yes, we do X." or "No, we do not participate in Y.") and create splits for training, validation and testing.
The splits of the two datasets are different since we stratify by the class label in order to fairly balance the classes across the splits."""
),
label_classes=["0", "1"],
data_dir="all_data/ClimateInsurance",
text_features={"text": "text"},
label_column="label",
**_Climabench_BASE_KWARGS,
),
ClimabenchConfig(
name="clima_insurance_plus",
description=textwrap.dedent(
"""\
We create two tasks based on the responses to the NAIC survey, first being a binary Yes/No classification task
(CLIMA-INSURANCE) and the other one being a question type classification problem (CLIMAINSURANCE+).
The data is web scraped from all the annual survey responses between 2012-2021 giving a total of 17K labelled passages.
We remove the first sentence in each response as it contains obvious markers (like "Yes, we do X." or "No, we do not participate in Y.") and create splits for training, validation and testing.
The splits of the two datasets are different since we stratify by the class label in order to fairly balance the classes across the splits."""
),
label_classes=["0", "1", "2", "3", "4", "5", "6", "7"],
data_dir="all_data/ClimateInsuranceMulti",
text_features={"text": "text"},
label_column="label",
**_Climabench_BASE_KWARGS,
),
ClimabenchConfig(
name="clima_cdp",
description=textwrap.dedent(
"""\
The CDP survey responses fall into 3 buckets, namely Cities, States and Corporations, each with a different questionnaire with varying number of questions.
We filter out non-English, short (less than 10 words) and duplicate responses. The Cities dataset is the largest by volume and
consists of parent sections and subsections. We transform these sections into 12 broad categories
with the help of our climate change researcher to curate the labelled data called CLIMA-CDP for the
years 2018-2021 (Appendix Table 8). The goal is to classify CC data into relevant categories. The
12-category mapping creates a more parsimonious set of labels which can be compared to other studies and reduces noise in classification (The original
CDP section labels have changed slightly in the period 2018-2021). The train, development and
test splits are stratified by the organization so that some organization responses are not seen during
training."""
),
label_classes=[
"Emissions",
"Strategy",
"Climate Hazards",
"Governance and Data Management",
"Opportunities",
"Adaptation",
"Water",
"Energy",
"Waste",
"Transport",
"Food",
"Buildings",
],
data_dir="all_data/CDP/Cities/Cities Responses",
text_features={"text": "Text"},
label_column="Label",
**_Climabench_BASE_KWARGS,
),
ClimabenchConfig(
name="clima_qa",
description=textwrap.dedent(
"""\
Although the categories in CLIMACDP are valuable for CC topic classification, they
restrict the downstream application to finite classes.
Hence, we extend our focus on the actual question
response pairs within the surveys to set up a more
nuanced and challenging QA dataset called CLIMAQA. The pre-processing steps are the
same as that of CLIMA-CDP. We curate three different subsets: CDP-CITIES, CDP-STATES and
CDP-CORPORATION where the splits
are stratified by the organizations. They have 294,
132 and 43 unique questions respectively."""
),
data_dir="all_data/CDP",
text_features={"question": "question", "answer": "answer"},
label_classes=["0", "1"],
label_column="label",
**_Climabench_BASE_KWARGS,
),
ClimabenchConfig(
name="scidcc",
description=textwrap.dedent(
"""\
The Science Daily Climate Change (SCIDCC) dataset is
curated by web scraping news articles from the
Science Daily (SD) website. It contains around
11k news articles from 20 categories relevant to
climate change, where each article comprises of
a title, summary, and a body. Some of the major
categories are Earthquakes, Pollution, Hurricanes
and Cyclones. We propose to use this dataset for
the first time as a category classification task for
two reasons. Firstly, the SD news articles are relatively
more scientific as compared to other online
news. Secondly, the average document length is
around 500-600 words with a maximum of roughly
2.5k words, which is significantly longer than other
existing public CC datasets."""
),
label_classes=[
"Ozone Holes",
"Pollution",
"Hurricanes Cyclones",
"Earthquakes",
"Climate",
"Environment",
"Geography",
"Geology",
"Global Warming",
"Weather",
"Agriculture & Food",
"Animals",
"Biology",
"Endangered Animals",
"Extinction",
"New Species",
"Zoology",
"Biotechnology",
"Genetically Modified",
"Microbes",
],
data_dir="all_data/SciDCC",
text_features={"title": "Title", "summary": "Summary", "body": "Body"},
label_column="Category",
citation=textwrap.dedent(
"""@inproceedings{mishra2021neuralnere,
title={NeuralNERE: Neural Named Entity Relationship Extraction for End-to-End Climate Change Knowledge Graph Construction},
author={Mishra, Prakamya and Mittal, Rohan},
booktitle={ICML 2021 Workshop on Tackling Climate Change with Machine Learning},
url={https://www.climatechange.ai/papers/icml2021/76},
year={2021}
}"""
),
),
]
def _info(self):
if self.config.name == "climate_fever":
features = datasets.Features(
{
"claim_id": datasets.Value("string"),
"claim": datasets.Value("string"),
"claim_label": datasets.ClassLabel(
names=["SUPPORTS", "REFUTES", "NOT_ENOUGH_INFO", "DISPUTED"]
),
"evidences": [
{
"evidence_id": datasets.Value("string"),
"evidence_label": datasets.ClassLabel(
names=["SUPPORTS", "REFUTES", "NOT_ENOUGH_INFO"]
),
"article": datasets.Value("string"),
"evidence": datasets.Value("string"),
"entropy": datasets.Value("float32"),
"votes": [datasets.Value("string")],
},
],
}
)
else:
if self.config.name == "clima_qa":
features = {
text_feature: datasets.Value("string")
for text_feature in self.config.text_features.keys()
}
features["category"] = datasets.Value("string")
else:
features = {
text_feature: datasets.Value("string")
for text_feature in self.config.text_features.keys()
}
if self.config.label_classes:
features["label"] = datasets.features.ClassLabel(
names=self.config.label_classes
)
else:
features["label"] = datasets.Value("float32")
features["idx"] = datasets.Value("int32")
return datasets.DatasetInfo(
description=_DESCRIPTION,
features=datasets.Features(features),
homepage=self.config.url,
citation=self.config.citation + "\n" + _CITATION,
)
def _split_generators(self, dl_manager):
data_dir = self.config.data_dir
if self.config.name == "scidcc":
return [
datasets.SplitGenerator(
name=datasets.Split.TEST,
gen_kwargs={
"data_file": os.path.join(data_dir or "", "SciDCC.csv"),
"split": "test",
},
),
]
if self.config.name == "climate_fever":
return [
datasets.SplitGenerator(
name=datasets.Split.TEST,
gen_kwargs={
"data_file": os.path.join(
data_dir or "", "climate-fever-dataset-r1.jsonl"
),
"split": "test",
},
),
]
if self.config.name == "climatext":
files = {
"train": [
"train-data/AL-10Ks.tsv : 3000 (58 positives, 2942 negatives) (TSV, 127138 KB).tsv",
"train-data/AL-Wiki (train).tsv",
],
"valid": ["dev-data/Wikipedia (dev).tsv"],
"test": [
"test-data/Claims (test).tsv",
"test-data/Wikipedia (test).tsv",
"test-data/10-Ks (2018, test).tsv",
],
}
return [
datasets.SplitGenerator(
name=datasets.Split.TRAIN,
gen_kwargs={
"data_file": [
os.path.join(data_dir or "", f) for f in files["train"]
],
"split": "train",
},
),
datasets.SplitGenerator(
name=datasets.Split.VALIDATION,
gen_kwargs={
"data_file": [
os.path.join(data_dir or "", f) for f in files["valid"]
],
"split": "valid",
},
),
datasets.SplitGenerator(
name=datasets.Split.TEST,
gen_kwargs={
"data_file": [
os.path.join(data_dir or "", f) for f in files["test"]
],
"split": "test",
},
),
]
if self.config.name == "clima_qa":
categories = {
"cities": "Cities/Cities Responses",
"states": "States",
"corporations": "Corporations/Corporations Responses/Climate Change",
}
return [
datasets.SplitGenerator(
name=datasets.Split.TRAIN,
gen_kwargs={
"data_file": [
(k, os.path.join(data_dir or "", v, "train_qa.csv"))
for k, v in categories.items()
],
"split": "train",
},
),
datasets.SplitGenerator(
name=datasets.Split.VALIDATION,
gen_kwargs={
"data_file": [
(k, os.path.join(data_dir or "", v, "val_qa.csv"))
for k, v in categories.items()
],
"split": "valid",
},
),
datasets.SplitGenerator(
name=datasets.Split.TEST,
gen_kwargs={
"data_file": [
(k, os.path.join(data_dir or "", v, "test_qa.csv"))
for k, v in categories.items()
],
"split": "test",
},
),
]
return [
datasets.SplitGenerator(
name=datasets.Split.TRAIN,
gen_kwargs={
"data_file": os.path.join(data_dir or "", "train.csv"),
"split": "train",
},
),
datasets.SplitGenerator(
name=datasets.Split.VALIDATION,
gen_kwargs={
"data_file": os.path.join(data_dir or "", "val.csv"),
"split": "valid",
},
),
datasets.SplitGenerator(
name=datasets.Split.TEST,
gen_kwargs={
"data_file": os.path.join(data_dir or "", "test.csv"),
"split": "test",
},
),
]
def _generate_examples(self, data_file, split):
if self.config.name == "climate_fever":
with open(data_file, encoding="utf-8") as f:
for id_, row in enumerate(f):
doc = json.loads(row)
yield id_, doc
elif self.config.name == "climatext":
idx = iter(range(100000))
for file in data_file:
yield from self._process_file(file, delimiter="\t", idx=idx)
elif self.config.name == "clima_qa":
idx = iter(range(10000000))
for category, file in data_file:
yield from self._process_file(file, idx=idx, category=category)
else:
yield from self._process_file(data_file)
def _process_file(self, data_file, delimiter=",", idx=None, category=None):
with open(data_file, encoding="utf8") as f:
process_label = self.config.process_label
label_classes = self.config.label_classes
reader = csv.DictReader(f, delimiter=delimiter, quoting=csv.QUOTE_ALL)
for n, row in enumerate(reader):
example = {
feat: row[col] for feat, col in self.config.text_features.items()
}
if idx:
example["idx"] = next(idx)
else:
example["idx"] = n
if category:
example["category"] = category
if self.config.label_column in row:
label = row[self.config.label_column]
# For some tasks, the label is represented as 0 and 1 in the tsv
# files and needs to be cast to integer to work with the feature.
if label_classes and label not in label_classes:
label = int(label) if label else None
example["label"] = process_label(label)
else:
example["label"] = process_label(-1)
# Filter out corrupted rows.
for value in example.values():
if value is None:
break
else:
yield example["idx"], example