grokaem_seby | Unsorted

Telegram-канал grokaem_seby - grokaem себя

2301

A bunch of things that I encounter during my journey as NLP/Audio developer

Subscribe to a channel

grokaem себя

Я вам описание баги, вы думаете пару часов, я скидываю решение баги. Погнали 🚀.

Против вас играет Милана из Нижнего Новгорода. Вопрос: прошло несколько экспериментов на multiclass классификацию. На 3 эксперименте вы делаете classification report из sklearn. Круто, 3 эксперимент побеждает по взвешенным метрикам. Вы делаете глоток кофе и замечаете, что support класса номер 30 в 1 эксперименте 139, во втором 4, в третьем 35. И так support значения не совпадают для всех классов во всех экспериментах. Данные вы не мешали, использовали тот же тестовый датасет и один и тот же скрипт.

⌛️Внимание, знатоки, что могло пойти не так?

Читать полностью…

grokaem себя

ЛЕТНЯЯ ШКОЛА AIRI В СИРИУСЕ

В вк выложили все лекции, что были в прошлом году в летней школе. Очень крутые эксперты и детальные лекции. Единственное: грустно, что выложили в вк, а не на ютуб....

upd спасибо читательнице:
youtube версия всех лекций

Лекции про все, от рекомендательных систем до графов и нефти.

#grokaem_dl #grokaem_nlp

Читать полностью…

grokaem себя

WORK ON MISTAKES

I don't fully trust metrics.
- sometimes people just say: our accuracy is 89%. But it means we fail 11%. That's maybe a depression-leading way in life, but certainly helpful in production.

0️⃣ WHY?
- mistakes are sometimes unique and we can determine outliers.
- some mistakes may reveal certain patterns or even mislabeling.

What do I with these 11%?
1️⃣ Test data and get logits of each class.
WHY? See not only label, but also confidence of the model. It can help further to determine the threshold.
Usually you get logits from the last year and can apply softmax on each logits to get probabilities.

2️⃣ Save the results in a csv or whatever and color wrong labels. (convenient when the test data is relatively small)
WHY? We usually have something like a content team, who determine which class is what. This table might be a useful guide for them to relabel some of the samples. I experience it many times when the model classified one sample with a different label and content team agreed that it's better.

function to apply color to the table:

def highlight_rows(row):
color = 'name of color' if row['pred_label'] != row['true_label'] else 'white'
return ['background-color: {}'.format(color) for r in row]

dataframe.style.apply(highlight_rows, axis=1)


3️⃣ If you're using attention mechanism in your model, get the confidence of each word for your output.
WHY?
- It can help to understand which words can be used as garbage or whether some words are very important for the decision making but don't appear in the train dataset at all.
- It can reviele wrong tokenization. For instance, I was classifying negative sentences and word "Ахха" was splitted by BPE as "ах" + "ха" and ах had a very strong importance for label negative, I guess you understand why. So it's important to work with such examples.

Useful library for it:
transformers-interpret - gives interpretation for classifiers from hugging face.
bertviz - gives visual interpretation of transformer like models

🦒giraffe to split languages🦒
Rus short version:
Подход от обратного, когда мы говорим, что наше качество не 89%, а мы фейлимся в 11% помогает распознать неправильные лейблы, а также слабые точки модели. Я на практике использую чаще всего три метода для анализа этих ошибок:
1. Беру вероятности как уверенность модели в решении, это может помочь выявить новые threshold для итогового решения.
2. Подсвечиваю неверные решения на тестовой выборке (если она маленькая), это помогает и мне выявить паттерны ошибок или ошибки в лейблинге.
3. Подсвечиваю важности токенов от attention, чтобы выявить возможное переобучение или дикие кейсы.

#metrics #data_science #business_process
#grokaem_dl

Читать полностью…

grokaem себя

#датасайнс_книги #датасайнс_курсы #asr

A list of courses and books about audio analysis. I will add more to this post in future.

