-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathperception_and_action_distance.py
242 lines (194 loc) · 8.25 KB
/
perception_and_action_distance.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
"""
===========================
Compute distances using perception and action distance as well as sensorimotor distance.
===========================
Dr. Cai Wingfield
---------------------------
Embodied Cognition Lab
Department of Psychology
University of Lancaster
caiwingfield.net
---------------------------
2022
---------------------------
"""
from logging import basicConfig, INFO
from pathlib import Path
from random import seed
from typing import Tuple, Iterable
from pandas import DataFrame, concat, read_csv, isna
from linguistic_distributional_models.evaluation.association import WordsimAll, WordAssociationTest, SimlexSimilarity, \
MenSimilarity
from predictors.aux import logger, logger_format, logger_dateformat, pos_dir, lsa_dir
from predictors.distance import Cosine
from predictors.predictors import add_wordnet_predictor, add_lsa_predictor, add_feature_overlap_predictor, \
add_sensorimotor_predictor, add_mandera_predictor, PredictorName
from predictors.wordnet import WordnetAssociation
def common_similarity_modelling(df: DataFrame,
word_key_cols: Tuple[str, str],
dv_col: str,
pos_path: Path,
lsa_path: Path,
save_path: Path):
"""
Use all predictors to model a given similarity judgement dataset.
:param df:
:param word_key_cols:
:param dv_col:
:param pos_path:
:param lsa_path:
:param save_path:
:return:
"""
df.rename(columns={WordAssociationTest.TestColumn.association_strength: dv_col}, inplace=True)
logger.info("Adding concreteness labels")
df = label_with_concreteness(df)
logger.info("Adding predictors")
df = add_wordnet_predictor(
df,
word_key_cols=word_key_cols,
pos_path=pos_path,
association_type=WordnetAssociation.JiangConrath)
df = add_lsa_predictor(
df,
word_key_cols=word_key_cols,
lsa_path=lsa_path)
df = add_mandera_predictor(
df,
word_key_cols=word_key_cols)
df = add_feature_overlap_predictor(
df,
word_key_cols=word_key_cols)
df = add_sensorimotor_predictor(
df,
word_key_cols=word_key_cols,
distance=Cosine(), only="sensory")
df = add_sensorimotor_predictor(
df,
word_key_cols=word_key_cols,
distance=Cosine(), only="motor")
df["Common to all predictors"] = (
~isna(df[PredictorName.wordnet(WordnetAssociation.JiangConrath)])
& ~isna(df[PredictorName.lsa()])
& ~isna(df[PredictorName.mandera_cbow()])
& ~isna(df[PredictorName.feature_overlap()])
& ~isna(df[PredictorName.sensory_distance(Cosine())])
& ~isna(df[PredictorName.motor_distance(Cosine())])
)
logger.info(f"Saving results to {save_path}")
with save_path.open("w") as save_file:
df.to_csv(save_file, header=True, index=False)
return df
def model_wordsim(location: Path, overwrite: bool) -> DataFrame:
"""
Model the WordSim dataset using all predictors.
:param location:
:param overwrite:
:return:
"""
save_path = Path(location, "wordsim.csv")
if save_path.exists() and not overwrite:
logger.warning(f"{save_path} exists, skipping")
with save_path.open("r") as f:
return read_csv(f)
wordsim_data = common_similarity_modelling(
# Load data from source:
df=WordsimAll().associations_to_dataframe(),
word_key_cols=(WordAssociationTest.TestColumn.word_1, WordAssociationTest.TestColumn.word_2),
dv_col = "WordSim similarity judgement",
lsa_path=Path(lsa_dir, "wordsim-lsa.csv"),
pos_path=Path(pos_dir, "wordsim-pos.tab"),
save_path=save_path)
return wordsim_data
def model_simlex(location: Path, overwrite: bool) -> DataFrame:
"""
Model the Simlex dataset using all predictors.
:param location:
:param overwrite:
:return:
"""
save_path = Path(location, "simlex.csv")
if save_path.exists() and not overwrite:
logger.warning(f"{save_path} exists, skipping")
with save_path.open("r") as f:
return read_csv(f)
simlex_data = common_similarity_modelling(
# Load data from source:
df=SimlexSimilarity().associations_to_dataframe(),
word_key_cols=(WordAssociationTest.TestColumn.word_1, WordAssociationTest.TestColumn.word_2),
dv_col="Simlex similarity judgement",
lsa_path=Path(lsa_dir, "simlex-lsa.csv"),
pos_path=Path(pos_dir, "simlex-pos.tab"),
save_path=save_path)
return simlex_data
def model_men(location: Path, overwrite: bool) -> DataFrame:
"""
Model the MEN dataset using all predictors.
:param location:
:param overwrite:
:return:
"""
save_path = Path(location, "men.csv")
if save_path.exists() and not overwrite:
logger.warning(f"{save_path} exists, skipping")
with save_path.open("r") as f:
return read_csv(f)
men_data = common_similarity_modelling(
# Load data from source:
df=MenSimilarity().associations_to_dataframe(),
word_key_cols=(WordAssociationTest.TestColumn.word_1, WordAssociationTest.TestColumn.word_2),
dv_col="MEN similarity judgement",
lsa_path=Path(lsa_dir, "men-lsa.csv"),
pos_path=Path(pos_dir, "men-pos.tab"),
save_path=save_path)
return men_data
def save_combined_pairs(dfs: Iterable[DataFrame], location: Path) -> None:
combined_data: DataFrame = concat(dfs,
# The DV columns aren't comparable between datasets, and can't be used for the
# grand correlation. However they all have different names so we can just exclude
# them automatically.
join='inner')
combined_data.drop_duplicates(subset=[WordAssociationTest.TestColumn.word_1, WordAssociationTest.TestColumn.word_2],
inplace=True)
with Path(location, "combined.csv").open("w") as f:
combined_data.to_csv(f, header=True, index=False)
def label_with_concreteness(df: DataFrame) -> DataFrame:
concreteness_df = read_csv(
Path(Path(__file__).parent, "data", "concreteness", "13428_2013_403_MOESM1_ESM.csv").as_posix())
# Get first-word-in-pair concreteness rating
df = df.merge(
concreteness_df
.rename(columns={"Word": WordAssociationTest.TestColumn.word_1, "Conc.M": "Word 1 concreteness"})
[[WordAssociationTest.TestColumn.word_1, "Word 1 concreteness"]],
how="left", on=WordAssociationTest.TestColumn.word_1)
# Get second-word-in-pair concreteness rating
df = df.merge(
concreteness_df
.rename(columns={"Word": WordAssociationTest.TestColumn.word_2, "Conc.M": "Word 2 concreteness"})
[[WordAssociationTest.TestColumn.word_2, "Word 2 concreteness"]],
how="left", on=WordAssociationTest.TestColumn.word_2)
def pair_type(row) -> str:
# Concrete defined to be >=3 on the 1–5 Brysbaert scale. <3 is therefore abstract
word_1_is_concrete: bool = row["Word 1 concreteness"] >= 3
word_2_is_concrete: bool = row["Word 2 concreteness"] >= 3
if word_1_is_concrete and word_2_is_concrete:
return "concrete_concrete"
if (not word_1_is_concrete) and (not word_2_is_concrete):
return "abstract_abstract"
return"mixed"
df["Pair type"] = df.apply(pair_type, axis=1)
return df
if __name__ == '__main__':
basicConfig(format=logger_format, datefmt=logger_dateformat, level=INFO)
# For reproducibility
seed(1)
# TODO: make these CLI args
save_dir = Path("/Users/caiwingfield/Box Sync/LANGBOOT Project/Manuscripts/Draft - Sensorimotor distance norms/Output/response_subspaces/")
overwrite = True
# Run each of the analyses in turn
wordsim_data = model_wordsim(location=save_dir, overwrite=overwrite)
simlex_data = model_simlex(location=save_dir, overwrite=overwrite)
men_data = model_men(location=save_dir, overwrite=overwrite)
save_combined_pairs((wordsim_data, simlex_data, men_data), location=save_dir)
logger.info("Done!")