File size: 5,050 Bytes
465a774 | 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 | """Feature extraction for separating linguistic vs mathematical difficulty in MWPs.
Two orthogonal feature blocks per problem:
LING - readability formulas, lexical (CEFR), syntactic (parse depth, dependency length)
MATH - solution-step count, operation count/type, equation/number complexity
"""
import re
import numpy as np
import textstat
import spacy
from cefrpy import CEFRAnalyzer
_NLP = spacy.load("en_core_web_sm")
_CEFR = CEFRAnalyzer()
_CEFR_NUM = {"A1": 1, "A2": 2, "B1": 3, "B2": 4, "C1": 5, "C2": 6}
# Protected Common-Core / NCTM math terms - never count as "hard language"
MATH_TERMS = {
"area", "perimeter", "volume", "ratio", "proportion", "fraction", "decimal",
"percent", "percentage", "median", "mean", "mode", "average", "sum", "difference",
"product", "quotient", "divide", "multiply", "add", "subtract", "equation",
"angle", "triangle", "rectangle", "square", "circle", "diameter", "radius",
"numerator", "denominator", "integer", "remainder", "factor", "multiple",
}
def _cefr_features(tokens):
levels = []
above_b1 = 0
for t in tokens:
w = t.lower()
if w in MATH_TERMS:
continue
lvl = _CEFR.get_average_word_level_CEFR(w)
if lvl is not None:
n = int(lvl.value) # CEFRLevel enum -> 1..6
levels.append(n)
if n >= 3: # B1 or above
above_b1 += 1
if not levels:
return 0.0, 0.0, 0.0
return float(np.mean(levels)), float(np.max(levels)), above_b1 / max(len(levels), 1)
def _syntactic_features(doc):
# parse-tree depth (max distance to root), mean dependency length
depths, dep_lens = [], []
n_clauses = 0
n_subord = 0
for sent in doc.sents:
for tok in sent:
# depth: walk up to root
d, cur = 0, tok
while cur.head != cur:
cur = cur.head
d += 1
if d > 50:
break
depths.append(d)
dep_lens.append(abs(tok.i - tok.head.i))
if tok.dep_ in ("ccomp", "advcl", "relcl", "acl", "xcomp"):
n_clauses += 1
if tok.dep_ == "mark" or tok.tag_ == "IN" and tok.dep_ == "mark":
n_subord += 1
return (
float(np.max(depths)) if depths else 0.0,
float(np.mean(dep_lens)) if dep_lens else 0.0,
float(n_clauses),
)
def linguistic_features(text):
doc = _NLP(text)
tokens = [t.text for t in doc if t.is_alpha]
fk = textstat.flesch_kincaid_grade(text)
fre = textstat.flesch_reading_ease(text)
dc = textstat.dale_chall_readability_score(text)
n_words = len(tokens)
n_sents = max(len(list(doc.sents)), 1)
mean_word_len = float(np.mean([len(t) for t in tokens])) if tokens else 0.0
cefr_mean, cefr_max, cefr_above_b1 = _cefr_features(tokens)
parse_depth, mean_dep_len, n_clauses = _syntactic_features(doc)
return {
"ling_fk_grade": fk,
"ling_flesch_ease": fre,
"ling_dale_chall": dc,
"ling_n_words": n_words,
"ling_words_per_sent": n_words / n_sents,
"ling_mean_word_len": mean_word_len,
"ling_cefr_mean": cefr_mean,
"ling_cefr_max": cefr_max,
"ling_cefr_above_b1": cefr_above_b1,
"ling_parse_depth": parse_depth,
"ling_mean_dep_len": mean_dep_len,
"ling_n_clauses": n_clauses,
}
_OPS = re.compile(r"[+\-*/]")
def math_features_from_chain(chain):
"""ASDiv: count <gadget> calculator steps and operators."""
n_steps = chain.count("<gadget")
# only look at expressions inside gadget tags to avoid counting tag slashes
exprs = " ".join(re.findall(r'<gadget[^>]*>(.*?)</gadget>', chain, flags=re.S))
ops = _OPS.findall(exprs)
nums = re.findall(r"\d+\.?\d*", exprs)
max_num = max([float(n) for n in nums], default=0.0)
has_frac = 1.0 if "/" in exprs else 0.0
has_dec = 1.0 if any("." in n for n in nums) else 0.0
return {
"math_n_steps": float(max(n_steps, 1)),
"math_n_ops": float(len(ops)),
"math_max_num": max_num,
"math_has_frac": has_frac,
"math_has_decimal": has_dec,
}
def math_features_from_equation(eq):
"""SVAMP: parse the Equation string."""
ops = _OPS.findall(eq)
nums = re.findall(r"\d+\.?\d*", eq)
max_num = max([float(n) for n in nums], default=0.0)
depth = 0
cur = 0
for ch in eq:
if ch == "(":
cur += 1
depth = max(depth, cur)
elif ch == ")":
cur -= 1
return {
"math_n_ops": float(len(ops)),
"math_max_num": max_num,
"math_paren_depth": float(depth),
"math_has_decimal": 1.0 if any("." in n and float(n) != int(float(n)) for n in nums) else 0.0,
}
if __name__ == "__main__":
t = "Ellen has six more balls than Marin. Marin has nine balls. How many balls does Ellen have?"
print(linguistic_features(t))
print(math_features_from_chain('<gadget id="calculator">6 + 9</gadget>'))
|