🌚Video🌚
1. Valerio Velardo. I think I rewatched it three times, I even have it downloaded on my computer to watch during long train trips. This theory course is the best. Topics: specs, mel-spectrogram, mfcc, Fourier Transformation in detail, time and frequency domain features.
2. Курс от вышки большой (TTS, Voice conversion и тд). Есть код, есть видео, есть слайды, есть доп. ссылки (rus)
3. Часть курса Deep Learning School: введение в распознавание речи от Нади , TTS от Андрея.

🌒FFT🌒
1. мой недоконспект про все подряд
2. FFT interpretation
3. Простыми словами

🌓Code 🌓
1. Audio features with librosa
2. More about audio representations
3. Audio manipulations with pytorch audio

🌔Blogs and chats🌔
1. Распознавание речи: чат. Можно задавать вопросы профессионалам
2. Надя пробует. Надя иногда рассказывает про papers и новые технологии
3. Voice stuff. Различные посты про обработку аудио

🌝Книжки, они все на русском и советские, но у них какой-то свой клевый вайб))🌝
1. Маленький конспект про речевой тракт и форманты.
2. Фант, акустическая теория речеобразования
3. Динамические спектры сигналов Деркач
4. Обработка сигналов Юкио Сато

Share your resources about audio processing

Читать полностью…

grokaem себя

Скоро будет пост про книги, курсы по rl и аудио, а пока раз уж тут я все публиковала, то вот:

#non_tech_milana

Наверное выскажу одну из самых непопулярных идеи со стороны девушки. Но разве это не унизительно, когда прямым текстом пишут, что на scholarship берут только девушек, что компания отдает приоритет девушкам, что учится или работает 30% девушек в компании и это вау как круто. Это равенство? Это не должно быть акцентом. Это унизительно, если кто-то берет тебя не потому что ты крутая и у тебя есть уникальные скилы, а потому что ты можешь рожать детей. Это не решение проблемы. Это ее усугубление. Я не хотела бы быть на месте парня, который не может получить стипендию, потому что он парень. Если он знает больше меня, может больше меня, давайте приоритет ему. Это очень грустно и унизительно осознавать, что ты можешь получить какую-то роль, какую-то стипендию только потому что ты родилась не парнем, а не долго трудилась над своими знаниями. И я серьезно. Это похоже на эти сексистские шутки и ухмылки. В голове в такие моменты звучит противная слизкая фраза одного моего знакомого "womeeeeen", господи как от нее воротит. Судить нужно на равных.

Я рада, что в детстве меня никто не считал хуже или лучше, потому что я девочка. И никто не говорил мне, что мне нужно родить или выйти замуж, спасибо маме. Сейчас я вижу все меньше таких загонов. Но не нужно считать, что девушки лучше потому что они девушки. Гендерное равенство в том, что все равны и уникальны, в этом и крутость. А так получается, что через лет так 10-20 будет течение, чтобы вернуть права мужскому полу. Так может перестать акцентировать на этом внимание? И выключить уже наконец фильтр по гендеру в профессиональной деятельности.

Всех девушек с праздником, а всех парней с прошедшим и всем равных возможностей

Пс. Ещё всем безопасности везде и отсутствия объективизации.

Читать полностью…

grokaem себя

Thanks to everyone who subscribed, I hope to be helpful. But please "expect disappointment and you'll never be disappointed."

*Now I'm even more stressed to post anything because I've checked who subscribed and you guys are really smart*

Читать полностью…

grokaem себя

EMBEDDINGS NORMALISATION

me: I normalized my vectors and got lower results for my neural network. can you explain what's wrong ?

ChatGPT (with my correction):
There are a few potential reasons for this:

0️⃣ Loss of information: If the length of the vector is an important feature for your model, then normalizing it could hurt performance.

1️⃣ Change in scale: Normalizing a vector can also change the scale of the features which again results in the loss of information.

