Snap

Содержание:

Methods Unified by SHAP

  1. LIME: Ribeiro, Marco Tulio, Sameer Singh, and Carlos Guestrin. «Why should i trust you?: Explaining the predictions of any classifier.» Proceedings of the 22nd ACM SIGKDD International Conference on Knowledge Discovery and Data Mining. ACM, 2016.

  2. Shapley sampling values: Strumbelj, Erik, and Igor Kononenko. «Explaining prediction models and individual predictions with feature contributions.» Knowledge and information systems 41.3 (2014): 647-665.

  3. DeepLIFT: Shrikumar, Avanti, Peyton Greenside, and Anshul Kundaje. «Learning important features through propagating activation differences.» arXiv preprint arXiv:1704.02685 (2017).

  4. QII: Datta, Anupam, Shayak Sen, and Yair Zick. «Algorithmic transparency via quantitative input influence: Theory and experiments with learning systems.» Security and Privacy (SP), 2016 IEEE Symposium on. IEEE, 2016.

  5. Layer-wise relevance propagation: Bach, Sebastian, et al. «On pixel-wise explanations for non-linear classifier decisions by layer-wise relevance propagation.» PloS one 10.7 (2015): e0130140.

  6. Shapley regression values: Lipovetsky, Stan, and Michael Conklin. «Analysis of regression in game theory approach.» Applied Stochastic Models in Business and Industry 17.4 (2001): 319-330.

Methods Unified by SHAP

  1. LIME: Ribeiro, Marco Tulio, Sameer Singh, and Carlos Guestrin. «Why should i trust you?: Explaining the predictions of any classifier.» Proceedings of the 22nd ACM SIGKDD International Conference on Knowledge Discovery and Data Mining. ACM, 2016.

  2. Shapley sampling values: Strumbelj, Erik, and Igor Kononenko. «Explaining prediction models and individual predictions with feature contributions.» Knowledge and information systems 41.3 (2014): 647-665.

  3. DeepLIFT: Shrikumar, Avanti, Peyton Greenside, and Anshul Kundaje. «Learning important features through propagating activation differences.» arXiv preprint arXiv:1704.02685 (2017).

  4. QII: Datta, Anupam, Shayak Sen, and Yair Zick. «Algorithmic transparency via quantitative input influence: Theory and experiments with learning systems.» Security and Privacy (SP), 2016 IEEE Symposium on. IEEE, 2016.

  5. Layer-wise relevance propagation: Bach, Sebastian, et al. «On pixel-wise explanations for non-linear classifier decisions by layer-wise relevance propagation.» PloS one 10.7 (2015): e0130140.

  6. Shapley regression values: Lipovetsky, Stan, and Michael Conklin. «Analysis of regression in game theory approach.» Applied Stochastic Models in Business and Industry 17.4 (2001): 319-330.

Model agnostic example with KernelExplainer (explains any function)

Kernel SHAP uses a specially-weighted local linear regression to estimate SHAP values for any model. Below is a simple example for explaining a multi-class SVM on the classic iris dataset.

import sklearn
import shap
from sklearn.model_selection import train_test_split

# print the JS visualization code to the notebook
shap.initjs()

# train a SVM classifier
X_train,X_test,Y_train,Y_test = train_test_split(*shap.datasets.iris(), test_size=0.2, random_state=)
svm = sklearn.svm.SVC(kernel='rbf', probability=True)
svm.fit(X_train, Y_train)

# use Kernel SHAP to explain test set predictions
explainer = shap.KernelExplainer(svm.predict_proba, X_train, link="logit")
shap_values = explainer.shap_values(X_test, nsamples=100)

# plot the SHAP values for the Setosa output of the first instance
shap.force_plot(explainer.expected_value[], shap_values[], X_test.iloc, link="logit")

The above explanation shows four features each contributing to push the model output from the base value (the average model output over the training dataset we passed) towards zero. If there were any features pushing the class label higher they would be shown in red.

If we take many explanations such as the one shown above, rotate them 90 degrees, and then stack them horizontally, we can see explanations for an entire dataset. This is exactly what we do below for all the examples in the iris test set:

# plot the SHAP values for the Setosa output of all instances
shap.force_plot(explainer.expected_value[], shap_values[], X_test, link="logit")

Snapchat — что это

