The post has been translated automatically. Original language: Russian
It's time to get acquainted with "hello, world!" in the world of Machine Learning.
scikit-learn is one of the most popular libraries for building predictive models.:
import sklearn
As written in the documentation: sklearn built on NumPy, SciPy, and matplotlib. And we have already met them in parts 1, 3 and 5 of our series of publications about preparing for work in Data Science.
The canonical example for "hello, world!" is often the training datasets of iris and titanic. The first one became popular due to one of the first UCI open dataset archives developed at one of the universities of California (hence the abbreviation UCI — University of California, Irvine). The second one is due to the available educational competitions on the Kaggle platform.
In the Practical Machine Learning Course, we begin our acquaintance with models with the metric kNN (k nearest neighbors) algorithm and the intuitive compactness hypothesis: similar objects more often belong to the same class than to different ones (boys look like boys, and girls look like girls). For example, handwritten numbers from the MNIST dataset, represented in a two-dimensional space, will be clustered (clustered) into 10 classes.

We suggest selecting the dataset you are interested in, uploading data in the format of a feature description of objects (train matrix) and their markup (labels vector). First of all, conduct an exploratory data analysis: calculate and visualize the characteristics of your data, check the completeness of the filling, and discuss with your mentor the necessary data preprocessing and cleaning. If there is no such senior partner at hand, then at first some GPT will do.
Next, we take our kNN from the sklearn library.:
from sklearn.neighbors import KNeighborsClassifier
knn = KNeighborsClassifier(n_neighbors=1)
Training our model:
knn.fit(train, labels)
And we check the quality of the prediction using the accuracy metric (don't even try to read 100,500 articles about accuracy, precision, recall and F1, almost everyone explains it too mathematically; in short, accuracy is the number (or percentage) of correctly predicted objects):
from sklearn.metrics import accuracy_score
accuracy_score(labels, knn.predict(train))
That's all, it may seem — fit-predict and 300k per second in your pocket. In reality, you will still need to study and understand:
1. What are the families of algorithms, what are their pros and cons, and what are their limitations on applicability?;
2. Why does the code above give almost 100% quality on any dataset, but in reality it works much worse;
3. What kind of quality metrics are there, for what and why. How do they count and what kind of intuition is behind them?;
4. What is quality assessment and what is the mathematics behind cross-validation?;
5. What is good and what is bad (in the ML world). And a lot of other things, which will take more than one month of immersion.
We offer to praise ourselves for the work done, for getting acquainted with the abundance of useful libraries, for the first trained machine learning model, and, possibly, for the first submit to Kaggle.;
, Easter egg
The Turing Award is an analog of the Nobel Prize in Computer Science. The award winners receive recognition and a fee of $ 1 million.
Which dataset author of the above has received the Turing Award?
Useful information
Read first: Part 1 introduction to ML and ML libraries for Python
Previous issue: Part 5 optimization of ML algorithms
BigData Team: the way you learn best
Самое время познакомиться с "hello, world!" в мире Machine Learning.
scikit-learn является одной из самых популярных библиотек для построения предсказательных моделей:
import sklearn
Как написано в документации: sklearn built on NumPy, SciPy, and matplotlib. А с ними мы уже познакомились в частях 1, 3 и 5 нашей серии публикаций про подготовку к работе в Data Science.
Каноническим примером для "hello, world!" часто служат тренировочные датасеты iris и titanic. Первый стал популярен благодаря одному из первых архивов открытых датасетов UCI, разработанному в одном из университетов Калифорнии (отсюда и сокращение UCI — University of California, Irvine). Второй — благодаря доступным учебным соревнованиям на платформе Kaggle.
На Практическом курсе по Machine Learning мы начинаем знакомство с моделями с метрического алгоритма kNN (k ближайших соседей) и интуитивно понятной гипотезы компактности: похожие объекты чаще принадлежат одному классу, чем разным (мальчики похожи на мальчиков, а девочки на девочек). Например, рукописные цифры из датасета MNIST, представленные в двумерном пространстве, будут кластеризоваться (кучковаться) на 10 классов.

Предлагаем выбрать интересующий вас датасет, загрузить данные в формате признакового описания объектов (матрица train) и их разметки (вектор labels). В первую очередь проведите разведочный анализ данных: посчитайте и визуализируйте характеристики ваших данных, проверьте полноту заполнения и обсудите с вашим наставником необходимую предобработку и очистку данных. Если такого старшего товарища под рукой нет, то на первых порах подойдет какой-нибудь GPT.
Далее берем наш kNN из библиотеки sklearn:
from sklearn.neighbors import KNeighborsClassifier
knn = KNeighborsClassifier(n_neighbors=1)
Обучаем нашу модель:
knn.fit(train, labels)
И проверяем качество предсказания по метрике accuracy (даже и не пытайтесь прочитать 100500 статей про accuracy, precison, recall и F1, почти все объясняют это слишком математизированно; коротко, accuracy — количество (или процент) правильно предсказанных объектов):
from sklearn.metrics import accuracy_score
accuracy_score(labels, knn.predict(train))
Вот и всё, может показаться — fit-predict и 300k в секунду у вас кармане. В реальности вам еще нужно будет изучить и понять:
1. Какие семейства алгоритмов бывают, в чем их плюсы, минусы и какие у них ограничения применимости;
2. Почему код выше даёт практически 100% качество на любых датасетах, но в реальности работает гораздо хуже;
3. Какие метрики качества бывают, для чего и почему. Как они считаются и какая за ними стоит интуиция;
4. Что такое оценка качества и какая математика стоит за кросс-валидацией;
5. Что такое хорошо и что такое плохо (в мире ML). И много чего другого, на что уйдет не один месяц погружения.
Предлагаем похвалить себя за проделанную работу, за знакомство с обилием полезных библиотек, за первую обученную модель машинного обучения, и, возможно, за первый submit в Kaggle;
🎁 Пасхалка
Премия Тьюринга - аналог нобелевской премии в сфере Computer Science. Лауреаты премии получают признание и гонорар в размере 1 миллиона долларов.
Автор какого датасета из вышеупомянутых получил премию Тьюринга?
Полезная информация
Читать сначала: ч.1 введение в ML и библиотеки ML для Python
Предыдущий выпуск: ч.5 оптимизация ML алгоритмов
BigData Team: the way you learn best