2️⃣ Data specific: The effect of normalization on performance can also be data-specific. Normalization can help in some cases and hurt in others, depending on the specifics of the data and the model.

🫐🫐🫐 blueberry to split info and cause i like it 🫐🫐🫐
How normalization even works?
1. Let's take a vector [3, 4]
2. Calculate its length using the Pythagorean theorem:
length or magnitude or russian норма = sqrt(3^2 + 4^2) = 5

3. Divide each component by the length to obtain the normalized vector:
[3/5, 4/5]

4. This normalized vector has a length of 1 and points in the same direction as the original vector.

🫐
Why should you do normalization?
We usually do normalization when we don't care about the magnitude of the vector, for instance in cosine similarity. Also normalization is very useful (essential) for linear models.

what other questions do you have about normalization?

#nlp #deep_learning #embeddings #эмбеддинги
#grokaem_nlp

Читать полностью…

grokaem себя

Я стала реже тут писать, наверное потому что обучающие материалы я сейчас иногда пишу для JetBrains Academy, а ужасно душные тексты на английском для диплома. Я не создавала этот канал для других, это была скорее книжка того, что я не знаю. Если вам интересные какие-то темы, собесы или забавные истории и незабавные о сексизме и моих позорах на собесах - пишите в комменты))

Писать я продолжу и на русском, и на английском) Только на английском меня можно читать milana.shxanukova15">на medium (пожалуйста, подпишитесь, хочу 100 подписчиков, чтобы зарабатывать на кофе с mediumа 😂)

Читать полностью…

grokaem себя

COURSE MATH

Some people enjoy watching lectures (yeah, I know some). One of the courses I've found recently was created in MIT and it covers linear algebra with 34 lectures. I highly recommend to study both russian and english versions of linear algebra if you want to read papers later. Course also covers tasks and their solutions, Language is not difficult, video is nice quality.

link to the course

#math #data_science_video
#grokaem_math #grokaem_courses

Читать полностью…

grokaem себя

#data_science_video
Если вы не знали, чем себя занять вечерком, тут Andrey Karpathy GPT from scratch пишет 2 часика.

Читать полностью…

grokaem себя

LYRICS GENERATION

A few weeks ago I asked you for russian singers. I wanted to make a project about lyrics generation based on these authors using hugging face. Why?

1. I like russian language and russian indi and alternative songs. Really? I'm so glad I can understand them wihout a dictionary.
2. I wanted to play with GPT. I made a few post about other language models, but had not use GPT for work or other tasks, so it was time for an experiment. Check out post about gpt, xlnet.
3. I wanted to get more experience with hugging face. I love this library, as it is much easier to work with, but all my other work and pet-projects I implement with PyTorch, as I need a lower level, I wanted to play with high level hugging face more.
4. Why not? It's just interesting, isn't it?

It's not fancy at all, but it was a piece of fun for me. So be ready to cry and let's read lyrics. Maybe I will finish my other projects soon and work on generation music to these songs, who knows...

I certainly want to get deeper with this topic as it's pretty interesting what ideas russian authors share.

