mict-zhaw commited on
Commit
e7fd89e
1 Parent(s): f98f1b9

Introduce stratified folds

Browse files
Files changed (1) hide show
  1. chall.py +59 -23
chall.py CHANGED
@@ -19,7 +19,6 @@ logger = logging.get_logger(__name__)
19
 
20
 
21
  class ChallConfig(BuilderConfig):
22
-
23
  split_segments: bool = False
24
 
25
  # settings that can only be used together with split_segments
@@ -33,7 +32,11 @@ class ChallConfig(BuilderConfig):
33
  allowed_chars: set
34
  special_terms_mapping: dict
35
 
 
 
 
36
  def __init__(self, **kwargs):
 
37
  self.split_segments = kwargs.pop("split_segments", False)
38
  self.remove_trailing_pauses = kwargs.pop("remove_trailing_pauses", False)
39
 
@@ -50,11 +53,13 @@ class ChallConfig(BuilderConfig):
50
  else:
51
  self.allowed_chars: set = set(string.ascii_lowercase + string.ascii_uppercase + " ÄÖÜäöü'")
52
 
 
 
 
53
  super(ChallConfig, self).__init__(**kwargs)
54
 
55
 
56
  class Chall(GeneratorBasedBuilder):
57
-
58
  VERSION = Version("1.0.0")
59
 
60
  BUILDER_CONFIG_CLASS = ChallConfig
@@ -84,6 +89,14 @@ class Chall(GeneratorBasedBuilder):
84
  remove_trailing_pauses=True,
85
  lowercase=True,
86
  num_to_words=True,
 
 
 
 
 
 
 
 
87
  description="Settings used for the paper."
88
  )
89
  ]
@@ -220,29 +233,47 @@ class Chall(GeneratorBasedBuilder):
220
  f"that includes files unzipped from the chall zip. Manual download instructions: {self.manual_download_instructions}"
221
  )
222
 
223
- return [
224
- SplitGenerator(
225
- name=Split.TRAIN,
226
- gen_kwargs={
227
- "filepath": os.path.join(data_dir, "data"),
228
- "metafile": os.path.join(data_dir, _METAFILE)
229
- },
230
- ),
231
- # datasets.SplitGenerator(
232
- # name=datasets.Split.TEST,
233
- # gen_kwargs={"filepath": os.path.join(data_dir, "data"), "metafile": os.path.join(data_dir, _METAFILE)},
234
- # ),
235
- # datasets.SplitGenerator(
236
- # name=datasets.Split.VALIDATION,
237
- # gen_kwargs={"filepath": os.path.join(data_dir, "data"), "metafile": os.path.join(data_dir, _METAFILE)},
238
- # ),
239
- ]
240
-
241
- def _generate_examples(self, filepath, metafile):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
242
  """
243
  This method handles input defined in _split_generators to yield (key, example) tuples from the dataset.
244
  :param filepath: The path where the data is located.
245
  :param metafile: The metafile describing the chall data
 
 
246
  :return:
247
  """
248
 
@@ -251,6 +282,11 @@ class Chall(GeneratorBasedBuilder):
251
  with open(metafile, 'r') as file:
252
  metadata = json.load(file)
253
  for row in metadata["data"]:
 
 
 
 
 
254
  # load transcript
255
  transcript_file = os.path.join(filepath, row["transcript_file"])
256
  with open(transcript_file, 'r') as transcript:
@@ -386,14 +422,14 @@ class Chall(GeneratorBasedBuilder):
386
 
387
  split_segments = []
388
  for segment in segments:
389
- if any(w["end"]-w["start"] >= self.config.max_pause_length and w["text"].strip() == "(...)" for w in segment["words"]):
390
  start_i = 0
391
  for i, word in enumerate(segment["words"]):
392
  w_duration = word["end"] - word["start"]
393
  if w_duration >= self.config.max_pause_length and word["text"].strip() == "(...)":
394
  if len(segment["words"][start_i:i]) > 0:
395
  split_segments.append({"speaker": segment["speaker"], "words": segment["words"][start_i:i]})
396
- start_i = i+1
397
 
398
  if len(segment["words"][start_i:]) > 0:
399
  split_segments.append({"speaker": segment["speaker"], "words": segment["words"][start_i:]})
 
19
 
20
 
21
  class ChallConfig(BuilderConfig):
 
22
  split_segments: bool = False
23
 
24
  # settings that can only be used together with split_segments
 
32
  allowed_chars: set
33
  special_terms_mapping: dict
34
 
35
+ stratify_column: Union[None, str]
36
+ folds: Union[None, Dict[str, List]]
37
+
38
  def __init__(self, **kwargs):
