Create simple-arithmetic-problems.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433import randomfrom datasets import ( BuilderConfig, SplitGenerator, GeneratorBasedBuilder, DatasetInfo, Value, Features,)from decimal import Decimalimport yaml
SEED = 42TEST_SIZE = 0.2DIVISION_RESULT_MULTIPLIER = 4FLOAT_FLOAT_PROBLEM_PROPORTION = 0.3
_CITATION = """\@misc{lee2024simplearithmeticproblemsdataset,title = {Simple Arithmetic Problems},author={Garreth Lee},year={2024}}"""
class Operator: ADD = "+" SUBTRACT = "-" MULTIPLY = "*" DIVIDE = "/"
OPERATORS = [ADD, SUBTRACT, MULTIPLY, DIVIDE]
@classmethod def is_operator(cls, value): return value in cls.OPERATORS
@classmethod def operator_to_name(cls, value): if value == cls.ADD: return "add" elif value == cls.SUBTRACT: return "subtract" elif value == cls.MULTIPLY: return "multiply" elif value == cls.DIVIDE: return "divide" else: raise ValueError(f"Invalid operator: {value}")
class OperationType: INT_INT = [False, False] INT_FLOAT = [True, False] FLOAT_FLOAT = [True, True]
class ArithmeticProblemsConfig: def __init__( self, config_file_path: str, ) -> None: with open(config_file_path) as f: self.config = yaml.safe_load(f)
class ArithmeticProblemsConfig(BuilderConfig): def __init__( self, name: str, num_problems: int, min_exponent: int, max_exponent: int, max_rounding_precision: int, use_commas: bool = False, **kwargs, ): super().__init__(name=name) self.num_problems = num_problems self.min_exponent = min_exponent self.max_exponent = max_exponent self.max_rounding_precision = max_rounding_precision self.use_commas = use_commas self.kwargs = kwargs
class ArithmeticProblemsDataset(GeneratorBasedBuilder): BUILDER_CONFIG_CLASS = ArithmeticProblemsConfig FLOAT_ANSWER_ROUNDING_PRECISION = 4
BUILDER_CONFIGS = [ ArithmeticProblemsConfig( name="very_easy", num_problems=5000, min_exponent=0, max_exponent=1, max_rounding_precision=1, ), ArithmeticProblemsConfig( name="easy", num_problems=5000, min_exponent=0, max_exponent=2, max_rounding_precision=2, ), ArithmeticProblemsConfig( name="medium", num_problems=5000, min_exponent=1, max_exponent=3, max_rounding_precision=3, ), ArithmeticProblemsConfig( name="hard", num_problems=5000, min_exponent=1, max_exponent=4, max_rounding_precision=4, ), ArithmeticProblemsConfig( name="very_hard", num_problems=5000, min_exponent=2, max_exponent=5, max_rounding_precision=5, ), ArithmeticProblemsConfig( name="very_easy_use_commas", num_problems=5000, min_exponent=0, max_exponent=1, max_rounding_precision=1, use_commas=True, ), ArithmeticProblemsConfig( name="easy_use_commas", num_problems=5000, min_exponent=0, max_exponent=2, max_rounding_precision=2, use_commas=True, ), ArithmeticProblemsConfig( name="medium_use_commas", num_problems=5000, min_exponent=1, max_exponent=3, max_rounding_precision=3, use_commas=True, ), ArithmeticProblemsConfig( name="hard_use_commas", num_problems=5000, min_exponent=1, max_exponent=4, max_rounding_precision=4, use_commas=True, ), ArithmeticProblemsConfig( name="very_hard_use_commas", num_problems=5000, min_exponent=2, max_exponent=5, max_rounding_precision=5, use_commas=True, ), ]
VERSION = "1.0.0"
def _info(self): return DatasetInfo( description="Generate arithmetic problems for use in math tokenization", features=Features( { "question": Value("string"), "answer": Value("string"), "operator": Value("string"), } ), citation=_CITATION, )
def _generate_number( self, min_val: int, max_val: int, is_float: bool, max_rounding_precision: int ) -> float | int: """ Generates a random number within a specified range, either as an integer or float.
Args: min_val: The minimum value of the range. max_val: The maximum value of the range. is_float: If true, generates a float max_rounding_precision: The maximum precision to use when rounding the number.
Returns: A random number within the specified range, either as an int or a float. """ if is_float: # Round to a random precision between 0 and max_rounding_precision return round( random.uniform(min_val, max_val), random.choice(range(1, max_rounding_precision + 1)), ) else: return random.randint(min_val, max_val)
def _format_number(self, number: int | float, use_commas: bool = False) -> str: """ Rounds a number to a specified precision, and then formats it as a string.
Args: number: The number to be formatted. use_commas: Whether to include commas as thousand separators.
Returns: A string representation of the input number, rounded to the specified precision. """ if use_commas: return "{:,}".format(number) else: return str(number)
def _construct_equation( self, operand1: int | float, operand2: int | float, operator: str, use_commas: bool = False, ) -> str: """Helper function for constructing the string equations."""
return "%s %s %s = " % ( self._format_number(operand1, use_commas), operator, self._format_number(operand2, use_commas), )
def create_question_answer_pair( self, min_value: int, max_value: int, operator: str, use_commas: bool, operation_type: list[bool], max_rounding_precision: int | None, ) -> dict[str, str]: """Creates a random question and correct answer pair.
Args: min_value: The lowest possible random value. max_value: The highest possible random value. include_decimals: Whether to include float numbers in the generated problems. operator: The mathematical operator to use. use_commas: Whether to use commas to separate numbers right-to-left.
Returns: A dictionary containing the equation string and the expected answer. """ if not Operator.is_operator(operator): raise ValueError(f"Invalid operator: {operator}")
is_float1, is_float2 = operation_type operand1 = self._generate_number( min_val=min_value, max_val=max_value, is_float=is_float1, max_rounding_precision=max_rounding_precision, ) operand2 = self._generate_number( min_val=min_value, max_val=max_value, is_float=is_float2, max_rounding_precision=max_rounding_precision, )
if operator == Operator.SUBTRACT: result = operand1 - operand2 elif operator == Operator.ADD: result = operand1 + operand2 elif operator == Operator.MULTIPLY: result = operand1 * operand2 else: # this prevents a lot of "0" answers from being generated if operand1 < operand2 or random.random() < 0.01: operand1, operand2 = operand2, operand1
if operation_type == OperationType.INT_INT: tmp = operand1 / operand2
# we scale the temp result up to prevent a lot of "small divisions" if tmp < 10: tmp *= DIVISION_RESULT_MULTIPLIER if max_value > 999: tmp *= random.randint(2, 4)
# prevents zero division operand1 = int(round(tmp)) * operand2 result = int(operand1 / operand2)
elif operation_type == OperationType.INT_FLOAT: operand2 = int(operand2) tmp = round( operand1 / operand2, random.randint(1, max_rounding_precision), )
# we scale the temp result up to prevent a lot of "small divisions" if tmp < 10: tmp = float( Decimal(str(tmp)) * Decimal(str(DIVISION_RESULT_MULTIPLIER)) )
# deals with Python's decimal multiplication precision issue operand1 = float(Decimal(str(tmp)) * Decimal(str(operand2))) result = tmp
else: tmp = round( operand1 / operand2, random.randint(1, max_rounding_precision) )
# we scale the temp result up to prevent a lot of "small divisions" if tmp < 10: tmp = float( Decimal(str(tmp)) * Decimal(str(DIVISION_RESULT_MULTIPLIER)) )
# deals with Python's decimal multiplication precision issue operand1 = float(Decimal(str(tmp)) * Decimal(str(operand2))) result = tmp
result = round(result, self.FLOAT_ANSWER_ROUNDING_PRECISION)
question = self._construct_equation( operand1=operand1, operand2=operand2, operator=operator, use_commas=use_commas, ) answer = self._format_number(result, use_commas)
return {"question": question, "answer": answer, "operator": operator}
def _split_generators(self, dl_manager, **kwargs) -> list[SplitGenerator]: generators = []
for operator in Operator.OPERATORS: # Create separate splits for each type of number for type in ("int", "float"): split_name = f"{type}_{Operator.operator_to_name(operator)}"
train_generator = SplitGenerator( name=split_name + "_train", gen_kwargs={ "num_problems": int(self.config.num_problems * (1 - TEST_SIZE)), "min_value": 10**self.config.min_exponent, "max_value": 10**self.config.max_exponent, "max_rounding_precision": self.config.max_rounding_precision if type == "float" else None, "use_commas": self.config.use_commas, "operator": operator, }, )
test_generator = SplitGenerator( name=split_name + "_test", gen_kwargs={ "num_problems": int(self.config.num_problems * TEST_SIZE), "min_value": 10**self.config.min_exponent, "max_value": 10**self.config.max_exponent, "max_rounding_precision": self.config.max_rounding_precision if type == "float" else None, "use_commas": self.config.use_commas, "operator": operator, }, )
generators.append(train_generator) generators.append(test_generator)
return generators
def _generate_examples( self, num_problems, min_value, max_value, max_rounding_precision, use_commas, operator, ): def _get_operation_type(current_idx: int): # If max_rounding_precision is None, generate only integer problems """ Determines the type of operation (integer-integer, float-float, or integer-float) to generate based on the current index and the proportion of float problems.
Args: current_idx: The current index of the problem being generated. num_problems: The total number of problems to generate. max_rounding_precision: The maximum rounding precision to use when generating float problems.
Returns: An OperationType indicating the type of operation to generate. """ if max_rounding_precision is None: return OperationType.INT_INT
# Otherwise, if the current index is less than the float problem proportion, elif current_idx < num_problems * FLOAT_FLOAT_PROBLEM_PROPORTION: return OperationType.FLOAT_FLOAT
else: return OperationType.INT_FLOAT
random.seed(SEED)
for i in range(num_problems): yield ( str(i), self.create_question_answer_pair( min_value=min_value, max_value=max_value, operator=operator, use_commas=use_commas, operation_type=_get_operation_type(i), max_rounding_precision=max_rounding_precision, ), )simple-arithmetic-problems.pyAdded+433