That was interesting as the model was sharing common songs between authors and certainly was overfitted on rare authors(

🐻Examples are in comments!🐻

milana.shxanukova15/generate-lyrics-with-gpt-2-4a74701d2953">article

#grokaem_nlp #lyrics_generation

Читать полностью…

grokaem себя

DENIS SEXY IT

#grokaem_blogs

Sometimes I recommend blogs to you that I read. To be honest, I skip most of the detailed posts about CV or 'how to become a data scientist', so I have to unsubscribe from many channels. But there is one that different - Denis Sexy IT. That's nearly the only news channel I read about now, except лентач. The news are detailed to some extent, science-orientated and always so interesting to read! My high recommendation.

Читать полностью…

grokaem себя

ASR for STUTTERING SPEECH

Check out milana.shxanukova15/asr-state-of-the-art-wav2vec-whisper-deepspeech-e1b715c2aed0">my new post about ASR inference for stuttering speech samples.

🦕(is it dinosaur?) dinosaur to explain why I did it 🦕
I'm of the opinion that AI is intended to help people not only interact them. This main purpose is being solved by nearly all of the solutions, the most evident examples are designs by Apple for people with disabilities. I was so impressed by all of the solutions that they build for our everyday actions that we underestimate.

I'm working on dementia classification by audio and speech of dementia ill people is special. They make a lot of pauses, stutter, repeat themselves and so on. It is similar to stuttering speech disorders which include blocks, prolongations and so on. Therefore, I decided to check current pipelines on similar data.
🦕🦕🦕

Before most of the ASR models were trained on clean speech of professionals who were reading books in studious. Now the data is more diversified. Whisper, Wav2Vec and DeepSpeech were analyzed in milana.shxanukova15/asr-state-of-the-art-wav2vec-whisper-deepspeech-e1b715c2aed0">my post. For all models I provide code to make inference, so you can use it later for your work.

other not technical reminders:
if you're reading this, it means you're alive and understand my written words. Appreciate all of your abilities and be attentive to your family and friends.
childhood dementia
children have dialogues with dementia ill people
story of a 39 old man with dementia

#NLP #ASR #milana_medium
#grokaem_audio

Читать полностью…

grokaem себя

ANDREW NG ML

Coursera Machine learning specialization. Andrew Ng.

🐙octopus for preambule🐙
kind reminder: my other recommendations can be found in this channel by #датасайнс_курсы

🐙main part 🐙
Why should you watch it?
- math. Most of the things are implemented manually, so you experience to reconstruct formulas.
- Andrew Ng and his phrase 'don't worry', we all need it.
- short videos
- notebooks for further research
- hints: you always get the right answer, it's helpful when you run out of time

Why should you not watch it?
If you look for the start course, that's not the best choice as it includes math. But if you like it, go on

What do I personally like about it?
- reinforcement learning. This part was the most interesting as I have not learnt about it before. I want to continue studying it with ods course. If you know cool courses about reinforcement learning, please write in comments.
- recommendation systems. I don't really like this topic but it was explained from different angles so I enjoyed it.

#courses #machine_learning #датасайнс_курсы
#grokaem_ml #grokaem_courses

Читать полностью…

grokaem себя

DIVE INTO DEEP LEARNING

I came across a huge blog/book about deep learning and it seems as one of the most informative I've seen. I enjoyed the part about attention as it includes formulas

what is cool?
- code, a lot and easy to grasp
- math, formulas all the way through but not nit-picky approaches
- detailed, each topic has different views
- projects for nlp - sentiment analysis and natural language inference
- gans are also covered slightly
- there are exercises at the end of each topic, some people answer in the comments

🦭🦭🦭fur seals to split blocks for geeks 🦭🦭🦭
- block about math (even geometry)
- block about tools for dl (gpus are discussed)

#grokaem_books #grokaem_nlp
#books #nlp #deep_learning

Читать полностью…

grokaem себя

#grokaem_courses #mlops

Вкуснятина, когда дело доходит не просто модельки погонять у себя в ноутбуках, а оформить, чтобы это было осязаемо и можно было использовать на проде ✨. Кроме того, нужно проследить за версиями и экспериментами. Два курса, которые этому учат:

1. MlOps и продакш подход на ODS - поток закончен, так что можно посмотреть видео и сделать тесты. Мне понравилась лекция про организацию репозитория, с тех пор стараюсь использовать CookieCutter.

upd спасибо комментарию: новый поток MlOps
2. ML ZoomCamp - начнется 15 мая, собираются покрыть много тем. Я постараюсь присоединиться, хочется послушать про Flask и все темы из 4, 5, 6 модуля. Есть возможность сделать финальный проект + домашки. Все на английском.

ML ZoomCamp - starts on 15th May. A lot of topics in MlOps will be covered. I will try to join too as I'm very interested in the 4, 5, 6 modules. The course offers the final project and homeworks.

К организации экспериментов относятся конфиги, про yaml конфиги писала тут.

Читать полностью…

grokaem себя

Я наконец-то почистила навигацию по каналу, много я всякого написала за эти несколько лет 🥵

Теперь в закрепленном сообщении все хештеги. Когда нажимаете на хештег - будут видны слева все посты с названием заглавными буквами. Так легче найти, что вам нужно)