Сначала разберемся, что это – приложение Snapchat. Это интересный современный мессенджер, предназначенный для общения между пользователями. Ключевыми особенностями программы можно считать:

  • Уничтожение роликов после просмотра;
  • Отсутствие автоматического сохранения сделанных фото;
  • Отсутствие интеграции с другими сервисами, а также списком контактов;
  • Нет лайков и комментариев, не поддерживаются подписчики;
  • Фото и видео могут быть только вертикальными.

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

  • Андроид;
  • iOs.

Tree ensemble example with TreeExplainer (XGBoost/LightGBM/CatBoost/scikit-learn/pyspark models)

import xgboost
import shap

# load JS visualization code to notebook
shap.initjs()

# train XGBoost model
X,y = shap.datasets.boston()
model = xgboost.train({"learning_rate": 0.01}, xgboost.DMatrix(X, label=y), 100)

# explain the model's predictions using SHAP
# (same syntax works for LightGBM, CatBoost, scikit-learn and spark models)
explainer = shap.TreeExplainer(model)
shap_values = explainer.shap_values(X)

# visualize the first prediction's explanation (use matplotlib=True to avoid Javascript)
shap.force_plot(explainer.expected_value, shap_values, X.iloc)

If we take many explanations such as the one shown above, rotate them 90 degrees, and then stack them horizontally, we can see explanations for an entire dataset (in the notebook this plot is interactive):

# visualize the training set predictions
shap.force_plot(explainer.expected_value, shap_values, X)

To understand how a single feature effects the output of the model we can plot the SHAP value of that feature vs. the value of the feature for all the examples in a dataset. Since SHAP values represent a feature’s responsibility for a change in the model output, the plot below represents the change in predicted house price as RM (the average number of rooms per house in an area) changes. Vertical dispersion at a single value of RM represents interaction effects with other features. To help reveal these interactions automatically selects another feature for coloring. In this case coloring by RAD (index of accessibility to radial highways) highlights that the average number of rooms per house has less impact on home price for areas with a high RAD value.

# create a dependence plot to show the effect of a single feature across the whole dataset
shap.dependence_plot("RM", shap_values, X)

To get an overview of which features are most important for a model we can plot the SHAP values of every feature for every sample. The plot below sorts features by the sum of SHAP value magnitudes over all samples, and uses SHAP values to show the distribution of the impacts each feature has on the model output. The color represents the feature value (red high, blue low). This reveals for example that a high LSTAT (% lower status of the population) lowers the predicted home price.

# summarize the effects of all the features
shap.summary_plot(shap_values, X)

We can also just take the mean absolute value of the SHAP values for each feature to get a standard bar plot (produces stacked bars for multi-class outputs):

shap.summary_plot(shap_values, X, plot_type="bar")

Подборки

Армейские ПесниКлассика пианиноМузыка из рекламыДетские песни из мультфильмовМузыка для аэробикиСборник песен 70х годовДля любимого человекаКлассика в современной обработкеКлубные миксы русских исполнителей3D ЗвукДальнобойщикиЗарубежный рэп для машиныТоповые Клубные ТрекиМощные БасыДискотека 2000Песни про папуХристианские ПесниЗимняя МузыкаМузыка Для МедитацииРусские Хиты 90ХГрустная МузыкаRomantic SaxophoneТанцевальный хип-хопНовогодние песниЗарубежные хиты 80 — 90Песни про покемонаРомантическая МузыкаМотивация для тренировокМузыка для сексаМузыка в машинуДля силовых тренировокПремия «Grammy 2017»

Branches & Forks

This is the CefSharp fork, as maintained by the CefSharp community. You can also view the entire network of public forks/branches.

Development is done in the branch. New features are preferably added in feature branches, if the changes are more than trivial. New should be targeted against .

When a new release is imminent a branch is created. We try to avoid making public facing changes in branches (Adding new features is fine, just not breaking changes).

CI Builds
Every commit on produces a package. Use at your own risk!

Pre-release

Stable

Release Branches

With each release a new branch is created, for example the release corresponds to the branch.
If you’re new to and are downloading the source to check it out, please use a Release branch

