Aspiring Data Science
373 subscribers
425 photos
11 videos
10 files
1.87K links
Заметки экономиста о программировании, прогнозировании и принятии решений, научном методе познания.
Контакт: @fingoldo

I call myself a data scientist because I know just enough math, economics & programming to be dangerous.
Download Telegram
#featureengineering #pysr #symbolicregression

На самом деле, подход символьной регрессии перекликается с моей идеей использования информационно-теоретических метрик.

Читаю сейчас статью pysr, у них интересный подход с генетиком над признаками, отобранными бустингом.

Очень хочу сравнить их результаты со своими на том же игрушечном примере.

Для естественных наук приложение прямое, для машинного обучения, естественно, приложение может быть в создании новых хороших признаков.

Ps. ДА! pysr отлично справился с моим примером!

import numpy as np, pandas as pd

n =100_000
a = np.random.rand(n)
b = np.random.rand(n)
c = np.random.rand(n)
d = np.random.rand(n)
e = np.random.rand(n)
f = np.random.rand(n)

y=a**2/b+f/5+np.log(c)*np.sin(d)

df = pd.DataFrame(
{
"a": a,
"b": b,
"c": c,
"d": d,
"e": e,

}
)

from pysr import PySRRegressor

model = PySRRegressor(
maxsize=20,
niterations=40, # < Increase me for better results
binary_operators=["+", "*"],
unary_operators=[
"cos",
"exp",
"log",
"sin",
"inv(x) = 1/x",
# ^ Custom operator (julia syntax)
],
extra_sympy_mappings={"inv": lambda x: 1 / x},
# ^ Define operator for SymPy as well
elementwise_loss="loss(prediction, target) = (prediction - target)^2",
# ^ Custom loss function (julia syntax)
)

model.fit(df, y)

model.get_best()


после ~6 минут работы

complexity 14
loss 0.003329
score 0.947915
sympy_format a**2/b + log(c)*sin(d) + 0.09998281
👍2
#featureengineering #pysr #symbolicregression #todo

Библиотека pysr заслуживает пристального внимания. Она настолько хорошо сделана, глубока и функциональна, что просто загляденье.

Полностью готова к внедрению в бой, поддерживает оптимизации, кластера, логгинг в тензорборд, пре-отбор признаков с помощью ML, сохранение прогресса в файл и тёплый старт.

Зацените функциональность и количество опций:

model = PySRRegressor(
populations=8,
# ^ Assuming we have 4 cores, this means 2 populations per core, so one is always running.
population_size=50,
# ^ Slightly larger populations, for greater diversity.
ncycles_per_iteration=500,
# ^ Generations between migrations.
niterations=10000000, # Run forever
early_stop_condition=(
"stop_if(loss, complexity) = loss < 1e-6 && complexity < 10"
# Stop early if we find a good and simple equation
),
timeout_in_seconds=60 * 60 * 24,
# ^ Alternatively, stop after 24 hours have passed.
maxsize=50,
# ^ Allow greater complexity.
maxdepth=10,
# ^ But, avoid deep nesting.
binary_operators=["*", "+", "-", "/"],
unary_operators=["square", "cube", "exp", "cos2(x)=cos(x)^2"],
constraints={
"/": (-1, 9),
"square": 9,
"cube": 9,
"exp": 9,
},
# ^ Limit the complexity within each argument.
# "inv": (-1, 9) states that the numerator has no constraint,
# but the denominator has a max complexity of 9.
# "exp": 9 simply states that `exp` can only have
# an expression of complexity 9 as input.
nested_constraints={
"square": {"square": 1, "cube": 1, "exp": 0},
"cube": {"square": 1, "cube": 1, "exp": 0},
"exp": {"square": 1, "cube": 1, "exp": 0},
},
# ^ Nesting constraints on operators. For example,
# "square(exp(x))" is not allowed, since "square": {"exp": 0}.
complexity_of_operators={"/": 2, "exp": 3},
# ^ Custom complexity of particular operators.
complexity_of_constants=2,
# ^ Punish constants more than variables
select_k_features=4,
# ^ Train on only the 4 most important features
progress=True,
# ^ Can set to false if printing to a file.
weight_randomize=0.1,
# ^ Randomize the tree much more frequently
cluster_manager=None,
# ^ Can be set to, e.g., "slurm", to run a slurm
# cluster. Just launch one script from the head node.
precision=64,
# ^ Higher precision calculations.
warm_start=True,
# ^ Start from where left off.
turbo=True,
# ^ Faster evaluation (experimental)
extra_sympy_mappings={"cos2": lambda x: sympy.cos(x)**2},
# extra_torch_mappings={sympy.cos: torch.cos},
# ^ Not needed as cos already defined, but this
# is how you define custom torch operators.
# extra_jax_mappings={sympy.cos: "jnp.cos"},
# ^ For JAX, one passes a string.
)


И на её базе, как понимаю, уже сделаны отличные исследования.
Надо изучать доку.

И хорошо бы её потестить для FE, на каких-то разумных настройках глубины/сложности/времени. И датасетах с в т.ч. большим количеством фичей.
👍2