Читать полностью…

grokaem себя

Переживать - это мое всё. Я уже почти научилась не краснеть на собесах и нормально кушать перед экзаменами. Но. Сегодня вот пошла на блиц по нейронкам и хоть 90% вопросов я знала сама, я все равно подготовила небольшой notion по всем вопросам, потому что 'а мало ли' (+ синдром самозванца)

блиц по нейронкам (можно копировать и менять)

Может быть, кому-то будет полезно. Тут не расписаны transformers, но когда-то я запилю что-то большое по ним, а так интересные вопросы по transformers в моих постах:
книжка по трансформерам
пост небольшой по ним
xlnet
attention

Читать полностью…

grokaem себя

#датасайнс_книги

NLP with Transformers. Эдакая поваренная книжка с рецептами по шагам для задач классификации, NER, text generation, summarisation, question answering.

Из особенностей или собственно суть книги:
- блок про anatomy of transformers, разбирается каждый блок вместе с кодом, приводится дерево transformer based моделей
- make transformers efficient in production - отдельный блок про клевые штуки, которые делают умные ребята: knowledge distillation, quantization, pruning, graph optimization
- есть еще блок про тренировку from scratch, там понравились метрики для оценки tokenizers (p.436)

🤗pros
+ актуальные темы и на них всех есть примеры
+ легкое повествование вместе с табличками и схемами
+ в меру матеши и объяснений
+ есть советы по ошибкам, ограничениям памяти и тд

🤗cons
- кратко и сжато, но это и не учебник
- версии у hugging face меняются, так что что-то может не работать с ростом обновлений, но у книги куча future directions, так что обновления кода должны быть

Я не читала сама всё, но многие моменты показались интересными. Особенно советую, когда либо не знаете с чего начать, либо вдруг почему-то решили transformers разобрать.

Читать полностью…

grokaem себя

#nlp #deep_learning #embeddings #эмбеддинги

- Okay, Milana, there is a mistake: cosine similarity cannot be negative.
- Oh, it can be.

0️⃣ What is it?
Cosine similarity is a metric that determines how two vectors (words, sentences, features) are similar to each other. Basically, it is an angle between two vectors.

1️⃣ Range
Similarity range is between -1 to 1, where -1 absolutely opposite vectors (python - security of code), 0 no correlation (university knowledge - work), 1 absolutely similar (chatgpt - hype). It can be explained again by the angles, remember the cosine of two vectors that point to different directions. The angle between them is 180, they are opposite, cosine is equal to -1.
some explanation

2️⃣ Cosine distance
cosine distance = 1 - cosine similarity

Range 0 to 2, 0 - identical vectors, 1 - no correlation, 2 - absolutely different.

2️⃣.1️⃣ Why use cosine distance?
While cosine similarity measures how similar two vectors are, cosine distance measures how different they are.
In real applications it depends on the task what function to choose. You can use cosine similarity as a loss function or as a measure for clustering.

You can check nn.CosineSimilarity and nn.CosineEmbeddingLoss, I personally use the second one as a loss function to learn embeddings of pairs.

3️⃣ Normalisation, how does it affect cosine similarity?
Well, it depends....on the type of normalisation you use. If you use the normalisation technique we have discussed previously, you will see no difference. However, when you normalise your embeddings with Z-score normalisation (v - mean)/ std, you will get different results as both your mean and std change. Just keep it in mind.