Branch CEF Version VC++ Version .Net Version Status
master 4147 2015 4.5.2 Development
cefsharp/84 4147 2015 4.5.2 Release
cefsharp/83 4103 2015 4.5.2 Unsupported
cefsharp/81 4044 2015 4.5.2 Unsupported
cefsharp/79 3945 2015 4.5.2 Unsupported
cefsharp/77 3865 2015 4.5.2 Unsupported
cefsharp/75 3770 2015 4.5.2 Unsupported
cefsharp/73 3683 2015 4.5.2 Unsupported
cefsharp/71 3578 2015 4.5.2 Unsupported
cefsharp/69 3497 2015 4.5.2 Unsupported
cefsharp/67 3396 2015 4.5.2 Unsupported
cefsharp/65 3325 2015 4.5.2 Unsupported
cefsharp/63 3239 2013 4.5.2 Unsupported
cefsharp/62 3202 2013 4.5.2 Unsupported
cefsharp/57 2987 2013 4.5.2 Unsupported
cefsharp/55 2883 2013 4.5.2 Unsupported
cefsharp/53 2785 2013 4.5.2 Unsupported
cefsharp/51 2704 2013 4.5.2 Unsupported
cefsharp/49 2623 2013 4.0 Unsupported
cefsharp/47 2526 2013 4.0 Unsupported
cefsharp/45 2454 2013 4.0 Unsupported
cefsharp/43 2357 2012 4.0 Unsupported
cefsharp/41 2272 2012 4.0 Unsupported
cefsharp/39 2171 2012 4.0 Unsupported
cefsharp/37 2062 2012 4.0 Unsupported

Инструкция по использованию

Ура, мы начинаем использовать Снапчат! Сначала рассмотрим главный экран мессенджера и поговорим о подробностях использования.

Делаем снап:

  • Откройте приложение;
  • Кликните на кружок в центре нижней панели.

Но делать простой снап не хочется – давайте разнообразим его линзами!

  • Рядом с кнопкой съемки находится иконка смайлика – она позволяет открыть перечень  сохраненных линз;
  • Делайте свайп вправо-влево, чтобы перелистывать список линз;
  • Сделайте свайп вверх по экрану, чтобы открыть огромное количество линз, созданных пользователями и сообществами. Кликайте на понравившийся вариант, чтобы добавить его в личную ленту.

Слева вы увидите небольшую панель:

На нижней панели вы увидите кнопки «Друзья» и «Discover». Но об этом мы поговорим подробнее позже. Если вы всерьез задумались о том, как настроить Снапчат – обсудим особенности редактирования.

Вы уже сделали снап – пора рассмотреть подробные настройки на левой панели экрана, чтобы понять, для чего нужен Снапчат:

Буква «Т» позволяет вводить текст. Вы можете выбрать тип шрифта, цвет и размер;

Карандаш позволяет рисовать – определите размер кисти и цвет;

Иконка стикера дает доступ к множеству анимированных картинок, которые можно наклеивать на снэп;

  • Ножницы позволяют вырезать часть фотографии, чтобы сделать стикер;
  • С помощью скрепки можно добавить файл из интернета – достаточно ввести URL документа;
  • Делайте кадрирование фото, уменьшайте или увеличивайте масштаб;
  • Кнопка секундомера позволяет обозначить время трансляции снэпа – от одной до десяти секунд, или бесконечность.

В нижней части странички есть еще несколько иконок:

  • Добавьте фото или ролик в историю, чтобы друзья могли просматривать контент на протяжении 24 часов без ограничений;
  • Сохраните снэп в воспоминания или фотопленку;
  • Чтобы загрузить снап в ленту, кликайте на иконку в виде синей стрелки с подписью «Отправить».

Чтобы выбрать фильтр, листайте экран вправо-влево. Некоторые фильтры можно комбинировать!

Продолжаем изучать, как пользоваться приложением Snapchat – на очереди общение! Вы можете добавлять друзей следующим образом:

  • Нажмите на иконку человека на главном экране;
  • Сделайте свайп вправо или влево, затем нажмите на аналогичную иконку;
  • Выберите человека из списка рекомендаций или просто введите имя пользователя в поисковую строку.

Приложение Снэпчат предназначено для общения – пора поговорить о том, как переписываться с друзьями и знакомыми!

  • Кликните на иконку ярлычка в левом нижнем углу главной страницы;
  • Или сделайте свайп вправо, затем кликните на кнопку в виде ярлыка в правом верхнем углу;
  • Выберите адресата сообщения из перечня, затем кликните кнопку «Чат».

Рассмотрим нижнюю панель:

  • Вводите текст в специальное поле;
  • Нажмите на кнопку фотоаппарата, чтобы сделать снап;
  • Кликайте на микрофон, чтобы записать аудиосообщение;
  • Смайлик позволяет создать специальный стикер с вашим лицом;
  • Иконка в виде карт позволяет получить доступ к библиотеке сохраненных фото;
  • Значок ракеты – это доступ к совместным играм.

