power bi машинное обучение
Руководство по Интеграция Power BI. Создание прогнозной модели с помощью Jupyter Notebook (часть 1 из 2)
В первой части этого руководства показано, как обучить и развернуть прогнозную модель машинного обучения с помощью кода в записной книжке Jupyter Notebook. Вы также создадите скрипт оценки, чтобы определить входную и выходную схему модели для интеграции в Power BI. Во второй части показано, как использовать модель для прогнозирования результатов в Microsoft Power BI.
Изучив это руководство, вы:
Есть три способа создания и развертывания модели, которая будет использоваться в Power BI. В этой статье рассматривается вариант А — обучение и развертывание моделей с помощью записных книжек. Этот вариант предусматривает использование подхода Code First и записных книжек Jupyter Notebook, размещенных в Студии машинного обучения Azure.
Но вместо него можно использовать один из следующих вариантов:
Предварительные требования
Создание записной книжки и вычислительного экземпляра
На домашней странице Студии машинного обучения Azure выберите Создать > Записная книжка:
На странице Создание файла сделайте следующее:
Затем для выполнения ячеек кода создайте вычислительный экземпляр и подключите его к записной книжке. Для этого щелкните значок плюса в верхней части записной книжки:
На странице Создание вычислительного экземпляра сделайте следующее:
В записной книжке вы можете заметить, что кружок рядом с надписью Вычисление сменил цвет на голубой. Это указывает, что создается вычислительный экземпляр:
Подготовка вычислительного экземпляра занимает от 2 до 4 минут.
После подготовки вычислительного экземпляра вы можете использовать записную книжку для выполнения ячеек кода. Например, в ячейке можно ввести следующий код:
Затем нажмите клавиши SHIFT+ВВОД (или CTRL+ВВОД либо нажмите кнопку Воспроизвести рядом с ячейкой). Вы должны увидеть следующий результат:
Теперь можно создать модель машинного обучения.
Создание модели с помощью scikit-learn
В этом руководстве используется набор данных Diabetes. Этот набор данных доступен в Открытых наборах данных Azure.
Импорт данных
Чтобы импортировать данные, скопируйте и вставьте следующий код в новую ячейку кода в записной книжке.
Кадр данных Pandas X_df содержит 10 базовых входных переменных. Эти переменные описывают возраст, пол, индекс массы тела, среднее кровяное давление и шесть показателей сыворотки крови. Кадр данных Pandas y_df является целевой переменной. Она содержит количественный показатель развития болезни за год в сравнении с исходным значением. Кадр данных содержит 442 записи.
Обучение модели
Создайте новую ячейку кода в записной книжке. Скопируйте следующий код и вставьте его в ячейку. Этот фрагмент кода создает модель гребневой регрессии и сериализует модель с помощью формата модуля pickle для Python.
Регистрация модели
Кроме содержимого файла модели, в зарегистрированной модели будут храниться метаданные. Метаданные включают описание модели, теги и сведения о платформе.
Метаданные полезны при управлении моделями в рабочей области и их развертывании. С помощью тегов, например, можно классифицировать модели и применять фильтры при составлении списка моделей в рабочей области. Кроме того, маркировка этой модели с использованием scikit-learn упростит развертывание в качестве веб-службы.
Скопируйте и вставьте следующий код в новую ячейку кода в записной книжке.
Вы также можете просмотреть модель в Студии машинного обучения Azure. В меню слева выберите Модели:
Определение скрипта оценки
При развертывании модели, которая должна быть интегрирована в Power BI, необходимо определить скрипт оценки Python и пользовательскую среду. Скрипт оценки содержит две функции:
Декораторы Python в приведенном ниже коде определяют схему входных и выходных данных, что важно для интеграции в Power BI.
Скопируйте и вставьте следующий код в новую ячейку кода в записной книжке. В следующем фрагменте кода содержится магическая команда, которая записывает код в файл с именем score.py.
Определение пользовательской среды
Затем определите среду для оценки модели. В среде определите пакеты Python, такие как Pandas и scikit-learn, которые требуются для скрипта оценки (score.py).
Чтобы определить среду, скопируйте и вставьте следующий код в новую ячейку кода в записной книжке.
Развертывание модели
Чтобы развернуть модель, скопируйте и вставьте следующий код в новую ячейку кода в записной книжке:
Развертывание службы занимает от 2 до 4 минут.
Если служба будет развернута успешно, отобразятся следующие выходные данные:
Вы также можете просмотреть службу в Студии машинного обучения Azure. В меню слева выберите Конечные точки:
Рекомендуется протестировать веб-службу, чтобы убедиться, что она работает должным образом. Чтобы вернуться в записную книжку, в Студии машинного обучения Azure в меню слева выберите Записные книжки. Затем скопируйте и вставьте следующий код в новую ячейку кода в записной книжке, чтобы протестировать службу.
Выходные данные должны выглядеть, как в следующей структуре JSON: <'predict': [[205.59], [68.84]]>.
Дальнейшие действия
Из этого руководства вы узнали, как создать и развернуть модель так, чтобы ее можно было использовать в Power BI. В следующей части показано, как использовать эту модель в отчете Power BI.
Creating Machine Learning models in Power BI
Power BI Dataflows offer a simple and powerful ETL tool that enables analysts to prepare data for further analytics. You invest significant effort in data cleansing and preparation, creating datasets that can be used across your organization. AutoML enables you to leverage your data prep effort for building machine learning models directly in Power BI.
With AutoML, the data science behind the creation of ML models is automated by Power BI, with guardrails to ensure model quality, and visibility to ensure you have full insight into the steps used to create your ML model.
AutoML also emphasizes Explainability — highlighting the key features among your inputs that most influence the predictions returned by your model. The full lifecycle for creation, hosting and deployment of the ML models is managed by Power BI, without any additional dependencies.
AutoML is available for dataflows in workspaces hosted on Power BI Premium and Embedded capacities. In this release, we are introducing support for ML models for Binary Predictions, Classifications and Regressions. Timeseries forecasting will also be available shortly.
Creating an AutoML model
To create your AutoML model, simply select the dataflow entity with the historical data and the field with the values you want to predict, and Power BI will suggest the types of ML models that can be built using that data. Next, Power BI analyzes the other available fields in the selected entity to suggest the input fields you can use to create your model. You can change or accept these suggestions, and just save your configuration.
Your machine learning model will automatically be trained upon the next refresh of your dataflow, automating the data science tasks of sampling, normalization, feature extraction, algorithm and hyperparameter selection, and validation.
AutoML model report
After training, an automatically generated Power BI report summarizes the performance of your ML model. It includes information about key influencers that the model uses to predict an outcome. The report is specific to each model type, explaining how the model can be applied.
A statistical summary page in the report includes the standard data science measures of performance for the model.
The report also includes a Training details page, that provides full visibility into the process used to create the model. It describes how each input field was transformed, as well as every iteration with the algorithm and parameter settings used to create your model.
Applying the ML model to your data
With just a couple of clicks, you can apply the model to incoming data, and Power BI keeps your predictions up-to-date whenever the dataflow is refreshed. It also includes an individualized explanation for each specific prediction score that the ML model produces.
Get started building your own ML models
AutoML is now available for preview in all public cloud regions where Power BI Premium and Embedded is available. You can follow this step-by-step tutorial to build your first machine learning model using AutoML in minutes!
You can also read about AutoML in Power BI to learn more. If you have any questions, you can reach me at @santoshc1. We’d love to hear your feedback on the experience, and ideas on how you’d like to use AutoML.
Tutorial: Build a Machine Learning model in Power BI
In this tutorial article, you use Automated Machine Learning to create and apply a binary prediction model in Power BI. The tutorial includes guidance for creating a Power BI dataflow, and using the entities defined in the dataflow to train and validate a machine learning model directly in Power BI. We then use that model for scoring new data to generate predictions.
First, you’ll create a Binary Prediction machine learning model, to predict the purchase intent of online shoppers based on a set of their online session attributes. A benchmark machine learning dataset is used for this exercise. Once a model is trained, Power BI will automatically generate a validation report explaining the model results. You can then review the validation report and apply the model to your data for scoring.
This tutorial consists of following steps:
Create a dataflow with the input data
The first part of this tutorial is to create a dataflow with input data. That process takes a few steps, as shown in the following sections, beginning with getting data.
Get data
The first step in creating a dataflow is to have your data sources ready. In our case, we use a machine learning dataset from a set of online sessions, some of which culminated in a purchase. The dataset contains a set of attributes about these sessions, which we’ll use for training our model.
You can download the dataset from the UC Irvine website. We also have this available, for the purpose of this tutorial, from the following link: online_shoppers_intention.csv.
Create the entities
To create the entities in your dataflow, sign into the Power BI service and navigate to a workspace on your capacity that has AI enabled.
If you don’t already have a workspace, you can create one by selecting Workspaces in the nav pane menu in the Power BI service, and select Create workspace at the bottom of the panel that appears. This opens a panel on the right to enter the workspace details. Enter a workspace name and select Advanced. Confirm that the workspace uses Dedicated Capacity using the radio button, and that it’s assigned to a capacity instance that has the AI preview turned on. Then select Save.
Once the workspace is created, you can select Skip in the bottom right of the Welcome screen, as shown in the following image.
Select the Create button at the top right of the workspace, and then select Dataflow.
Select Add new entities. This launches a Power Query editor in the browser.
Select Text/CSV File as a data source, shown in the following image.
In the Connect to a data source page that appears next, paste the following link to the online_shoppers_intention.csv into the File path or URL box, and then select Next.
The Power Query Editor shows a preview of the data from the CSV file. You can rename the query to a friendlier name by changing the value in the Name box found in the right pane. For example, you could change the Query name to Online Visitors.
Power Query automatically infers the type of columns. You can change the column type by clicking on the attribute type icon at the top of the column header. In this example, we change the type of the Revenue column to True/False.
Select the Save & close button to close Power Query Editor. Provide a name for the dataflow, and then select Save on the dialog, as shown in the following image.
Create and train a machine learning model
To add a machine learning model, Select the Apply ML model button in the Actions list for the base entity that contains your training data and label information, and then select Add a machine learning model.
The first step for creating our machine learning model is to identify the historical data including the outcome field that you want to predict. The model will be created by learning from this data.
In the case of the dataset we’re using, this is the Revenue field. Select Revenue as the ‘Outcome field’ value and then select Next.
Next, we must select the type of machine learning model to create. Power BI analyzes the values in the outcome field that you’ve identified and suggests the types of machine learning models that can be created to predict that field.
In this case since we’re predicting a binary outcome of whether a user will make a purchase or not, Binary Prediction is recommended. Since we are interested in predicting users who will make a purchase, select True as the Revenue outcome that you’re most interested in. Additionally, you can provide friendly labels for the outcomes to be used in the automatically generated report that will summarize the results of the model validation. Then select Next.
Next, Power BI does a preliminary scan of a sample of your data and suggests the inputs that may produce more accurate predictions. If Power BI doesn’t recommend a field, an explanation would be provided next to it. You have the option to change the selections to include only the fields you want the model to study, or you can select all the fields by selecting the checkbox next to the entity name. Select Next to accept the inputs.
In the final step, we must provide a name for our model. Name the model Purchase Intent Prediction. You can choose to reduce the training time to see quick results or increase the amount of time spent in training to get the best model. Then select Save and train to start training the model.
The training process will begin by sampling and normalizing your historical data and splitting your dataset into two new entities Purchase Intent Prediction Training Data and Purchase Intent Prediction Testing Data.
Depending on the size of the dataset, the training process can take anywhere from a few minutes to the training time selected at the previous screen. At this point, you can see the model in the Machine learning models tab of the dataflow. The Ready status indicates that the model has been queued for training or is under training.
You can confirm that the model is being trained and validated through the status of the dataflow. This appears as a data refresh in progress in the Dataflows tab of the workspace.
Once the model training is completed, the dataflow displays an updated refresh time. You can confirm that the model is trained, by navigating to the Machine learning models tab in the dataflow. The model you created should show status as Trained and the Last Trained time should now be updated.
Review the model validation report
To review the model validation report, in the Machine learning models tab, select the View training report button in the Actions column for the model. This report describes how your machine learning model is likely to perform.
In the Model Performance page of the report, select See top predictors to view the top predictors for your model. You can select one of the predictors to see how the outcome distribution is associated with that predictor.
You can use the Probability Threshold slicer on the Model Performance page to examine its influence on the Precision and Recall for the model.
The other pages of the report describe the statistical performance metrics for the model.
The report also includes a Training Details page that describes the different iterations that were run, how features were extracted from the inputs, and the hyperparameters for the final model used.
Apply the model to a dataflow entity
Select the Apply model button at the top of the report to invoke this model. In the Apply dialog, you can specify the target entity that has the source data to which the model should be applied.
When prompted, you must Refresh the dataflow to preview the results of your model.
Applying the model will create two new entities, with the suffix enriched and enriched explanations. In our case, applying the model to the Online Visitors entity will create Online Visitors enriched Purchase Intent Prediction which includes the predicted output from the model, and Online Visitors enriched Purchase Intent Prediction explanations which contains top record-specific influencers for the prediction.
Applying a Binary Prediction model adds four columns with predicted outcome, probability score, the top record-specific influencers for the prediction, and explanation index each prefixed with the column name specified.
Once the dataflow refresh is completed, you can select the Online Visitors enriched Purchase Intent Prediction entity to view the results.
You can also invoke any AutoML model in the workspace, directly from the Power Query Editor in your dataflow. To access the AutoML models, select theВ EditВ button for the entity that you want to enrich with insights from your AutoML model, as shown in the following image.
Selecting theВ EditВ button opens the Power Query Editor for the entities in your dataflow. Select theВ AI InsightsВ button in the ribbon.
Select theВ Power BI Machine Learning ModelsВ folder from the nav pane menu. All the AutoML models to which you have access are listed here as Power Query functions. Also, the input parameters for the AutoML model are automatically mapped as parameters of the corresponding Power Query function. Note that automatic mapping of parameters happens only if the name and data type of the parameter is the same.
To invoke an AutoML model, you can specify any of the selected entity’s columns as an input from the drop-down. You can also specify a constant value to be used as an input by toggling the column icon to the left of the input dialog.
SelectВ Apply to view the preview of the AutoML model’s output as a new columns in the entity table. You will also see the model invocation as an applied step for the query.
Once you save your dataflow, the model is automatically invoked when the dataflow is refreshed, for any new or updated rows in the entity table.
Using the scored output from the model in a Power BI report
To use the scored output from your machine learning model you can connect to your dataflow from the Power BI desktop, using the Dataflows connector. The Online Visitors enriched Purchase Intent Prediction entity can now be used to incorporate the predictions from your model in Power BI reports.
Next steps
In this tutorial, you created and applied a binary prediction model in Power BI using these steps:
For more information about Machine Learning automation in Power BI, see Automated Machine Learning in Power BI.