4️⃣ Soft cosine measure
One of the common changes suggested in 2014 the basic idea is that we use additional similarity matrix for all features of vectors. I consider it as an efficient method for TF-IDF case. For instance, when we need to show that such words as play and game are close to each other in semantic sense, but it cannot be captured with cos similarity of just sentences "a player will play a game they like to play", "they play the game they like". Similarity matrix can be constructed by word-embeddings similarity, Levenshtein or whatever you want.

Читать полностью…

grokaem себя

#deep_learning #community #nlp #cv #machine_learning

Если бы не комьюнити, я бы забила на все еще в первый год. Комьюнити также помогает найти работу, тебя закидывают по реферальной, появляются ребята, с которыми вместе можно делать проекты и самое главное - задать вопрос! Короче, для этого был ods, но сейчас все немного стало тише с ним, ребята создали /channel/betterdatacommunity . Кажется, будет что-то очень крутое))

Читать полностью…

grokaem себя

#grokaem_random #nlp #deep_learning

Random things I encountered, that either impressed me or saved my time.

0️⃣ Использовать lambda функцию не только как часть pandas apply или маппинг в словаре, но и для тензоров. Например, transform_tensor = lambda x: torch.concat(x).squeeze().flatten().cpu().numpy().astype(int) Мне очень не нравилось писать это для 4 тензоров, а такая обертка довольно интуитивно понятная.

1️⃣ Мб, кто-то не знал, но можно делать print в файл, то есть:
with open('', 'w') as f:
print('', file=f)

2️⃣ black - я ненавижу сидеть и двигать эти too long lines или trailing whitespaces, со временем привыкаешь верно писать, но пока что-то дебажишь, обязательно становится грязно и black красиво все чистит, можно уточнить, какую макс длину хотите.

3️⃣ dict(zip()) - самая крутая штука, я знала о ней давно, но ввела в привычку недавно, советую для тех же pandas таблиц.

4️⃣ нашла на просторах linkedin пост про параллелизм и классный пост, как не путать ошибки первого и второго рода. Кратко: Когда мальчик закричал «волк!» – жители поверили ему, хотя волка не было. Следовательно, false positive – Type I error. После этого, жители больше не верили мальчику, даже когда волк на самом деле пришел в деревню, false negative - Type II error.

Читать полностью…

grokaem себя

ЭМБЕДДИНГИ GENSIM

Серия постов про эмбеддинги!

#1 Боль дообучения через gensim

Чаще всего я использую эмбеддинги от берта, но иногда приходится юзать и word2vec, fasttext. Самая удобная библиотека для этого - gensim. Но они к сожалению (очень большому) не сделали функционал по fine-tuninгу эмбеддингов.

🐝 Почему жалко? 🐝
1. Когда у вас маленький набор уникальных текстов и в нем нет более обыденных слов, которые есть в предобученных моделях, вы хотите просто 'добавить новые слова' и не 'терять эмбеддинги простых слов'
2. Когда у вас постоянно поступают новые тексты. Обучил в прошлом году, появились новые слова - завафайнтюнил, прошла еще неделя - еще зафайнтюнил.
3. Ну не прикольно руками код библиотек разбирать, ю ноу.

Как сделать?
- обучаем сначала на новом датасете
- загружаем старые эмбеддинги
- делаем .append_vectors()
- gensim напортачили с функционалом и через append vectors не обновится vectors vocab, поэтому после того, как добавили обновляем vectors_vocab

если есть повторы, то:
а) делаем replace, если вам кажется, что старые вектора лучше или без replace, если новые нравятся больше
б) хочется и то, и то словить - можно усреднять вектор старый и новый, честно я так не делала, потому что мне нужны были именно новые вектора

Вариант б мне не очень нравится, так что если у вас есть более крутой - велком в комментарии (да, я случайно удалила канал с комментами, но вроде бы сейчас все должно снова работать))

#nlp #deep_learning #эмбеддинги
#grokaem_nlp

Читать полностью…

grokaem себя