Рассмотрим верхнюю панель:

  • Трубка предназначена для голосовых вызовов;
  • Значок камеры нужен для записи видеоролика;
  • Кнопка в виде крестика предназначена для закрытия чата.

Tree ensemble example with TreeExplainer (XGBoost/LightGBM/CatBoost/scikit-learn models)

import xgboost
import shap

# load JS visualization code to notebook
shap.initjs()

# train XGBoost model
X,y = shap.datasets.boston()
model = xgboost.train({"learning_rate": 0.01}, xgboost.DMatrix(X, label=y), 100)

# explain the model's predictions using SHAP values
# (same syntax works for LightGBM, CatBoost, and scikit-learn models)
explainer = shap.TreeExplainer(model)
shap_values = explainer.shap_values(X)

# visualize the first prediction's explanation
shap.force_plot(explainer.expected_value, shap_values, X.iloc)

If we take many explanations such as the one shown above, rotate them 90 degrees, and then stack them horizontally, we can see explanations for an entire dataset (in the notebook this plot is interactive):

# visualize the training set predictions
shap.force_plot(explainer.expected_value, shap_values, X)

To understand how a single feature effects the output of the model we can plot the SHAP value of that feature vs. the value of the feature for all the examples in a dataset. Since SHAP values represent a feature’s responsibility for a change in the model output, the plot below represents the change in predicted house price as RM (the average number of rooms per house in an area) changes. Vertical dispersion at a single value of RM represents interaction effects with other features. To help reveal these interactions automatically selects another feature for coloring. In this case coloring by RAD (index of accessibility to radial highways) highlights that the average number of rooms per house has less impact on home price for areas with a high RAD value.

# create a SHAP dependence plot to show the effect of a single feature across the whole dataset
shap.dependence_plot("RM", shap_values, X)

To get an overview of which features are most important for a model we can plot the SHAP values of every feature for every sample. The plot below sorts features by the sum of SHAP value magnitudes over all samples, and uses SHAP values to show the distribution of the impacts each feature has on the model output. The color represents the feature value (red high, blue low). This reveals for example that a high LSTAT (% lower status of the population) lowers the predicted home price.

# summarize the effects of all the features
shap.summary_plot(shap_values, X)

We can also just take the mean absolute value of the SHAP values for each feature to get a standard bar plot (produces stacked bars for multi-class outputs):

shap.summary_plot(shap_values, X, plot_type="bar")

Deep learning example with DeepExplainer (TensorFlow/Keras models)

# ...include code from https://github.com/keras-team/keras/blob/master/examples/mnist_cnn.py

import shap
import numpy as np

# select a set of background examples to take an expectation over
background = x_train, 100, replace=False)]

# explain predictions of the model on four images
e = shap.DeepExplainer(model, background)
# ...or pass tensors directly
# e = shap.DeepExplainer((model.layers.input, model.layers.output), background)
shap_values = e.shap_values(x_test)

# plot the feature attributions
shap.image_plot(shap_values, -x_test)

The plot above explains ten outputs (digits 0-9) for four different images. Red pixels increase the model’s output while blue pixels decrease the output. The input images are shown on the left, and as nearly transparent grayscale backings behind each of the explanations. The sum of the SHAP values equals the difference between the expected model output (averaged over the background dataset) and the current model output. Note that for the ‘zero’ image the blank middle is important, while for the ‘four’ image the lack of a connection on top makes it a four instead of a nine.

Sample notebooks

The notebooks below demonstrate different use cases for SHAP. Look inside the notebooks directory of the repository if you want to try playing with the original notebooks yourself.

DeepExplainer

An implementation of Deep SHAP, a faster (but only approximate) algorithm to compute SHAP values for deep learning models that is based on connections between SHAP and the DeepLIFT algorithm.

MNIST Digit classification with Keras — Using the MNIST handwriting recognition dataset, this notebook trains a neural network with Keras and then explains predictions using shap.

GradientExplainer

An implementation of expected gradients to approximate SHAP values for deep learning models. It is based on connections between SHAP and the Integrated Gradients algorithm. GradientExplainer is slower than DeepExplainer and makes different approximation assumptions.

Explain an Intermediate Layer of VGG16 on ImageNet — This notebook demonstrates how to explain the output of a pre-trained VGG16 ImageNet model using an internal convolutional layer.

KernelExplainer

