garrethlee HF staff commited on
Commit
f84c4f9
1 Parent(s): a9241d7

Delete loading script

Browse files
Files changed (1) hide show
  1. simple-arithmetic-problems.py +0 -433
simple-arithmetic-problems.py DELETED
@@ -1,433 +0,0 @@
1
- import random
2
- from datasets import (
3
- BuilderConfig,
4
- SplitGenerator,
5
- GeneratorBasedBuilder,
6
- DatasetInfo,
7
- Value,
8
- Features,
9
- )
10
- from decimal import Decimal
11
- import yaml
12
-
13
- SEED = 42
14
- TEST_SIZE = 0.2
15
- DIVISION_RESULT_MULTIPLIER = 4
16
- FLOAT_FLOAT_PROBLEM_PROPORTION = 0.3
17
-
18
- _CITATION = """\
19
- @misc{lee2024simplearithmeticproblemsdataset,
20
- title = {Simple Arithmetic Problems},
21
- author={Garreth Lee},
22
- year={2024}
23
- }
24
- """
25
-
26
-
27
- class Operator:
28
- ADD = "+"
29
- SUBTRACT = "-"
30
- MULTIPLY = "*"
31
- DIVIDE = "/"
32
-
33
- OPERATORS = [ADD, SUBTRACT, MULTIPLY, DIVIDE]
34
-
35
- @classmethod
36
- def is_operator(cls, value):
37
- return value in cls.OPERATORS
38
-
39
- @classmethod
40
- def operator_to_name(cls, value):
41
- if value == cls.ADD:
42
- return "add"
43
- elif value == cls.SUBTRACT:
44
- return "subtract"
45
- elif value == cls.MULTIPLY:
46
- return "multiply"
47
- elif value == cls.DIVIDE:
48
- return "divide"
49
- else:
50
- raise ValueError(f"Invalid operator: {value}")
51
-
52
-
53
- class OperationType:
54
- INT_INT = [False, False]
55
- INT_FLOAT = [True, False]
56
- FLOAT_FLOAT = [True, True]
57
-
58
-
59
- class ArithmeticProblemsConfig:
60
- def __init__(
61
- self,
62
- config_file_path: str,
63
- ) -> None:
64
- with open(config_file_path) as f:
65
- self.config = yaml.safe_load(f)
66
-
67
-
68
- class ArithmeticProblemsConfig(BuilderConfig):
69
- def __init__(
70
- self,
71
- name: str,
72
- num_problems: int,
73
- min_exponent: int,
74
- max_exponent: int,
75
- max_rounding_precision: int,
76
- use_commas: bool = False,
77
- **kwargs,
78
- ):
79
- super().__init__(name=name)
80
- self.num_problems = num_problems
81
- self.min_exponent = min_exponent
82
- self.max_exponent = max_exponent
83
- self.max_rounding_precision = max_rounding_precision
84
- self.use_commas = use_commas
85
- self.kwargs = kwargs
86
-
87
-
88
- class ArithmeticProblemsDataset(GeneratorBasedBuilder):
89
- BUILDER_CONFIG_CLASS = ArithmeticProblemsConfig
90
- FLOAT_ANSWER_ROUNDING_PRECISION = 4
91
-
92
- BUILDER_CONFIGS = [
93
- ArithmeticProblemsConfig(
94
- name="very_easy",
95
- num_problems=5000,
96
- min_exponent=0,
97
- max_exponent=1,
98
- max_rounding_precision=1,
99
- ),
100
- ArithmeticProblemsConfig(
101
- name="easy",
102
- num_problems=5000,
103
- min_exponent=0,
104
- max_exponent=2,
105
- max_rounding_precision=2,
106
- ),
107
- ArithmeticProblemsConfig(
108
- name="medium",
109
- num_problems=5000,
110
- min_exponent=1,
111
- max_exponent=3,
112
- max_rounding_precision=3,
113
- ),
114
- ArithmeticProblemsConfig(
115
- name="hard",
116
- num_problems=5000,
117
- min_exponent=1,
118
- max_exponent=4,
119
- max_rounding_precision=4,
120
- ),
121
- ArithmeticProblemsConfig(
122
- name="very_hard",
123
- num_problems=5000,
124
- min_exponent=2,
125
- max_exponent=5,
126
- max_rounding_precision=5,
127
- ),
128
- ArithmeticProblemsConfig(
129
- name="very_easy_use_commas",
130
- num_problems=5000,
131
- min_exponent=0,
132
- max_exponent=1,
133
- max_rounding_precision=1,
134
- use_commas=True,
135
- ),
136
- ArithmeticProblemsConfig(
137
- name="easy_use_commas",
138
- num_problems=5000,
139
- min_exponent=0,
140
- max_exponent=2,
141
- max_rounding_precision=2,
142
- use_commas=True,
143
- ),
144
- ArithmeticProblemsConfig(
145
- name="medium_use_commas",
146
- num_problems=5000,
147
- min_exponent=1,
148
- max_exponent=3,
149
- max_rounding_precision=3,
150
- use_commas=True,
151
- ),
152
- ArithmeticProblemsConfig(
153
- name="hard_use_commas",
154
- num_problems=5000,
155
- min_exponent=1,
156
- max_exponent=4,
157
- max_rounding_precision=4,
158
- use_commas=True,
159
- ),
160
- ArithmeticProblemsConfig(
161
- name="very_hard_use_commas",
162
- num_problems=5000,
163
- min_exponent=2,
164
- max_exponent=5,
165
- max_rounding_precision=5,
166
- use_commas=True,
167
- ),
168
- ]
169
-
170
- VERSION = "1.0.0"
171
-
172
- def _info(self):
173
- return DatasetInfo(
174
- description="Generate arithmetic problems for use in math tokenization",
175
- features=Features(
176
- {
177
- "question": Value("string"),
178
- "answer": Value("string"),
179
- "operator": Value("string"),
180
- }
181
- ),
182
- citation=_CITATION,
183
- )
184
-
185
- def _generate_number(
186
- self, min_val: int, max_val: int, is_float: bool, max_rounding_precision: int
187
- ) -> float | int:
188
- """
189
- Generates a random number within a specified range, either as an integer or float.
190
-
191
- Args:
192
- min_val: The minimum value of the range.
193
- max_val: The maximum value of the range.
194
- is_float: If true, generates a float
195
- max_rounding_precision: The maximum precision to use when rounding the number.
196
-
197
- Returns:
198
- A random number within the specified range, either as an int or a float.
199
- """
200
- if is_float:
201
- # Round to a random precision between 0 and max_rounding_precision
202
- return round(
203
- random.uniform(min_val, max_val),
204
- random.choice(range(1, max_rounding_precision + 1)),
205
- )
206
- else:
207
- return random.randint(min_val, max_val)
208
-
209
- def _format_number(self, number: int | float, use_commas: bool = False) -> str:
210
- """
211
- Rounds a number to a specified precision, and then formats it as a string.
212
-
213
- Args:
214
- number: The number to be formatted.
215
- use_commas: Whether to include commas as thousand separators.
216
-
217
- Returns:
218
- A string representation of the input number, rounded to the specified precision.
219
- """
220
- if use_commas:
221
- return "{:,}".format(number)
222
- else:
223
- return str(number)
224
-
225
- def _construct_equation(
226
- self,
227
- operand1: int | float,
228
- operand2: int | float,
229
- operator: str,
230
- use_commas: bool = False,
231
- ) -> str:
232
- """Helper function for constructing the string equations."""
233
-
234
- return "%s %s %s = " % (
235
- self._format_number(operand1, use_commas),
236
- operator,
237
- self._format_number(operand2, use_commas),
238
- )
239
-
240
- def create_question_answer_pair(
241
- self,
242
- min_value: int,
243
- max_value: int,
244
- operator: str,
245
- use_commas: bool,
246
- operation_type: list[bool],
247
- max_rounding_precision: int | None,
248
- ) -> dict[str, str]:
249
- """Creates a random question and correct answer pair.
250
-
251
- Args:
252
- min_value: The lowest possible random value.
253
- max_value: The highest possible random value.
254
- include_decimals: Whether to include float numbers in the generated problems.
255
- operator: The mathematical operator to use.
256
- use_commas: Whether to use commas to separate numbers right-to-left.
257
-
258
- Returns:
259
- A dictionary containing the equation string and the expected answer.
260
- """
261
- if not Operator.is_operator(operator):
262
- raise ValueError(f"Invalid operator: {operator}")
263
-
264
- is_float1, is_float2 = operation_type
265
- operand1 = self._generate_number(
266
- min_val=min_value,
267
- max_val=max_value,
268
- is_float=is_float1,
269
- max_rounding_precision=max_rounding_precision,
270
- )
271
- operand2 = self._generate_number(
272
- min_val=min_value,
273
- max_val=max_value,
274
- is_float=is_float2,
275
- max_rounding_precision=max_rounding_precision,
276
- )
277
-
278
- if operator == Operator.SUBTRACT:
279
- result = operand1 - operand2
280
- elif operator == Operator.ADD:
281
- result = operand1 + operand2
282
- elif operator == Operator.MULTIPLY:
283
- result = operand1 * operand2
284
- else:
285
- # this prevents a lot of "0" answers from being generated
286
- if operand1 < operand2 or random.random() < 0.01:
287
- operand1, operand2 = operand2, operand1
288
-
289
- if operation_type == OperationType.INT_INT:
290
- tmp = operand1 / operand2
291
-
292
- # we scale the temp result up to prevent a lot of "small divisions"
293
- if tmp < 10:
294
- tmp *= DIVISION_RESULT_MULTIPLIER
295
- if max_value > 999:
296
- tmp *= random.randint(2, 4)
297
-
298
- # prevents zero division
299
- operand1 = int(round(tmp)) * operand2
300
- result = int(operand1 / operand2)
301
-
302
- elif operation_type == OperationType.INT_FLOAT:
303
- operand2 = int(operand2)
304
- tmp = round(
305
- operand1 / operand2,
306
- random.randint(1, max_rounding_precision),
307
- )
308
-
309
- # we scale the temp result up to prevent a lot of "small divisions"
310
- if tmp < 10:
311
- tmp = float(
312
- Decimal(str(tmp)) * Decimal(str(DIVISION_RESULT_MULTIPLIER))
313
- )
314
-
315
- # deals with Python's decimal multiplication precision issue
316
- operand1 = float(Decimal(str(tmp)) * Decimal(str(operand2)))
317
- result = tmp
318
-
319
- else:
320
- tmp = round(
321
- operand1 / operand2, random.randint(1, max_rounding_precision)
322
- )
323
-
324
- # we scale the temp result up to prevent a lot of "small divisions"
325
- if tmp < 10:
326
- tmp = float(
327
- Decimal(str(tmp)) * Decimal(str(DIVISION_RESULT_MULTIPLIER))
328
- )
329
-
330
- # deals with Python's decimal multiplication precision issue
331
- operand1 = float(Decimal(str(tmp)) * Decimal(str(operand2)))
332
- result = tmp
333
-
334
- result = round(result, self.FLOAT_ANSWER_ROUNDING_PRECISION)
335
-
336
- question = self._construct_equation(
337
- operand1=operand1,
338
- operand2=operand2,
339
- operator=operator,
340
- use_commas=use_commas,
341
- )
342
- answer = self._format_number(result, use_commas)
343
-
344
- return {"question": question, "answer": answer, "operator": operator}
345
-
346
- def _split_generators(self, dl_manager, **kwargs) -> list[SplitGenerator]:
347
- generators = []
348
-
349
- for operator in Operator.OPERATORS:
350
- # Create separate splits for each type of number
351
- for type in ("int", "float"):
352
- split_name = f"{type}_{Operator.operator_to_name(operator)}"
353
-
354
- train_generator = SplitGenerator(
355
- name=split_name + "_train",
356
- gen_kwargs={
357
- "num_problems": int(self.config.num_problems * (1 - TEST_SIZE)),
358
- "min_value": 10**self.config.min_exponent,
359
- "max_value": 10**self.config.max_exponent,
360
- "max_rounding_precision": self.config.max_rounding_precision
361
- if type == "float"
362
- else None,
363
- "use_commas": self.config.use_commas,
364
- "operator": operator,
365
- },
366
- )
367
-
368
- test_generator = SplitGenerator(
369
- name=split_name + "_test",
370
- gen_kwargs={
371
- "num_problems": int(self.config.num_problems * TEST_SIZE),
372
- "min_value": 10**self.config.min_exponent,
373
- "max_value": 10**self.config.max_exponent,
374
- "max_rounding_precision": self.config.max_rounding_precision
375
- if type == "float"
376
- else None,
377
- "use_commas": self.config.use_commas,
378
- "operator": operator,
379
- },
380
- )
381
-
382
- generators.append(train_generator)
383
- generators.append(test_generator)
384
-
385
- return generators
386
-
387
- def _generate_examples(
388
- self,
389
- num_problems,
390
- min_value,
391
- max_value,
392
- max_rounding_precision,
393
- use_commas,
394
- operator,
395
- ):
396
- def _get_operation_type(current_idx: int):
397
- # If max_rounding_precision is None, generate only integer problems
398
- """
399
- Determines the type of operation (integer-integer, float-float, or integer-float)
400
- to generate based on the current index and the proportion of float problems.
401
-
402
- Args:
403
- current_idx: The current index of the problem being generated.
404
- num_problems: The total number of problems to generate.
405
- max_rounding_precision: The maximum rounding precision to use when generating float problems.
406
-
407
- Returns:
408
- An OperationType indicating the type of operation to generate.
409
- """
410
- if max_rounding_precision is None:
411
- return OperationType.INT_INT
412
-
413
- # Otherwise, if the current index is less than the float problem proportion,
414
- elif current_idx < num_problems * FLOAT_FLOAT_PROBLEM_PROPORTION:
415
- return OperationType.FLOAT_FLOAT
416
-
417
- else:
418
- return OperationType.INT_FLOAT
419
-
420
- random.seed(SEED)
421
-
422
- for i in range(num_problems):
423
- yield (
424
- str(i),
425
- self.create_question_answer_pair(
426
- min_value=min_value,
427
- max_value=max_value,
428
- operator=operator,
429
- use_commas=use_commas,
430
- operation_type=_get_operation_type(i),
431
- max_rounding_precision=max_rounding_precision,
432
- ),
433
- )