#grokaem_seby_thoughts
I was lucky this year to participate in IEEE SAMI 2023 with my work on dementia classification using audio data. 🎉 This research is very special for me as I hold the topic close to my heart but it was also very important for developing my skills. Here are some things I've learnt, you can read my story in comments in russian. ⬇️

1. Keep an eye whether speakers that appear in training data are also present in validation data. They may say different things in different conditions, but it's a high bias!
2. If you have data and make your analysis on your private computer - buy a portable disk.
3. If you don't have access to high-level computing resources have a few accounts in kaggle. Prepare dataset there and update it.
4. Define baseline metrics before you do your analysis! It's easy, but all of the requirements should be the same.
5. Be very strict to yourself. If you get high metric, ask why. Maybe it was a mistake. 🤓
6. Don't trust autosaving if you have long experiments.
7. Save models with wandb and their version checking, it's very helpful.
8. Don't use librosa, move to torchaudio.
9. Visualise your spectrograms at every step.
10. Save audio samples and spectrograms too as pt .
11. Keep versions of code, models and data as long as you can. Maybe later it can be helpful.
12. Don't doubt in yourself. Turn off this impostor syndrome. You can.

Читать полностью…

grokaem себя

ЕЩЕ ТЕНЗОРЫ

I've written a post about it 2 years ago.... But there I've discussed only cat 🐈
Let's discuss stack and repeat.

🦩🦩🦩STACK 🦩🦩🦩
Not much to tell about stack - concatenate tensors on a new dimension.
For instance:
t1 = torch.tensor([[1, 2],
[3, 4],
[5, 6],]) # shape [3, 2]
t2 = torch.tensor([[7, 8],
[9, 10],
[11, 12],]) # shape [3, 2]
t = torch.stack((t1, t2))
t: tensor(
[[[ 1, 2],
[ 3, 4],
[ 5, 6]],
[[ 7, 8],
[ 9, 10],
[11, 12]]])
# shape [2, 3, 2]

So our new tensor is just a sequence or a stack of two tensors (with the same shape!)

But if we concatenate tensors, we need to specify the dimension we use for this. Something like:
t = torch.cat((t1, t2), dim=0) # shape [6, 2]
t: tensor([[ 1, 2],
[ 3, 4],
[ 5, 6],
[ 7, 8],
[ 9, 10],
[11, 12]])

Use case from my experience:
- torch.stack - in collate function stack tokenized texts.
- torch.cat - in padding mode concatenate 0 sequences with existing examples.


🦩🦩🦩REPEAT🦩🦩🦩
This function helps to repeat a tensor across dimensions.
t = t1.repeat(2, 4)
t: tensor([[1, 2, 1, 2, 1, 2, 1, 2],
[3, 4, 3, 4, 3, 4, 3, 4],
[5, 6, 5, 6, 5, 6, 5, 6],
[1, 2, 1, 2, 1, 2, 1, 2],
[3, 4, 3, 4, 3, 4, 3, 4],
[5, 6, 5, 6, 5, 6, 5, 6]]) # shape [6, 8]

Use case from my experience:
- repeate embedding of one sentence to compare it with others. I used
.unsqueeze(1).repeat(1, K, 1) to repeat it only on the second dimension

#pytorch #deep_learning
#grokaem_programming

Читать полностью…

grokaem себя

Happy New Year! Hope the next year will bring us peace and happiness.

Читать полностью…

grokaem себя

#nlp #deep_learning
#grokaem_random

Random things I encountered, that either impressed me or saved my time.

1. VS code - command palete - sort imports. I hate sorting imports, this thing does it.
2. hugging face Dataset is awesome really. Makes it easy to load pandas/txt data, map it to tokenizer or other functions in parallel.
3. Pytorch Lightning is pretty with its colorful and informative RichProgressBar p.s. it has other cool features too about lr finding, batch capacity and parallel training on gpu.
4. Overview of GPUs and how to choose one.
5. Few-shot training with attention. Maybe I will write a post about it, but the idea is really cool considering the problem of interpretable ai.