39
+
40
  self.split_segments = kwargs.pop("split_segments", False)
41
  self.remove_trailing_pauses = kwargs.pop("remove_trailing_pauses", False)
42
 
 
53
  else:
54
  self.allowed_chars: set = set(string.ascii_lowercase + string.ascii_uppercase + " ÄÖÜäöü'")
55
 
56
+ self.stratify_column = kwargs.pop("stratify_column", None)
57
+ self.folds = kwargs.pop("folds", None)
58
+
59
  super(ChallConfig, self).__init__(**kwargs)
60
 
61
 
62
  class Chall(GeneratorBasedBuilder):
 
63
  VERSION = Version("1.0.0")
64
 
65
  BUILDER_CONFIG_CLASS = ChallConfig
 
89
  remove_trailing_pauses=True,
90
  lowercase=True,
91
  num_to_words=True,
92
+ stratify_column="intervention",
93
+ folds={
94
+ "fold0": ["17", "15", "1"],
95
+ "fold1": ["13", "7", "10"],
96
+ "fold2": ["4", "8", "6", "14"],
97
+ "fold3": ["12", "16", "5", "19"],
98
+ "fold4": ["9", "2", "3", "18", "11"]
99
+ },
100
  description="Settings used for the paper."
101
  )
102
  ]
 
233
  f"that includes files unzipped from the chall zip. Manual download instructions: {self.manual_download_instructions}"
234
  )
235
 
236
+ # kFold Strategy
237
+ if self.config.folds and self.config.stratify_column:
238
+ return [
239
+ SplitGenerator(
240
+ name=fold_name,
241
+ gen_kwargs={
242
+ "filepath": os.path.join(data_dir, "data"),
243
+ "metafile": os.path.join(data_dir, _METAFILE),
244
+ "stratify_column": self.config.stratify_column,
245
+ "fold": fold
246
+ },
247
+ )
248
+ for (fold_name, fold) in self.config.folds.items()]
249
+
250
+ # Train Only Strategy
251
+ else:
252
+ return [
253
+ SplitGenerator(
254
+ name=Split.TRAIN,
255
+ gen_kwargs={
256
+ "filepath": os.path.join(data_dir, "data"),
257
+ "metafile": os.path.join(data_dir, _METAFILE),
258
+ },
259
+ ),
260
+ # datasets.SplitGenerator(
261
+ # name=datasets.Split.TEST,
262
+ # gen_kwargs={"filepath": os.path.join(data_dir, "data"), "metafile": os.path.join(data_dir, _METAFILE)},
263
+ # ),
264
+ # datasets.SplitGenerator(
265
+ # name=datasets.Split.VALIDATION,
266
+ # gen_kwargs={"filepath": os.path.join(data_dir, "data"), "metafile": os.path.join(data_dir, _METAFILE)},
267
+ # ),
268
+ ]
269
+
270
+ def _generate_examples(self, filepath, metafile, stratify_column: str = None, fold: List = None):
271
  """
272
  This method handles input defined in _split_generators to yield (key, example) tuples from the dataset.
273
  :param filepath: The path where the data is located.
274
  :param metafile: The metafile describing the chall data
275
+ :param stratify_column: The meta column to stratify by.
276
+ :param fold: A list of values do define splits. Only works in combination with `stratify_column`
277
  :return:
278
  """
279
 
 
282
  with open(metafile, 'r') as file:
283
  metadata = json.load(file)
284
  for row in metadata["data"]:
285
+
286
+ # define splits if set
287
+ if stratify_column and str(row[stratify_column]) not in fold:
288
+ continue
289
+
290
  # load transcript
291
  transcript_file = os.path.join(filepath, row["transcript_file"])
292
  with open(transcript_file, 'r') as transcript:
 
422
 
423
  split_segments = []
424
  for segment in segments:
425
+ if any(w["end"] - w["start"] >= self.config.max_pause_length and w["text"].strip() == "(...)" for w in segment["words"]):
426
  start_i = 0
427
  for i, word in enumerate(segment["words"]):
428
  w_duration = word["end"] - word["start"]
429
  if w_duration >= self.config.max_pause_length and word["text"].strip() == "(...)":
430
  if len(segment["words"][start_i:i]) > 0:
431
  split_segments.append({"speaker": segment["speaker"], "words": segment["words"][start_i:i]})
432
+ start_i = i + 1
433
 
434
  if len(segment["words"][start_i:]) > 0:
435
  split_segments.append({"speaker": segment["speaker"], "words": segment["words"][start_i:]})