An implementation of Kernel SHAP, a model agnostic method to estimate SHAP values for any model. Because it makes not assumptions about the model type, KernelExplainer is slower than the other model type specific algorithms.

Deep learning example with DeepExplainer (TensorFlow/Keras models)

# ...include code from https://github.com/keras-team/keras/blob/master/examples/mnist_cnn.py

import shap
import numpy as np

# select a set of background examples to take an expectation over
background = x_train, 100, replace=False)]

# explain predictions of the model on four images
e = shap.DeepExplainer(model, background)
# ...or pass tensors directly
# e = shap.DeepExplainer((model.layers.input, model.layers.output), background)
shap_values = e.shap_values(x_test)

# plot the feature attributions
shap.image_plot(shap_values, -x_test)

The plot above explains ten outputs (digits 0-9) for four different images. Red pixels increase the model’s output while blue pixels decrease the output. The input images are shown on the left, and as nearly transparent grayscale backings behind each of the explanations. The sum of the SHAP values equals the difference between the expected model output (averaged over the background dataset) and the current model output. Note that for the ‘zero’ image the blank middle is important, while for the ‘four’ image the lack of a connection on top makes it a four instead of a nine.

Sample notebooks

The notebooks below demonstrate different use cases for SHAP. Look inside the notebooks directory of the repository if you want to try playing with the original notebooks yourself.

DeepExplainer

An implementation of Deep SHAP, a faster (but only approximate) algorithm to compute SHAP values for deep learning models that is based on connections between SHAP and the DeepLIFT algorithm.

GradientExplainer

An implementation of expected gradients to approximate SHAP values for deep learning models. It is based on connections between SHAP and the Integrated Gradients algorithm. GradientExplainer is slower than DeepExplainer and makes different approximation assumptions.

Explain an Intermediate Layer of VGG16 on ImageNet — This notebook demonstrates how to explain the output of a pre-trained VGG16 ImageNet model using an internal convolutional layer.

LinearExplainer

For a linear model with independent features we can analytically compute the exact SHAP values. We can also account for feature correlation if we are willing to estimate the feature covaraince matrix. LinearExplainer supports both of these options.

Sentiment Analysis with Logistic Regression — This notebook demonstrates how to explain a linear logistic regression sentiment analysis model.

KernelExplainer

An implementation of Kernel SHAP, a model agnostic method to estimate SHAP values for any model. Because it makes not assumptions about the model type, KernelExplainer is slower than the other model type specific algorithms.

Настройки профиля

Последняя часть инструкции о том, как пользоваться Снэпчат, расскажет вам о настройках профиля. Чтобы их открыть, кликайте на аватар в левом верхнем уголке:

  • Здесь можно добавить битмоджи;
  • Посмотреть трофеи;
  • Поделиться данными с другими пользователями;
  • Добавить друзей;
  • Включить или отключить уведомления;
  • Добавить историю.

Кликайте на значок шестеренки в верхнем правом углу и открывайте настройки:

  • Поменяйте имя профиля;
  • Измените ник, который отображается в ленте;
  • Выберите день рождения;
  • Откорректируйте номер телефона и адрес электронной почты;
  • Откройте редактор аватаров битмоджи;
  • Создайте и редактируйте собственный снапкаод;
  • Поменяйте заданный пароль;
  • Включите двухфакторную авторизацию;
  • Поиграйте с настройками уведомлений;
  • Установите резервное копирование, выберите место сохранения снэпов и включите «Ретроспективу» (демонстрация старых снапов);
  • Изучите настройки приватности – получение сообщений, просмотр историй и местоположения;
  • Обращение в поддержку, центр помощи и безопасности;
  • Удаление чатов, очистка кэша;
  • Выход из профиля.

В вопросе, как пользоваться Снапчатом на Андроиде и на iPhone нет ничего сложного – справится даже новичок.

Саундтреки