Читать полностью…

grokaem себя

Привет, я тут одну штуку придумала странную) Мб вы слушаете русскую альтернативу или инди, напишите в комментах или мне в лс ваши любимые группы, пожалуйста 🎧 Молодые авторы приветствуются

Читать полностью…

grokaem себя

PROFANITY WORDS

#nlp #profanity
#grokaem_nlp

*this post contains profanity words*

As NLP developer I work with one of the dirtiest and at the exact same time magnificent types of data - TEXTS. From my experience, it's much more difficult to work with Russian texts since Russian is more flexible.

🦥 sloth and mistypes🦥
The dirty has a variety of forms. The basic example is a mistype.
Some of the solutions are described by deeppavlov.
"Дорон утро, спокойного и прятного днявам" (my friend does not like T9, so I always guess the meaning of her messages, Polina hi :)
- прятного would be corrected to приятного, but other words would not be corrected with pyspellchecker
- днявам would also be changed by Yandex SpellChecker
Sadly no solutions could understand дорон(could you?), I have not checked bert for this, but it's meant to help.

🦥sloth and mat🦥
Getting back to the Mat [Russian profanity], I consider it as one of the great sophisticated inventions of the Russian people. I recommend to watch this video if you have some prejudice about it.

I decided to detect profanity in one of the projects. The first and the last library you gonna find for this is profanity-filter.

Why should you not use it? (I've spent around two days and n amount of profanity words to deal with all these problems)
1. You're gonna use it with spacy>3.0 as russian was introduced in this version. But sadly the library does not support spacy>3.0 and its functionality. It's possible to change some of the functions and it will work. (I did it)
2. The main idea is just check a word in the list of profanity words which are suggested in doc.
3. It does not deal with mistypes or long vowels. For instance, бл**яя is not gonna be detected.
4. The code is not readable in my point of view, so you're gonna struggle with it...

🦥mat and my experience🦥
1. Make transformations of mistypes in the word.
2. Delete long vowels.
3. Detect additional profanity words and add them in the list, for instance I added кон**нный and п**дец to the dictionary.
4. Check 'not in list' but 'in string' therefore some parts are gonna be counted. You can use stemming, but it didn't bring a lot of profit for my case.
After all this process I was able to detect from нвхуй на**й. I was really happy.


If you know some solutions to detect profanity, please write in the comments :)

Читать полностью…

grokaem себя

FOCAL LOSS

Focal loss is a loss function for binary, multilabel and multiclass classification. Why do we need another function if we have
cross and binary entropy?

Cross-entropy links (there are a lot):
the best one can skip others if you want
neat math + kl divergence
dummy and informative example
does really concern only positive samples
more math + code

🦔🦔hedgehogs to split info🦔🦔
Cross and binary entropy both suffer from two main problems:
0️⃣class imbalance
Check the example here. Even when we predict one very frequent sample nearly perfectly it still contributes much more than the minority bad classified sample. One of the solutions - is weighted cross-entropy where we simply penalize frequent classes with low weight and rare ones with higher weight (example here)
1️⃣ hard and easy examples
Hard examples are the ones that were given low probability and easy ones are given high probability. If our model has already learnt one class with 0.85 probability and does not know another one with 0.001 probability we should focus on predicting the second one. It is suggested to be done with gamma parameter which makes the contribution of hard examples higher and the effect of easy ones lower. Therefore easy examples get more updates in weights and are learnt better. It can be seen in the graph ⬇️ as when the probability is high the loss is nearly 0, it can be controlled by gamma parameter. The higher it is, the more regularization is introduced.
🦔🦔hedgehogs to make conclusion🦔🦔

So, one should make experiments with focal loss in case of the imbalanced dataset and easy/hard examples in it.
explanation of focal loss
another one

#loss #deep_learning #math #neural_networks
#grokaem_dl

Читать полностью…
Subscribe to a channel