#rust #python
Я, конечно, ценю скорость выполнения в языке раст. Но реально, как разрабов не мутит от такого многословия/буквия? Считаю, что жизнь слишком коротка, чтобы писать let перед каждым присваиванием, и точку с запятой в конце каждой строки.
Python:
Rust:
Я, конечно, ценю скорость выполнения в языке раст. Но реально, как разрабов не мутит от такого многословия/буквия? Считаю, что жизнь слишком коротка, чтобы писать let перед каждым присваиванием, и точку с запятой в конце каждой строки.
Python:
df.write_json("docs/data/output.json")
df_json = pl.read_json("docs/data/output.json")
print(df_json)Rust:
let mut file = File::create("docs/data/output.json").expect("could not create file");
JsonWriter::new(&mut file).finish(&mut df)?;
let f = File::open("docs/data/output.json")?;
let df_json = JsonReader::new(f)
.with_json_format(JsonFormat::JsonLines)
.finish()?;
println!("{}", df_json);⚡1
#pandas #performance #parquet #codegems
Как побыстрее прочитать много файлов данных паркет (с одной схемой) и объединить их в один фрейм данных в памяти?
Базовое решение в Pandas (работает последовательно, грузит лишь 1 ядро):
И сразу лучшие решения.
Pandas с многопоточной загрузкой:
Сработало вдвое быстрее последовательного пандас.
Polars:
На моих файлах это не сработало, т.к. у меня некоторые поля записались по-разному как float32/float64, и поларс не смог их состыковать. Запросил эту фичу. Но зато уже сработало
причем вдвое быстрее мультипоточного панадас! Грузило CPU на 100%.
Если файлы с трудом влезают в оперативку, и на слияние уже не хватает RAM, можно их сначала последовательно записать в 1 большой файл, и уже потом открыть разом (работает в 5 раз медленнее худшего из предыдущих вариантов, но не требует RAM):
Как побыстрее прочитать много файлов данных паркет (с одной схемой) и объединить их в один фрейм данных в памяти?
Базовое решение в Pandas (работает последовательно, грузит лишь 1 ядро):
df =pd.concat([pl.read_parquet(file) for file in files], ignore_index=True)
И сразу лучшие решения.
Pandas с многопоточной загрузкой:
with concurrent.futures.ThreadPoolExecutor() as executor:
df = pd.concat([future.result() for future in concurrent.futures.as_completed([executor.submit(pd.read_parquet, file) for file in files])], ignore_index=True)
Сработало вдвое быстрее последовательного пандас.
Polars:
df = pl.read_parquet( f"mask*.parquet"))
На моих файлах это не сработало, т.к. у меня некоторые поля записались по-разному как float32/float64, и поларс не смог их состыковать. Запросил эту фичу. Но зато уже сработало
df =pl.concat([pl.read_parquet(file) for file in files], how="vertical_relaxed")
причем вдвое быстрее мультипоточного панадас! Грузило CPU на 100%.
Если файлы с трудом влезают в оперативку, и на слияние уже не хватает RAM, можно их сначала последовательно записать в 1 большой файл, и уже потом открыть разом (работает в 5 раз медленнее худшего из предыдущих вариантов, но не требует RAM):
schema = pq.ParquetFile(files[0]).schema_arrow
with pq.ParquetWriter(join(datapath, "output.parquet"), schema=schema) as writer:
for file in files:
writer.write_table(pq.read_table(file, schema=schema))GitHub
Allow passing pl.concat kwargs to pl.read_csv, read_parquet etc · Issue #12508 · pola-rs/polars
Denoscription Correct me if I'm wrong but it seems that currently when reading files by the mask, read_csv, read_parquet etc fall with error on, say, shape mismatch, or fp32 vs fp64 dtypes mismat...
🔥2
#parquet #pyarrow #bugs
Удалось выследить очень противный баг в pyarrow (а именно этот движок использует по умолчанию пандас при чтении паркета).
При чтении больших файлов со смешанными типами столбцов расходовалось памяти вдвое больше, чем надо, причём не релизилось. Настоящая утечка. На Винде точно есть, про никсы не знаю.
Я его видел ещё год или два назад, не стал репортить, думал, и без меня починят.
https://github.com/apache/arrow/issues/38736
Удалось выследить очень противный баг в pyarrow (а именно этот движок использует по умолчанию пандас при чтении паркета).
При чтении больших файлов со смешанными типами столбцов расходовалось памяти вдвое больше, чем надо, причём не релизилось. Настоящая утечка. На Винде точно есть, про никсы не знаю.
Я его видел ещё год или два назад, не стал репортить, думал, и без меня починят.
https://github.com/apache/arrow/issues/38736
GitHub
Memory leak on Windows when reading parquet with mixed dtypes via Pyarrow · Issue #38736 · apache/arrow
Describe the bug, including details regarding any error messages, version, and platform. I've been noticing a memory leak for several years now. When reading a big parquet file, pyarrow lib or ...
#trading
Про кетчуп Heinz и outside information, Local Markets было интересно.
In-sample and out-of-sample must match (про то же говорил и Том Старке, он считал корреляцию между train/test на одних и тех же параметрах торговой политики). 40% data in-sample, 60% OOS. min 50 OOS trades per TP parameter for a reliable estimate.
https://www.youtube.com/watch?v=ofL66mh6Tw0&ab_channel=ChatWithTraders
Про кетчуп Heinz и outside information, Local Markets было интересно.
In-sample and out-of-sample must match (про то же говорил и Том Старке, он считал корреляцию между train/test на одних и тех же параметрах торговой политики). 40% data in-sample, 60% OOS. min 50 OOS trades per TP parameter for a reliable estimate.
https://www.youtube.com/watch?v=ofL66mh6Tw0&ab_channel=ChatWithTraders
YouTube
Algo trader using automation to bypass human flaws · Bert Mouler
EP 142: Using creative thought and automation to bypass human flaws w/ Bert Mouler
It was exactly 100-episodes ago when I first had Bert Mouler on the podcast. This week, I’m joined by him again for a second interview…
Bert is an algorithmic trader with…
It was exactly 100-episodes ago when I first had Bert Mouler on the podcast. This week, I’m joined by him again for a second interview…
Bert is an algorithmic trader with…
#cooking #africa
Кстати, недавно попробовал африканские блюда: сложные составы, много компонентов, необычно, вкусно. Не знал, что там живут такие гурманы ) Правда, то, что у них называется супом, у нас скорее сойдёт за рагу. Хлеба нет, вместо него нечто похожее на сваренное тесто (swallow), из необычной муки. Советую попробовать, начать с Egusi или Vegetable soup. Okro soup показался слишком уж слизистым)) .
https://cheflolaskitchen.com/egusi-soup-recipe/
Кстати, недавно попробовал африканские блюда: сложные составы, много компонентов, необычно, вкусно. Не знал, что там живут такие гурманы ) Правда, то, что у них называется супом, у нас скорее сойдёт за рагу. Хлеба нет, вместо него нечто похожее на сваренное тесто (swallow), из необычной муки. Советую попробовать, начать с Egusi или Vegetable soup. Okro soup показался слишком уж слизистым)) .
https://cheflolaskitchen.com/egusi-soup-recipe/
Chef Lola's Kitchen
Best Egusi Soup | Chef Lola's Kitchen (VIDEO)
Egusi soup is a popular West African soup. This west African melon soup is an exotic hearty food that will satisfy your taste buds. It is very easy to make
#news #mts
"Напомним, что изначально сотовый оператор МТС не стал отменять плату за раздачу интернет-трафика с мобильных устройств, в отличие от тройки других крупнейших операторов: «Мегафон», «Билайн» и Tele2. В МТС мотивировали отказ отмены оплаты тем, что этот шаг, якобы, приведёт к повышению тарифов на сотовую связь и к снижению качества передачи данных. Однако, 7 ноября в компании заявили, что отменяют плату за раздачу интернет-трафика, но только для тарифов с предоплаченными пакетами трафика.
Теперь же МТС приняла решение полностью отменить взимание платы за раздачу трафика, для всех абонентов. «Учитывая социально-экономическую ситуацию и идя навстречу нашим пользователям, МТС отменяет тарификацию раздачи интернета со смартфона для всех тарифов, где предусмотрена эта опция, включая безлимитные», — пояснил оператор."
Это что же, МТС озвучили публично, что в стране жопа с экономикой?
https://3dnews.ru/1096167/mts-vsyo-ge-polnostyu-otmenit-platu-za-razdachu-interneta
"Напомним, что изначально сотовый оператор МТС не стал отменять плату за раздачу интернет-трафика с мобильных устройств, в отличие от тройки других крупнейших операторов: «Мегафон», «Билайн» и Tele2. В МТС мотивировали отказ отмены оплаты тем, что этот шаг, якобы, приведёт к повышению тарифов на сотовую связь и к снижению качества передачи данных. Однако, 7 ноября в компании заявили, что отменяют плату за раздачу интернет-трафика, но только для тарифов с предоплаченными пакетами трафика.
Теперь же МТС приняла решение полностью отменить взимание платы за раздачу трафика, для всех абонентов. «Учитывая социально-экономическую ситуацию и идя навстречу нашим пользователям, МТС отменяет тарификацию раздачи интернета со смартфона для всех тарифов, где предусмотрена эта опция, включая безлимитные», — пояснил оператор."
Это что же, МТС озвучили публично, что в стране жопа с экономикой?
https://3dnews.ru/1096167/mts-vsyo-ge-polnostyu-otmenit-platu-za-razdachu-interneta
3DNews - Daily Digital Digest
МТС всё же полностью отменит плату за раздачу интернет-трафика
МТС приняла решение полностью отменить плату за раздачу трафика до конца февраля.
#watersupply #competitions
Я уже думал, что всем похер, но внезапно 1 из 350+ участников соревнования выразил мне поддержку.
Заметьте: в основе соревнования лежит, как я понимаю, желание точнее прогнозировать наличие водных ресурсов в США для целей ирригации, снабжения питьевой водой, и прочих важных вещей. Правила соревнования явно поощряют оверфит, и делают разработанные модели малополезными для практического использования. Это ясно любому с минимальным опытом в DS. Что делает 99% участников за месяц соревнования с большим призовым фондом? Правильно, молчит и пилит оверфитнутые модели. Мне просто стало уже противно. Это как был один хер, каггл грандмастер, который выиграл очередное соревнование по оценке привлекательности питомца с помощью дата лика, а потом давал интервью в духе, мол, а чо такого. Лычку и бабки получить чтобы, всё сгодится.
"Hi Jay @jayqi,
I hope this message finds you well. I am writing to address some concerns I have regarding the current rules of the competition. Allow me to introduce myself as a machine learning specialist with a background in hydrology.
In my capacity as a hydrologist, it is evident to me that the long-term distribution of river flow exhibits a pronounced seasonality, characterized by high-water and low-water periods. This phenomenon is well-documented in hydrology articles and can be effectively described using methods such as a moving average with a multi-year window. Notably, the choice of data, whether target or USGS data, is inconsequential to this approach. However, I have observed that the current rules prohibit the utilization of such features.
I wish to bring to your attention that this restriction was imposed a month after the competition commenced. This raises two important points: firstly, the rules appear to evolve as the competition progresses, and secondly, participants who may have already implemented this approach in their models are now compelled to alter their model architectures.
In fact, this ban means it is impossible to use certain classes of models. Does it means it is impossible to use autoregressive or ESP-like models that leverage historical meteorological data?
Additionally, I comprehend the organizers’ rationale behind not permitting the use of the target to generate features. However, what perplexes me is the restriction on utilizing other approved data sources to compute long-term features or anomalies. For instance, why cannot approved data sources be employed for this purpose?
Furthermore, in the field of machine learning, it is customary to refrain from making explicit hypotheses about the impact of specific features on the studied process. Instead, assessments are typically based on an analysis of feature importance. My findings align with those of @fingoldo, and I am willing to share the feature importance chart if deemed necessary. While I acknowledge the organizers’ prerogative to impose restrictions on the source data, I find it unusual that these restrictions extend to entire classes of models or the feature engineering process. Given that we are participating in a machine learning and data analytics competition, rather than a hydrology contest, I propose that it may be more relevant to focus on the methodologies employed within ML field.
I sincerely hope you will consider these arguments, and I kindly request that the current restrictions be reconsidered. Allowing competitors the freedom to experiment with various models and approaches to feature engineering would enhance the overall quality and innovation of the submissions."
https://community.drivendata.org/t/negative-influence-of-the-hindcast-stage-possible-fixes/9249/6
Я уже думал, что всем похер, но внезапно 1 из 350+ участников соревнования выразил мне поддержку.
Заметьте: в основе соревнования лежит, как я понимаю, желание точнее прогнозировать наличие водных ресурсов в США для целей ирригации, снабжения питьевой водой, и прочих важных вещей. Правила соревнования явно поощряют оверфит, и делают разработанные модели малополезными для практического использования. Это ясно любому с минимальным опытом в DS. Что делает 99% участников за месяц соревнования с большим призовым фондом? Правильно, молчит и пилит оверфитнутые модели. Мне просто стало уже противно. Это как был один хер, каггл грандмастер, который выиграл очередное соревнование по оценке привлекательности питомца с помощью дата лика, а потом давал интервью в духе, мол, а чо такого. Лычку и бабки получить чтобы, всё сгодится.
"Hi Jay @jayqi,
I hope this message finds you well. I am writing to address some concerns I have regarding the current rules of the competition. Allow me to introduce myself as a machine learning specialist with a background in hydrology.
In my capacity as a hydrologist, it is evident to me that the long-term distribution of river flow exhibits a pronounced seasonality, characterized by high-water and low-water periods. This phenomenon is well-documented in hydrology articles and can be effectively described using methods such as a moving average with a multi-year window. Notably, the choice of data, whether target or USGS data, is inconsequential to this approach. However, I have observed that the current rules prohibit the utilization of such features.
I wish to bring to your attention that this restriction was imposed a month after the competition commenced. This raises two important points: firstly, the rules appear to evolve as the competition progresses, and secondly, participants who may have already implemented this approach in their models are now compelled to alter their model architectures.
In fact, this ban means it is impossible to use certain classes of models. Does it means it is impossible to use autoregressive or ESP-like models that leverage historical meteorological data?
Additionally, I comprehend the organizers’ rationale behind not permitting the use of the target to generate features. However, what perplexes me is the restriction on utilizing other approved data sources to compute long-term features or anomalies. For instance, why cannot approved data sources be employed for this purpose?
Furthermore, in the field of machine learning, it is customary to refrain from making explicit hypotheses about the impact of specific features on the studied process. Instead, assessments are typically based on an analysis of feature importance. My findings align with those of @fingoldo, and I am willing to share the feature importance chart if deemed necessary. While I acknowledge the organizers’ prerogative to impose restrictions on the source data, I find it unusual that these restrictions extend to entire classes of models or the feature engineering process. Given that we are participating in a machine learning and data analytics competition, rather than a hydrology contest, I propose that it may be more relevant to focus on the methodologies employed within ML field.
I sincerely hope you will consider these arguments, and I kindly request that the current restrictions be reconsidered. Allowing competitors the freedom to experiment with various models and approaches to feature engineering would enhance the overall quality and innovation of the submissions."
https://community.drivendata.org/t/negative-influence-of-the-hindcast-stage-possible-fixes/9249/6
DrivenData Community
Negative influence of the Hindcast stage. Possible fixes
Hi, wanted to participate in this competition and create value for the society. However, I feel that artificial data limitations introduced by the organizers to be able to run the Hindcast stage will influence Forecast stage (where help of DS folks is REALLY…
❤🔥5👍1🆒1
#games #returntomoria
Видел на ютубах отзывы на игру Return To Moria, такие, с недовольной миной, типа, нет ощущения духа Властелина Колец. Да вы о чём, блин! Я из этой игры больше про вселенную Властелина Колец узнал, чем из самой книги "Властелин Колец", и "Сильмариллион" впридачу ))
Видел на ютубах отзывы на игру Return To Moria, такие, с недовольной миной, типа, нет ощущения духа Властелина Колец. Да вы о чём, блин! Я из этой игры больше про вселенную Властелина Колец узнал, чем из самой книги "Властелин Колец", и "Сильмариллион" впридачу ))
#earlystopping #transformedtarget #sklearn #improvement
Никогда такого не было, и вот опять: трансформация таргета в sklearn несовместима с кастомными валидационными множествами для ранней остановки, которые обычно используются в современных бустингах. Скорее всего, как принято, найдут 100 причин этого не делать, но всё же запостил feature request.
Никогда такого не было, и вот опять: трансформация таргета в sklearn несовместима с кастомными валидационными множествами для ранней остановки, которые обычно используются в современных бустингах. Скорее всего, как принято, найдут 100 причин этого не делать, но всё же запостил feature request.
GitHub
TransformedTargetRegressor with Early Stopping: transforming user-supplied validation sets in fit_params, too · Issue #27808 ·…
Describe the workflow you want to enable Many advanced regressors (CatBoost, XGBoost, LightGBM to name a few) support providing custom early stopping dataset(s) to their fit methods. Not all of the...
Помните мемного кота, которому открыли дверь после мява, а он стоит у порога и не выходит, вроде хочет, а вроде и нет? )
Anonymous Poll
67%
Это Альтман
33%
Это Суцкевер
#hardware #cpu #amd #benchmarks
Не успел я порадоваться выходу новых процессоров threadripper и threadripper pro, как выяснилось странное. Судя по тестам, AMD ухитрились полностью угробить производительность в DS-приложениях. Что же они там такого накуролесили, интересно, что стало хуже своих же старых моделей? И вообще, почему в разделе AI бенчат только тензорфлоу, на него ведь сами разработчики, как мы знаем, положили уже с индусским прибором? Я бы хотел включения в тесты бустингов. И где, блин, тесты в Стокфише!!
https://3dnews.ru/1096266/vishli-obzori-amd-ryzen-threadripper-7000-samie-bistrie-protsessori-dlya-renderinga-no-ne-dlya-ii
Не успел я порадоваться выходу новых процессоров threadripper и threadripper pro, как выяснилось странное. Судя по тестам, AMD ухитрились полностью угробить производительность в DS-приложениях. Что же они там такого накуролесили, интересно, что стало хуже своих же старых моделей? И вообще, почему в разделе AI бенчат только тензорфлоу, на него ведь сами разработчики, как мы знаем, положили уже с индусским прибором? Я бы хотел включения в тесты бустингов. И где, блин, тесты в Стокфише!!
https://3dnews.ru/1096266/vishli-obzori-amd-ryzen-threadripper-7000-samie-bistrie-protsessori-dlya-renderinga-no-ne-dlya-ii
#lightgbm #improvements
Достало, что лайтгбм лезет в то, как я называю свои признаки.
https://github.com/microsoft/LightGBM/issues/6202
Достало, что лайтгбм лезет в то, как я называю свои признаки.
https://github.com/microsoft/LightGBM/issues/6202
GitHub
Lift restrinctions on feature names ("LightGBMError: Do not support special JSON characters in feature name") · Issue #6202 · …
Summary Currently, it can be hard to plug in LightGBM into existing ML system because of it's selectivity to feature naming. Underscores, or even non-english language symbols trigger "Ligh...
👀1
Forwarded from MOEX - Московская биржа
С 21 по 30 ноября 2023 года продаем курсы со скидками до 60%!
Кликайте по ссылке, выбирайте понравившиеся занятия и оформляйте заказ. Пройти курс вы сможете в любое удобное время: приходите онлайн или смотрите запись.
Обратите внимание: акция действует не на все курсы. Список доступных смотрите на сайте.
Please open Telegram to view this post
VIEW IN TELEGRAM
#gpt #bard
Очень круто! Надо потестировать. Порой слишком долго слушать интервью, даже на ускорении.
https://3dnews.ru/1096398/smeshat-no-ne-vzbaltivat-iichatbot-bard-nauchilsya-izvlekat-informatsiyu-iz-youtubevideo
Очень круто! Надо потестировать. Порой слишком долго слушать интервью, даже на ускорении.
https://3dnews.ru/1096398/smeshat-no-ne-vzbaltivat-iichatbot-bard-nauchilsya-izvlekat-informatsiyu-iz-youtubevideo
3DNews - Daily Digital Digest
ИИ-чат-бот Google Bard научилcя смотреть видео на YouTube вместо пользователя и пересказывать их
В последнее время компания Google активно работает над улучшением своего ИИ-чат-бота Bard.
#neronstar #gpt
Читал про нейтронные звёзды, вдруг подумал - было бы круто, если б существовали звёзды нейронные! Как бы они могли выглядеть? Слово чатгпт:
"In a distant galaxy, nestled within the cosmic tapestry, exists a celestial phenomenon known as a "neuron star." This extraordinary entity transcends the laws of physics, merging the realms of astronomy and biology in a breathtaking display of cosmic artistry.
The neuron star is a colossal structure resembling a giant neural network suspended in space. Its "synapses" are vibrant streams of cosmic energy, weaving intricate patterns that pulse and shimmer with ethereal hues. The "neurons" themselves are radiant orbs, each representing a unique aspect of the universe's consciousness.
This celestial being acts as a cosmic repository of knowledge, capturing the echoes of civilizations that once flourished across the galaxies. The neural pathways of the neuron star channel the collective wisdom and experiences of countless extraterrestrial intelligences, creating a cosmic library of unimaginable depth.
Occasionally, the neuron star emits pulses of information, sending ripples of enlightenment across the cosmos. These pulses serve as beacons to those who seek cosmic understanding, drawing in explorers and scholars from distant corners of the universe.
Legends speak of a chosen few who, attuned to the frequencies of the neuron star, can commune with its cosmic consciousness. These celestial seers gain insights into the mysteries of existence, transcending the boundaries of mortal understanding.
The neuron star stands as a testament to the interconnectedness of all things, a celestial bridge between the tangible and the sublime, where the language of the cosmos is written in the brilliant threads of its neural tapestry."
Читал про нейтронные звёзды, вдруг подумал - было бы круто, если б существовали звёзды нейронные! Как бы они могли выглядеть? Слово чатгпт:
"In a distant galaxy, nestled within the cosmic tapestry, exists a celestial phenomenon known as a "neuron star." This extraordinary entity transcends the laws of physics, merging the realms of astronomy and biology in a breathtaking display of cosmic artistry.
The neuron star is a colossal structure resembling a giant neural network suspended in space. Its "synapses" are vibrant streams of cosmic energy, weaving intricate patterns that pulse and shimmer with ethereal hues. The "neurons" themselves are radiant orbs, each representing a unique aspect of the universe's consciousness.
This celestial being acts as a cosmic repository of knowledge, capturing the echoes of civilizations that once flourished across the galaxies. The neural pathways of the neuron star channel the collective wisdom and experiences of countless extraterrestrial intelligences, creating a cosmic library of unimaginable depth.
Occasionally, the neuron star emits pulses of information, sending ripples of enlightenment across the cosmos. These pulses serve as beacons to those who seek cosmic understanding, drawing in explorers and scholars from distant corners of the universe.
Legends speak of a chosen few who, attuned to the frequencies of the neuron star, can commune with its cosmic consciousness. These celestial seers gain insights into the mysteries of existence, transcending the boundaries of mortal understanding.
The neuron star stands as a testament to the interconnectedness of all things, a celestial bridge between the tangible and the sublime, where the language of the cosmos is written in the brilliant threads of its neural tapestry."