Из фильма В центре вниманияИз фильма Ван ХельсингИз сериала Дневники ВампираИз фильма Скауты против зомбииз фильмов ‘Миссия невыполнима’Из фильма Голодные игры: Сойка-пересмешница. Часть 2OST ‘Свет в океане’OST «Большой и добрый великан»из фильма ‘Новогодний корпоратив’из фильма ‘Список Шиндлера’ OST ‘Перевозчик’Из фильма Книга джунглейиз сериала ‘Метод’Из фильма ТелохранительИз сериала Изменыиз фильма Мистериум. Тьма в бутылкеиз фильма ‘Пассажиры’из фильма ТишинаИз сериала Кухня. 6 сезониз фильма ‘Расплата’ Из фильма Человек-муравейиз фильма ПриглашениеИз фильма Бегущий в лабиринте 2из фильма ‘Молот’из фильма ‘Инкарнация’Из фильма Савва. Сердце воинаИз сериала Легко ли быть молодымиз сериала ‘Ольга’Из сериала Хроники ШаннарыИз фильма Самый лучший деньИз фильма Соседи. На тропе войныМузыка из сериала «Остров»Из фильма ЙоганутыеИз фильма ПреступникИз сериала СверхестественноеИз сериала Сладкая жизньИз фильма Голограмма для короляИз фильма Первый мститель: ПротивостояниеИз фильма КостиИз фильма Любовь не по размеруOST ‘Глубоководный горизонт’Из фильма Перепискаиз фильма ‘Призрачная красота’Место встречи изменить нельзяOST «Гений»из фильма ‘Красотка’Из фильма Алиса в ЗазеркальеИз фильма 1+1 (Неприкасаемые)Из фильма До встречи с тобойиз фильма ‘Скрытые фигуры’из фильма Призывиз сериала ‘Мир Дикого Запада’из игр серии ‘Bioshock’ Музыка из аниме «Темный дворецкий»из фильма ‘Американская пастораль’Из фильма Тарзан. ЛегендаИз фильма Красавица и чудовище ‘Искусственный интеллект. Доступ неограничен»Люди в черном 3’из фильма ‘Планетариум’Из фильма ПрогулкаИз сериала ЧужестранкаИз сериала Элементарноиз сериала ‘Обратная сторона Луны’Из фильма ВаркрафтИз фильма Громче, чем бомбыиз мультфильма ‘Зверопой’Из фильма БруклинИз фильма Игра на понижениеИз фильма Зачарованнаяиз фильма РазрушениеOST «Полный расколбас»OST «Свободный штат Джонса»OST И гаснет светИз сериала СолдатыИз сериала Крыша мираИз фильма Неоновый демонИз фильма Москва никогда не спитИз фильма Джейн берет ружьеИз фильма Стражи галактикииз фильма ‘Sos, дед мороз или все сбудется’OST ‘Дом странных детей Мисс Перегрин’Из игры Contact WarsИз Фильма АмелиИз фильма Иллюзия обмана 2OST Ледниковый период 5: Столкновение неизбежноИз фильма Из тьмыИз фильма Колония Дигнидадиз фильма ‘Страна чудес’Музыка из сериала ‘Цвет черёмухи’Из фильма Образцовый самец 2из фильмов про Гарри Поттера Из фильма Дивергент, глава 3: За стеной из мультфильма ‘Монстр в Париже’из мультфильма ‘Аисты’Из фильма КоробкаИз фильма СомнияИз сериала Ходячие мертвецыИз фильма ВыборИз сериала Королек — птичка певчаяДень независимости 2: ВозрождениеИз сериала Великолепный векиз фильма ‘Полтора шпиона’из фильма Светская жизньИз сериала Острые козырьки

Model agnostic example with KernelExplainer (explains any function)

Kernel SHAP uses a specially-weighted local linear regression to estimate SHAP values for any model. Below is a simple example for explaining a multi-class SVM on the classic iris dataset.

import sklearn
import shap
from sklearn.model_selection import train_test_split

# print the JS visualization code to the notebook
shap.initjs()

# train a SVM classifier
X_train,X_test,Y_train,Y_test = train_test_split(*shap.datasets.iris(), test_size=0.2, random_state=)
svm = sklearn.svm.SVC(kernel='rbf', probability=True)
svm.fit(X_train, Y_train)

# use Kernel SHAP to explain test set predictions
explainer = shap.KernelExplainer(svm.predict_proba, X_train, link="logit")
shap_values = explainer.shap_values(X_test, nsamples=100)

# plot the SHAP values for the Setosa output of the first instance
shap.force_plot(explainer.expected_value[], shap_values[], X_test.iloc, link="logit")

The above explanation shows four features each contributing to push the model output from the base value (the average model output over the training dataset we passed) towards zero. If there were any features pushing the class label higher they would be shown in red.

If we take many explanations such as the one shown above, rotate them 90 degrees, and then stack them horizontally, we can see explanations for an entire dataset. This is exactly what we do below for all the examples in the iris test set:

# plot the SHAP values for the Setosa output of all instances
shap.force_plot(explainer.expected_value[], shap_values[], X_test, link="logit")

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *