linguisticprobing / linguisticprobing.py
sileod's picture
Create linguisticprobing.py
1372f06
# coding=utf-8
# Copyright 2020 The TensorFlow Datasets Authors and the HuggingFace Datasets Authors.
#
# 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.
# Lint as: python3
"""Linguistic Probing Benchmark from SentEval"""
from __future__ import absolute_import, division, print_function
import csv
import os
import textwrap
import six
import datasets
_Linguisticprobing_CITATION = r"""@inproceedings{conneau-etal-2018-cram,
title = "What you can cram into a single {\$}{\&}!{\#}* vector: Probing sentence embeddings for linguistic properties",
author = {Conneau, Alexis and
Kruszewski, German and
Lample, Guillaume and
Barrault, Lo{\"\i}c and
Baroni, Marco},
booktitle = "Proceedings of the 56th Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers)",
month = jul,
year = "2018",
address = "Melbourne, Australia",
publisher = "Association for Computational Linguistics",
url = "https://www.aclweb.org/anthology/P18-1198",
doi = "10.18653/v1/P18-1198",
pages = "2126--2136",
abstract = "Although much effort has recently been devoted to training high-quality sentence embeddings, we still have a poor understanding of what they are capturing. {``}Downstream{''} tasks, often based on sentence classification, are commonly used to evaluate the quality of sentence representations. The complexity of the tasks makes it however difficult to infer what kind of information is present in the representations. We introduce here 10 probing tasks designed to capture simple linguistic features of sentences, and we use them to study embeddings generated by three different encoders trained in eight distinct ways, uncovering intriguing properties of both encoders and training methods.",
}
"""
_Linguisticprobing_DESCRIPTION = """\
10 probing tasks designed to capture simple linguistic features of sentences,
"""
DATA_URL = "https://www.dropbox.com/s/djsk4kbu8in66gp/linguisticprobing.zip?dl=1"
TASK_TO_LABELS = {
"subj_number": ["NN", "NNS"],
"word_content": [
"abandoned",
"abruptly",
"accent",
"access",
"according",
"account",
"ache",
"ached",
"acted",
"acting",
"actions",
"actual",
"address",
"advantage",
"advice",
"afford",
"agent",
"agreement",
"aiden",
"airport",
"alarm",
"albert",
"alert",
"alexander",
"alice",
"alley",
"allowing",
"aloud",
"amanda",
"amber",
"american",
"amused",
"amusement",
"ancient",
"andy",
"annie",
"announced",
"annoyed",
"answering",
"anticipation",
"anxious",
"anybody",
"apologize",
"appearance",
"appears",
"approach",
"approaching",
"arched",
"argue",
"argument",
"aria",
"arrive",
"ashe",
"assume",
"assured",
"attached",
"attacked",
"attempted",
"audience",
"available",
"awful",
"awkward",
"background",
"backpack",
"backward",
"backwards",
"bags",
"balance",
"bank",
"barn",
"bars",
"bastard",
"bath",
"beating",
"begged",
"begins",
"begun",
"behavior",
"bell",
"belly",
"belong",
"belonged",
"bench",
"biggest",
"bike",
"billy",
"bird",
"birds",
"birth",
"birthday",
"bitch",
"bitter",
"blank",
"blast",
"bleeding",
"blind",
"blocked",
"blond",
"blonde",
"bond",
"bone",
"bored",
"bothered",
"bound",
"bowed",
"bowl",
"boxes",
"branches",
"brave",
"bread",
"breast",
"breaths",
"brian",
"brick",
"brilliant",
"broad",
"brows",
"brush",
"brushing",
"buddy",
"build",
"buildings",
"bullet",
"bunch",
"butt",
"cage",
"cain",
"caleb",
"callum",
"calmly",
"cameron",
"capable",
"cards",
"career",
"carol",
"caroline",
"carriage",
"cash",
"cassidy",
"casual",
"catching",
"causing",
"centuries",
"chain",
"chairs",
"challenge",
"chamber",
"chances",
"changes",
"changing",
"charged",
"checking",
"chicken",
"chief",
"chill",
"chloe",
"chocolate",
"choked",
"chosen",
"christian",
"chuckle",
"cigarette",
"circles",
"circumstances",
"claim",
"claimed",
"clary",
"classes",
"claws",
"clay",
"cleaned",
"cleaning",
"clearing",
"clicked",
"cliff",
"climb",
"climbing",
"closely",
"closest",
"cloth",
"clothing",
"cloud",
"clue",
"clung",
"clutched",
"coach",
"cocked",
"code",
"colin",
"collapsed",
"collar",
"colors",
"commander",
"comment",
"complicated",
"concrete",
"condition",
"confidence",
"confident",
"confirmed",
"connected",
"connor",
"convince",
"convinced",
"cook",
"cops",
"copy",
"corners",
"correct",
"cost",
"courage",
"cousin",
"covering",
"covers",
"crack",
"cracked",
"crap",
"crash",
"crashed",
"crawled",
"cream",
"create",
"credit",
"crept",
"crime",
"crossing",
"crowded",
"cruel",
"crystal",
"cupped",
"curiosity",
"current",
"curse",
"cursed",
"cute",
"cutting",
"daemon",
"dagger",
"damned",
"damp",
"danced",
"danny",
"dante",
"darkened",
"darling",
"darted",
"dating",
"dave",
"dawn",
"dealing",
"delicate",
"delicious",
"della",
"demons",
"deny",
"department",
"desert",
"deserved",
"destroy",
"destroyed",
"detail",
"detective",
"devil",
"devon",
"digging",
"dining",
"direct",
"directions",
"disappear",
"disappointed",
"disappointment",
"disbelief",
"discuss",
"disgust",
"display",
"distant",
"distracted",
"dogs",
"dollars",
"double",
"doubted",
"dozen",
"drag",
"dragging",
"drake",
"drank",
"drawer",
"drinks",
"driveway",
"dropping",
"drops",
"drug",
"drugs",
"ducked",
"duke",
"dull",
"duncan",
"duty",
"dylan",
"eager",
"eased",
"east",
"eaten",
"echo",
"echoed",
"eddie",
"edges",
"elbow",
"elena",
"ellie",
"embarrassed",
"embrace",
"emerged",
"emergency",
"emotional",
"ends",
"enemies",
"enormous",
"envelope",
"equipment",
"evan",
"event",
"everybody",
"exact",
"exchange",
"exchanged",
"exclaimed",
"exhausted",
"exist",
"existed",
"existence",
"exit",
"expensive",
"experienced",
"explanation",
"exploded",
"exposed",
"extended",
"extremely",
"eyed",
"fabric",
"fade",
"fairly",
"faith",
"fake",
"falls",
"families",
"fangs",
"farm",
"farther",
"favor",
"feared",
"feed",
"fellow",
"fence",
"fierce",
"fifty",
"file",
"filling",
"fingertips",
"finn",
"fired",
"fixed",
"flame",
"flashlight",
"flicked",
"floating",
"flushed",
"foolish",
"football",
"footsteps",
"forcing",
"formed",
"frame",
"freedom",
"french",
"friday",
"friendly",
"frightened",
"frown",
"frowning",
"froze",
"frozen",
"frustrated",
"fuck",
"fucking",
"furious",
"furniture",
"fury",
"gabe",
"games",
"garage",
"garrett",
"gary",
"gasp",
"gates",
"gather",
"gathering",
"gavin",
"gear",
"gesture",
"gestured",
"ghost",
"girlfriend",
"glances",
"glare",
"glowing",
"goodbye",
"gorgeous",
"government",
"gown",
"grabbing",
"graham",
"grand",
"grandfather",
"grandma",
"grant",
"grasp",
"grave",
"greeted",
"grief",
"grinning",
"groan",
"growl",
"guessed",
"guest",
"guests",
"guns",
"gwen",
"halfway",
"hank",
"hanna",
"happily",
"happiness",
"harry",
"harsh",
"heal",
"heartbeat",
"heaven",
"height",
"hero",
"hesitation",
"hissed",
"hitting",
"holds",
"holiday",
"holly",
"holy",
"honor",
"hopefully",
"horizon",
"houses",
"humor",
"hundreds",
"hunger",
"hunt",
"hunting",
"hurting",
"ideas",
"idiot",
"ignoring",
"images",
"imagination",
"impressed",
"impression",
"inches",
"including",
"incredible",
"incredibly",
"informed",
"injured",
"inner",
"insane",
"intended",
"intensity",
"invisible",
"invited",
"iron",
"isaac",
"issue",
"items",
"jamie",
"jared",
"jealous",
"jeremy",
"jerk",
"jess",
"jesus",
"jimmy",
"joey",
"johnny",
"jonas",
"jordan",
"joseph",
"joshua",
"josie",
"journey",
"judge",
"jumping",
"kane",
"karen",
"katherine",
"katie",
"keeps",
"kevin",
"kicking",
"kidding",
"killer",
"kisses",
"knelt",
"knocking",
"ladies",
"landing",
"language",
"larger",
"lately",
"laura",
"lauren",
"lawyer",
"lean",
"leapt",
"learning",
"lesson",
"letters",
"licked",
"lies",
"lifting",
"lightning",
"likes",
"lined",
"liquid",
"lobby",
"location",
"london",
"lonely",
"louder",
"lover",
"loves",
"loving",
"lucien",
"lucy",
"major",
"mama",
"manner",
"marks",
"martin",
"mask",
"mason",
"mass",
"massive",
"mate",
"material",
"mattered",
"matters",
"meaning",
"meat",
"medical",
"melissa",
"member",
"members",
"mental",
"mere",
"merely",
"midnight",
"military",
"minds",
"miranda",
"mist",
"mixed",
"moaned",
"monday",
"moonlight",
"morgan",
"mortal",
"motioned",
"mountains",
"movements",
"moves",
"movies",
"mumbled",
"muscle",
"mystery",
"nails",
"named",
"nathan",
"nearest",
"necklace",
"needing",
"nerves",
"nervously",
"nicolas",
"nicole",
"nightmare",
"nights",
"nina",
"nodding",
"nods",
"nora",
"noted",
"notes",
"numbers",
"object",
"occurred",
"offering",
"officers",
"oliver",
"opens",
"opinion",
"option",
"orange",
"ordinary",
"original",
"ourselves",
"overhead",
"owner",
"packed",
"pages",
"painful",
"paint",
"painted",
"painting",
"palace",
"palms",
"paris",
"parted",
"particularly",
"partner",
"parts",
"passenger",
"passion",
"patch",
"patience",
"patient",
"patrick",
"patted",
"paying",
"period",
"permission",
"pete",
"photo",
"pile",
"pillow",
"pissed",
"pity",
"placing",
"plain",
"planet",
"plastic",
"pleasant",
"plus",
"pockets",
"points",
"polite",
"popped",
"positive",
"possibility",
"potential",
"pounded",
"powers",
"precious",
"prefer",
"prepare",
"president",
"preston",
"pretend",
"pretending",
"previous",
"price",
"pride",
"princess",
"prison",
"professor",
"program",
"progress",
"project",
"proof",
"proper",
"property",
"protection",
"protest",
"provide",
"provided",
"pulse",
"punch",
"punched",
"pure",
"purple",
"puts",
"quinn",
"quit",
"racing",
"radio",
"rafe",
"raise",
"raising",
"rapidly",
"rare",
"rarely",
"reaches",
"react",
"realizing",
"rear",
"rebecca",
"recall",
"received",
"recently",
"record",
"reflection",
"refuse",
"regular",
"reluctantly",
"remaining",
"remains",
"remembering",
"remind",
"remove",
"replaced",
"request",
"required",
"rescue",
"research",
"resist",
"responsibility",
"responsible",
"result",
"returning",
"reveal",
"revealed",
"revealing",
"ribs",
"riding",
"rifle",
"roar",
"robe",
"robert",
"rode",
"rope",
"rubbing",
"ruin",
"ruined",
"rule",
"runs",
"rushing",
"sadly",
"sadness",
"sake",
"sally",
"satisfaction",
"satisfied",
"saturday",
"savannah",
"saving",
"scanned",
"scar",
"scare",
"scattered",
"scott",
"scrambled",
"screams",
"seated",
"seats",
"secrets",
"section",
"sees",
"self",
"sell",
"sensation",
"sensed",
"senses",
"sentence",
"separate",
"serena",
"series",
"serve",
"served",
"settle",
"sexy",
"shade",
"shakes",
"shame",
"sharply",
"shattered",
"sheet",
"sheets",
"sheriff",
"shield",
"shining",
"shiver",
"shivered",
"shooting",
"shopping",
"shore",
"shortly",
"shorts",
"shout",
"shouting",
"shown",
"shrug",
"shuddered",
"sidewalk",
"sideways",
"signal",
"signs",
"silk",
"silly",
"similar",
"sisters",
"site",
"sits",
"skills",
"skirt",
"skull",
"slapped",
"sleeve",
"slide",
"slipping",
"slowed",
"slumped",
"smaller",
"smith",
"snap",
"social",
"society",
"sofa",
"somewhat",
"sooner",
"sophia",
"sophie",
"souls",
"sounding",
"source",
"spare",
"speech",
"spencer",
"spending",
"spinning",
"split",
"spring",
"squeeze",
"stands",
"stated",
"statement",
"states",
"steal",
"stepping",
"stiff",
"stirred",
"stole",
"stones",
"stops",
"straightened",
"stream",
"stretch",
"strike",
"strode",
"stroked",
"struggle",
"struggling",
"student",
"students",
"studying",
"stuffed",
"style",
"success",
"suggest",
"sunday",
"sunlight",
"supplies",
"surprisingly",
"surrounding",
"survived",
"suspect",
"suspected",
"suspicious",
"swallow",
"sweetheart",
"swiftly",
"swing",
"switch",
"t-shirt",
"tables",
"tail",
"tapped",
"tara",
"target",
"task",
"tasted",
"taught",
"taylor",
"teach",
"teacher",
"teased",
"teasing",
"television",
"tells",
"temper",
"temple",
"tense",
"tent",
"terms",
"terrified",
"terror",
"tessa",
"text",
"thigh",
"thighs",
"thousands",
"threatened",
"threatening",
"throughout",
"thrown",
"thrust",
"tighter",
"till",
"tipped",
"toby",
"toes",
"tony",
"tore",
"torn",
"total",
"tough",
"towel",
"tower",
"trace",
"tracks",
"traffic",
"trailed",
"trained",
"trap",
"trapped",
"traveled",
"travis",
"tray",
"treat",
"treated",
"trembled",
"trevor",
"trick",
"tristan",
"trunk",
"trusted",
"twelve",
"ugly",
"unconscious",
"unexpected",
"uniform",
"universe",
"unknown",
"unlike",
"unsure",
"unusual",
"upper",
"upright",
"upward",
"useful",
"useless",
"valley",
"vanished",
"various",
"vehicle",
"veins",
"victor",
"video",
"vincent",
"violet",
"visible",
"vulnerable",
"walks",
"wandered",
"warrior",
"wash",
"washed",
"waving",
"weather",
"werewolf",
"whipped",
"whispers",
"whom",
"willow",
"winced",
"wings",
"winked",
"wise",
"wishing",
"witch",
"wolves",
"worn",
"wounded",
"wounds",
"wrap",
"wrapping",
"wrists",
"wrote",
"xavier",
"yanked",
"yard",
"yards",
"yelling",
"zach",
],
"obj_number": ["NN", "NNS"],
"past_present": ["PAST", "PRES"],
"sentence_length": [0, 1, 2, 3, 4, 5],
"top_constituents": [
"ADVP_NP_VP_.",
"CC_ADVP_NP_VP_.",
"CC_NP_VP_.",
"IN_NP_VP_.",
"NP_ADVP_VP_.",
"NP_NP_VP_.",
"NP_PP_.",
"NP_VP_.",
"OTHER",
"PP_NP_VP_.",
"RB_NP_VP_.",
"SBAR_NP_VP_.",
"SBAR_VP_.",
"S_CC_S_.",
"S_NP_VP_.",
"S_VP_.",
"VBD_NP_VP_.",
"VP_.",
"WHADVP_SQ_.",
"WHNP_SQ_.",
],
"tree_depth": ["depth_5", "depth_6", "depth_7", "depth_8", "depth_9", "depth_10", "depth_11"],
"coordination_inversion": ["I", "O"],
"odd_man_out": ["C", "O"],
"bigram_shift": ["I", "O"],
}
def get_labels(task):
return TASK_TO_LABELS[task]
class LinguisticprobingConfig(datasets.BuilderConfig):
"""BuilderConfig for Linguisticprobing."""
def __init__(
self,
text_features,
label_classes=None,
process_label=lambda x: x,
**kwargs,
):
"""BuilderConfig for Linguisticprobing.
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_url: `string`, url to download the zip file from
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(LinguisticprobingConfig, self).__init__(version=datasets.Version("1.0.0", ""), **kwargs)
self.text_features = text_features
self.label_column = "label"
self.label_classes = get_labels(self.name)
self.data_url = DATA_URL
self.data_dir = os.path.join("linguisticprobing", self.name)
self.citation = textwrap.dedent(_Linguisticprobing_CITATION)
self.process_label = process_label
self.description = ""
self.url = ""
class Linguisticprobing(datasets.GeneratorBasedBuilder):
"""The General Language Understanding Evaluation (Linguisticprobing) benchmark."""
BUILDER_CONFIG_CLASS = LinguisticprobingConfig
BUILDER_CONFIGS = [
LinguisticprobingConfig(
name="subj_number",
text_features={"sentence": "sentence"},
),
LinguisticprobingConfig(
name="word_content",
text_features={"sentence": "sentence"},
),
LinguisticprobingConfig(
name="obj_number",
text_features={"sentence": "sentence"},
),
LinguisticprobingConfig(
name="past_present",
text_features={"sentence": "sentence"},
),
LinguisticprobingConfig(
name="sentence_length",
text_features={"sentence": "sentence"},
),
LinguisticprobingConfig(
name="top_constituents",
text_features={"sentence": "sentence"},
),
LinguisticprobingConfig(
name="tree_depth",
text_features={"sentence": "sentence"},
),
LinguisticprobingConfig(
name="coordination_inversion",
text_features={"sentence": "sentence"},
),
LinguisticprobingConfig(
name="odd_man_out",
text_features={"sentence": "sentence"},
),
LinguisticprobingConfig(
name="bigram_shift",
text_features={"sentence": "sentence"},
),
]
def _info(self):
features = {text_feature: datasets.Value("string") for text_feature in six.iterkeys(self.config.text_features)}
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=_Linguisticprobing_DESCRIPTION,
features=datasets.Features(features),
homepage=self.config.url,
citation=self.config.citation + "\n" + _Linguisticprobing_CITATION,
)
def _split_generators(self, dl_manager):
dl_dir = dl_manager.download_and_extract(self.config.data_url)
data_dir = os.path.join(dl_dir, self.config.data_dir)
return [
datasets.SplitGenerator(
name=datasets.Split.TRAIN,
gen_kwargs={
"data_file": os.path.join(data_dir or "", "train.tsv"),
"split": "train",
},
),
datasets.SplitGenerator(
name=datasets.Split.VALIDATION,
gen_kwargs={
"data_file": os.path.join(data_dir or "", "dev.tsv"),
"split": "dev",
},
),
datasets.SplitGenerator(
name=datasets.Split.TEST,
gen_kwargs={
"data_file": os.path.join(data_dir or "", "test.tsv"),
"split": "test",
},
),
]
def _generate_examples(self, data_file, split):
process_label = self.config.process_label
label_classes = self.config.label_classes
with open(data_file, encoding="utf8") as f:
reader = csv.DictReader(f, delimiter="\t", quoting=csv.QUOTE_NONE)
for n, row in enumerate(reader):
example = {feat: row[col] for feat, col in six.iteritems(self.config.text_features)}
example["idx"] = n
if self.config.label_column in row:
label = row[self.config.label_column]
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)
yield example["idx"], example