<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Daria Mustafina on Medium]]></title>
        <description><![CDATA[Stories by Daria Mustafina on Medium]]></description>
        <link>https://medium.com/@darya.mustafina?source=rss-a6f550ea36e6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*QZToeUCmrEvym4-k</url>
            <title>Stories by Daria Mustafina on Medium</title>
            <link>https://medium.com/@darya.mustafina?source=rss-a6f550ea36e6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 23:34:54 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@darya.mustafina/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Efficient Time-Series Forecasting with Thousands of Local Models on Databricks]]></title>
            <link>https://medium.com/@darya.mustafina/efficient-time-series-forecasting-with-thousands-of-local-models-on-databricks-305162754607?source=rss-a6f550ea36e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/305162754607</guid>
            <category><![CDATA[time-series-forecasting]]></category>
            <category><![CDATA[databricks]]></category>
            <category><![CDATA[forecasting-models]]></category>
            <category><![CDATA[apply-in-pandas]]></category>
            <category><![CDATA[forecasting]]></category>
            <dc:creator><![CDATA[Daria Mustafina]]></dc:creator>
            <pubDate>Sat, 19 Apr 2025 01:03:43 GMT</pubDate>
            <atom:updated>2025-04-24T15:23:52.798Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CaWaU-U53Bcm3a6N" /><figcaption>Photo by <a href="https://unsplash.com/@federize?utm_source=medium&amp;utm_medium=referral">Federico Beccari</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Forecasting in industries like energy and retail often requires working with multiple time-series, each with its unique characteristics. To capture these nuances, it’s important to apply tailored models to each time series. However, fitting individual models to thousands of time series can be a significant challenge.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MaApOxurTQc_tixB-NCiRg.png" /><figcaption>Synthetic multiple time series data representing sales in different stores</figcaption></figure><p>Running <strong>thousands of local models</strong> — one for each time series — allows you to achieve more accurate and relevant forecasts by customizing each model to the specific characteristics of its data. However, the complexity of this approach can overwhelm traditional workflows. Fortunately, Databricks, in combination with <a href="https://docs.databricks.com/en/pandas/pandas-function-apis.html">applyInPandas</a>, offers a scalable solution for managing and processing large datasets across distributed environments.</p><h4><strong>The Journey to Efficient Time-Series Forecasting</strong></h4><p>In February 2024, I got a job at an electricity company and was tasked with doing forecasting for 26,000 customers — as quickly and reliably as possible. It was a challenge I didn’t take lightly, and the solution required working with massive amounts of time-series data.</p><p>I first turned to the solution described in the <a href="http://Serve Many Forecasting Models with Databricks Model Serving at Once">article</a> “Serve Many Forecasting Models with Databricks Model Serving at Once” from <a href="https://medium.com/u/21aed4db6339">Anastasia Prokaieva</a> and the applyInPandas method to scale the training and prediction of multiple local models, logging all the models in MLflow. However, as the number of models grew, I hit a roadblock: MLflow’s RPS limit. This meant I had to run retries to get the full coverage for all the customers.</p><p>I began exploring alternatives. One potential solution was training and prediction within a single pandas function, but this would require retraining all the models every time I needed to make a prediction, which wasn’t efficient. Then one day, a colleague suggested, “Why not try storing the models as binaries?” I decided to give it a go, and after some tinkering, it worked! I was thrilled to have found a way to handle the volume and asynchronous training and inference without hitting bottlenecks.</p><p>Coincidentally, a post by Maria Vechtomova (an MLOps influencer) popped up on LinkedIn about “Asking Any Question About Databricks.” A person from a different country and company shared the forecasting and backtesting problems I had struggled with. Another person responded, suggesting using binary model storage within the Many Models Forecasting library. The conversation led to an exchange between the three of us, and it turned out that storing models as binaries was a solution we all arrived at independently. Today, I want to share this concept solution with you</p><p>In this article, we will explore how to use Databricks and applyInPandas to scale the training and prediction of thousands of local models for time-series forecasting. We&#39;ll cover the workflow from model fitting to making predictions, and the benefits of running such operations in parallel using Databricks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uxbgcJv1FfGrwhaQTyeZYg.png" /></figure><h3>Local Model Definition and Structure</h3><p>To run thousands of local models, we need a structured approach to both fit and predict using the respective time-series data. The workflow can be divided into two main tasks: training the local models and predicting the future values based on the trained models. To do this efficiently, Databricks uses the applyInPandas function, which allows for the execution of functions in parallel on a distributed cluster.</p><p>For training the local models, we need a Spark DataFrame containing a unique ID per time series (for example, store_id). Using this, we will train individual models for each group (or store) from the respective time-series data.</p><h3>Model Fitting with ARIMA (Example)</h3><p>When working with time-series forecasting, one of the most common approaches is to apply a statistical model to each individual time series. In this example, we will demonstrate how to fit an <strong>ARIMA (AutoRegressive Integrated Moving Average)</strong> model for each time series group in a Spark DataFrame.</p><p>To scale this process to thousands of time series, we will utilize <strong>applyInPandas</strong>, which allows us to apply a <strong>Pandas function</strong> to each group of the <strong>Spark DataFrame</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_nOY0MtGRN-cDw3HsTYwdQ.png" /><figcaption>Spark DataFrame with multiple time column (ds), label column (y) and group unique identifier (store_id)</figcaption></figure><p>This enables us to use Pandas operations, such as ARIMA model fitting, on individual groups of the DataFrame (e.g., each store’s time series) <strong>in parallel</strong>. The groups are typically defined by some unique identifier, such as store_id.</p><p>In the workflow below, the <strong>ARIMA model</strong> from statsmodels will be used. However, you can easily swap this out for models from other libraries like <strong>sktime</strong>, <strong>Prophet</strong>, or <strong>scikit-learn</strong>, depending on your specific use case.</p><h4>Step-by-Step Process</h4><ol><li><strong>Define the </strong><strong>fit_local_model_arima Function</strong>:<br>This function will be applied to each time series group (e.g., data for each store). The function will fit an ARIMA model to the time series and serialize the model for storage.</li></ol><pre>import pandas as pd<br>import pickle<br>from statsmodels.tsa.arima.model import ARIMA<br><br>def fit_local_model_arima(pdf: pd.DataFrame) -&gt; pd.DataFrame:<br><br>    model = ARIMA(pdf[&#39;y&#39;], order=(5, 1, 0))  <br>    model_fit = model.fit()<br>    <br>    # Serialize the fitted ARIMA model using pickle<br>    model_data = pickle.dumps(model_fit)<br><br>    # Return a pandas DataFrame with store_id and the serialized model<br>    return pd.DataFrame({<br>        &#39;store_id&#39;: pdf[&#39;store_id&#39;].iloc[0],  # Store ID from the first row<br>        &#39;model&#39;: [model_data]  # Serialized ARIMA model as a list<br>    })<br></pre><p><strong>Explanation</strong>:</p><ul><li>The function fit_local_model_arima is applied to each group of the DataFrame. Each group corresponds to the sales data for a single store.</li><li>The function first fits an ARIMA model to the time series using the <strong>ARIMA</strong> class from the statsmodels.tsa.arima.model package.</li><li>After fitting the model, the fitted model is serialized using <strong>pickle</strong> so that it can be saved and used later for predictions.</li><li>The function returns a DataFrame containing the store_id and the serialized model (model), which will be stored and later retrieved for forecasting.</li></ul><p><strong>2. Apply the Model Fitting Function with </strong><strong>applyInPandas</strong>:<br>The applyInPandas function allows us to run a Pandas function (in this case, fit_local_model_arima) on each group of the Spark DataFrame in parallel. The groups are defined by the store_id, meaning that each store’s sales data will be passed to the fit_local_model_arima function for model fitting.</p><pre>from pyspark.sql import DataFrame<br>from pyspark.sql.types import StructType, StructField, StringType, BinaryType<br><br># Apply the model training function to each group in the DataFrame<br>fitted_local_models = df.groupBy(&#39;store_id&#39;).applyInPandas(<br>    lambda pdf: train_local_model_arima(pdf),<br>    schema=StructType([<br>        StructField(&quot;store_id&quot;, StringType(), True),<br>        StructField(&quot;model&quot;, BinaryType(), True)<br>    ])<br>)</pre><p><strong>3. Storing and Using the Fitted Models</strong></p><p>Once the models are trained and stored in the fitted_local_models DataFrame, they can be saved to a <strong>Unity Catalog</strong> or another persistent storage layer for future use. You can retrieve and deserialize these models later to make predictions on new data.</p><p>For example, you can store these models in Unity Catalog for asynchronous inference or use them for batch predictions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wmswEbZHVbpyedf6327GBg.png" /></figure><h3>Generating Future Timestamps</h3><p>After training the models, we need to create the future time series data for which we want to make predictions. This can be achieved by generating future timestamps for each store based on the most recent timestamp in the historical data.</p><pre>from pyspark.sql import DataFrame<br>from pyspark.sql.functions import col, date_add, max as spark_max, explode, array<br><br>def create_future_dataframe(df: DataFrame, days_ahead: int = 5) -&gt; DataFrame:<br>    &quot;&quot;&quot;<br>    Generate a future dataframe with timestamps for the next &#39;days_ahead&#39; days based on the latest timestamp in the dataset.<br>    <br>    Args:<br>        df (DataFrame): The input DataFrame containing historical data with a &#39;ds&#39; column (timestamp).<br>        days_ahead (int): The number of future days to generate. Default is 5.<br><br>    Returns:<br>        DataFrame: A DataFrame with &#39;store_id&#39; and future dates for the next &#39;days_ahead&#39; days.<br>    &quot;&quot;&quot;<br>    # Get the maximum timestamp for each store_id<br>    max_timestamps = df.groupBy(&quot;store_id&quot;).agg(spark_max(&quot;ds&quot;).alias(&quot;max_ds&quot;))<br><br>    # Generate future timestamps for &#39;days_ahead&#39; days<br>    future_dates = max_timestamps.select(<br>        &quot;store_id&quot;,<br>        # Generate future dates using date_add function<br>        *[date_add(col(&quot;max_ds&quot;), i).alias(f&quot;ds_{i}&quot;) for i in range(1, days_ahead + 1)]<br>    )<br><br>    # Unpivot to get a single column of future dates<br>    future_dates_unpivoted = future_dates.select(<br>        &quot;store_id&quot;, <br>        explode(array([col(f&quot;ds_{i}&quot;) for i in range(1, days_ahead + 1)])).alias(&quot;ds&quot;)<br>    )<br><br>    return future_dates_unpivoted</pre><h3>Making Predictions with ARIMA Models</h3><p>Now that we have generated the future timestamps, we can use the trained models to make predictions. We’ll define a function to deserialize the models and apply them to the future data.</p><pre>from pyspark.sql import DataFrame<br>from statsmodels.tsa.arima.model import ARIMAResults<br>import pickle<br>import pandas as pd<br>from pyspark.sql.types import StructType, StructField, <br>StringType, BinaryType, FloatType, TimestampType<br>from pyspark.sql.functions import col, date_add, <br>max as spark_max, explode, array<br><br>def predict_local_model_arima(future: pd.DataFrame, models: pd.DataFrame) -&gt; pd.DataFrame:<br>    &quot;&quot;&quot;<br>    Generate predictions using ARIMA models for each group using cogroup and applyInPandas.<br>    &quot;&quot;&quot;<br>    # Extract the ARIMA model for the group (ensure it is deserialized properly)<br>    model = pickle.loads(models[&quot;model&quot;].iloc[0])<br>    <br>    # Convert the &#39;ds&#39; column to pandas datetime<br>    future[&#39;ds&#39;] = pd.to_datetime(future[&#39;ds&#39;])<br>    <br>    # Forecast future values (predicting for the length of the future DataFrame)<br>    forecast = model.forecast(len(future))  # Predicting for future periods<br><br>    # Create a DataFrame for the predictions<br>    forecast_df = pd.DataFrame({<br>        &#39;store_id&#39;: [models[&#39;store_id&#39;].iloc[0]] * len(future),  # Store ID for all rows<br>        &#39;ds&#39;: future[&#39;ds&#39;],  # Future dates<br>        &#39;yhat&#39;: forecast.values  # Predicted values<br>    })<br><br>    return forecast_df<br><br>future_dates = create_future_dataframe(df, days_ahead=5)<br><br># Define the schema for the prediction output<br>predict_schema = StructType([<br>    StructField(&quot;store_id&quot;, StringType(), True),<br>    StructField(&quot;ds&quot;, TimestampType(), True),<br>    StructField(&quot;yhat&quot;, FloatType(), True),<br>])<br><br># Apply the prediction function on the grouped data<br>predictions = future_dates.groupby(&quot;store_id&quot;) \<br>    .cogroup(fitted_local_models.groupby(&quot;store_id&quot;)) \<br>    .applyInPandas(<br>        lambda future, models: predict_local_model_arima(future, models),<br>        schema=predict_schema<br>    )<br><br># Show predictions<br>display(predictions)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*klt0jU6xQwnNOjkqFBtxjA.png" /><figcaption>Example output of predictions using applyInPandas for 5 store_ids</figcaption></figure><h4>In this approach:</h4><ul><li><strong>groupBy(&#39;store_id&#39;)</strong>: Groups the data by the store_id column. Each store represents a unique time-series group.</li><li><strong>applyInPandas(lambda pdf: train_local_model_arima(pdf), schema=schema)</strong>: Applies the train_local_model_arima function to each group in parallel, training a separate ARIMA model for each store&#39;s time series.</li><li><strong>cogroup(fitted_local_models.groupby(&#39;store_id&#39;))</strong>: Combines the future data (future_dates) with the fitted models (fitted_local_models), grouped by store_id, so that each store’s data is paired with its corresponding trained model.</li><li><strong>applyInPandas(lambda future, models: predict_local_model_arima(future, models), schema=predict_schema)</strong>: Applies the predict_local_model_arima function in parallel to generate predictions for each store’s time-series group based on the trained ARIMA models.</li></ul><h3>Benefits and Considerations</h3><h4>Advantages</h4><ol><li><strong>Scalability</strong>:<br>Databricks can efficiently process thousands of local models in parallel across large datasets. By utilizing a distributed computing environment, tasks that would typically take much longer on a single machine can be executed in parallel, leading to significant reductions in processing time.</li><li><strong>Flexibility</strong>:<br>Using applyInPandas enables the application of Pandas-based operations, which simplifies model fitting and prediction tasks. This flexibility allows data scientists to take advantage of the rich ecosystem of libraries available in Pandas and seamlessly scale them across a distributed environment.</li><li><strong>Customizability</strong>:<br>Each time series gets its own custom model, allowing for optimized performance by capturing the unique characteristics of the data. This ensures that each time series is treated according to its specific patterns, such as trends and seasonality, resulting in more accurate forecasts.</li></ol><h4>Challenges</h4><ol><li><strong>Print Statements Do Not Show in Driver Logs</strong>:<br>Spark runs tasks in a distributed manner across multiple executors. As a result, print statements inside the applyInPandas function may only appear in the logs of the worker node where the specific task is running. These logs may not be easily accessible or visible in the driver logs, making debugging more difficult.</li><li><strong>Logging from Multiple Workers</strong>:<br>When multiple executors run your <strong>pandas function</strong>, logging can become tricky. You may miss logs from some workers, or the logs might become mixed up if multiple workers write to the same log file concurrently. This could lead to incomplete or confusing logs that make debugging harder.</li><li><strong>Out of Memory or Resource Allocation Issues</strong>:<br>Debugging issues related to memory usage and resource allocation in a distributed environment can be challenging. If your dataset is large, it can be difficult to pinpoint where the problem is occurring without monitoring the Spark cluster closely. Tools such as the Spark UI or Databricks’ resource monitoring tools can help track resource utilization, but they require additional effort and attention.</li><li><strong>Serialization of Logs</strong>:<br>Logs inside <strong>pandas function</strong> are often serialized by Spark, which means any data you try to print or log from within the <strong>pandas function</strong> must be serializable. This can lead to issues when attempting to print complex objects that are not easily serialized, potentially causing errors or losing critical log information.</li></ol><h3>How to Store Fitted Models</h3><ul><li><strong>Option 1</strong>: <strong>Option 1</strong>: Training and prediction can be combined within a single <strong>pandas function, i.e</strong> def train_predict_local_model(pdf). This method avoids storing the models but does not allow for asynchronous inference.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/499/1*lZ6W58iNvcHPqbekbh3eDA.png" /><figcaption>Option. 1: The training and predictions can be combined within pandas UDF</figcaption></figure><ul><li><strong>Option 2</strong>: Use <strong>MLflow</strong> to store the trained models and metadata, enabling asynchronous predictions. This approach for multiple time series is described in details in this <a href="https://medium.com/@anastasia.prokaieva/serve-many-forecasting-models-with-databricks-model-serving-at-once-80d5e3f32943">article</a>. However, for multiple time series, this approach may hit the MLflow <a href="https://docs.databricks.com/aws/en/resources/limits">RPS limit</a>, potentially affecting the forecasting of all groups.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/822/1*awoBtgsuOQjsuGkLCM5llQ.png" /><figcaption>Option 2: Use MlFLow to store the trained models and metadata and predict asynchronous</figcaption></figure><ul><li><strong>Option 3</strong>: Use <strong>Unity Catalog</strong> tables to store the trained models and metadata, and predict asynchronously. This approach is also used for local models in <a href="https://github.com/databricks-industry-solutions/many-model-forecasting">Many Model Forecasting library</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zTscys133RRqQSTilfVyYQ.png" /><figcaption>Option 3: Use Unity Catalog table to store the trained models and metadata and predict asynchronous</figcaption></figure><h3>Conclusion</h3><p>Running thousands of local models for time-series forecasting is a powerful solution for industries like energy and demand forecasting, where each time series may require a distinct model. By leveraging Databricks’ scalability and applyInPandas, you can efficiently handle large datasets and apply custom models in parallel, making the process more manageable. This approach not only improves forecasting accuracy but also allows businesses to make better-informed decisions based on tailored insights from their time-series data.</p><h4>Happy Forecasting!</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=305162754607" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to create Dataiku plugin with json output]]></title>
            <link>https://medium.com/@darya.mustafina/how-to-create-dataiku-plugin-with-json-output-f18f8639c405?source=rss-a6f550ea36e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/f18f8639c405</guid>
            <category><![CDATA[json]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[dataiku]]></category>
            <dc:creator><![CDATA[Daria Mustafina]]></dc:creator>
            <pubDate>Sat, 17 Jun 2023 09:01:14 GMT</pubDate>
            <atom:updated>2023-06-17T09:01:14.463Z</atom:updated>
            <content:encoded><![CDATA[<p>Dataiku is a datascience platfrom that allows to create and reuse self-developed plugins. Plugin has its own front-end, which allows not only data scientists to use it.</p><p>This tutorial demonstrates how to create a plugin with a dataset as an input and a json file as an output to a managed folder in Dataiku</p><h3>Step 1. Creating the project and dataset.</h3><p>If you already have the project and input dataset please skip this test. Otherwise we can create the project from DSS tutorials.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/511/1*DLQEyNrPnOAr35ZbflFFuw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/933/1*-3gygyh0sv3xiEMf_v-0gg.png" /></figure><h3>Step 2. Create the python script to create the json file</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UJ56aLQDnu1eNm57iAgusg.png" /></figure><pre><br>import dataiku<br>import pandas as pd, numpy as np<br>from dataiku import pandasutils as pdu<br><br># Read recipe inputs<br>wine_quality = dataiku.Dataset(&quot;wine_quality&quot;)<br>wine_quality_df = wine_quality.get_dataframe()<br><br>dictionary = {<br>    &quot;quality&quot;: &quot;quality&quot;,<br>    &quot;density&quot;: &quot;density&quot;,<br>    &quot;drink&quot;: &quot;wine&quot;,<br>    &quot;model&quot;: &quot;regression&quot;,<br>    &quot;features&quot;: &#39;alcohol, citric acid&#39;,<br>    &quot;number of irerations&quot;: 100,<br>    }<br>json_object = json.dumps(dictionary, indent=4)<br># Write recipe outputs<br>json_store = dataiku.Folder(&quot;EXar6XyL&quot;)<br>json_store_info = json_store.get_info()<br>json_store.upload_stream(&quot;wine&quot;,json_object)</pre><p>This code snippet reads input data, creates a dictionary, and writes the resulting JSON object to an output folder. The specific details of the input data, dictionary attributes, and output folder location are based on the provided code.</p><h3>Step 3: Convert a Dataiku element to a development plugin</h3><p>You can create a development plugin by converting a Dataiku code-based element, such as a code recipe, to a plugin.</p><p>Open a code recipe and click the <strong>Convert to plugin</strong> action from the sidebar.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OIhelGvQVzY2GY4qjRX-7g.png" /><figcaption>Converting python recipe into plugin</figcaption></figure><p>This action allows us to either create a new plugin that consists of the plugin recipe or to add the recipe component to an existing plugin.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/1*01xR_MJj-SHSt2R453UDRg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5HyAKaph_gKFnkTwLH3DGg.png" /><figcaption>Plugin development recipes</figcaption></figure><ul><li>Add the recipe component to the existing development plugin.</li></ul><p>By adding the recipe component to the existing development plugin, Dataiku makes the appropriate additions to the plugin’s directory structure, along with some starter code that you can modify as needed.</p><h3>Step 4: Modify the plugin component’s starter code</h3><p>To create a good quality plugin, you should follow good coding practices when modifying the starter code. Some practices to consider include:</p><ul><li>using good naming conventions;</li><li>writing clear descriptions;</li><li>checking for errors in user inputs, etc.</li></ul><p>Front-end of the plugin is controlled by the json file in plugin development folder.</p><p>For our case we take dataset as an input and managed folder as the output</p><pre>    &quot;inputRoles&quot;: [<br>        {<br>            &quot;name&quot;: &quot;input&quot;,<br>            &quot;label&quot;: &quot;dataset with an information about the drink&quot;,<br>            &quot;description&quot;: &quot;Input Dataset&quot;,<br>            &quot;arity&quot;: &quot;UNARY&quot;,<br>            &quot;required&quot;: true,<br>            &quot;acceptsDataset&quot;: true<br>        }<br>    ],<br><br>    &quot;outputRoles&quot;: [<br>        {<br>            &quot;name&quot;: &quot;main_output&quot;,<br>            &quot;label&quot;: &quot;managed folder to store json&quot;,<br>            &quot;description&quot;: &quot;output folder&quot;,<br>            &quot;arity&quot;: &quot;UNARY&quot;,<br>            &quot;required&quot;: true,<br>            &quot;acceptsManagedFolder&quot; : true<br>        }<br>        // ...<br>    ],<br>// Inputs and outputs are defined by roles. In the recipe&#39;s I/O tab, the user can associate one<br> // or more dataset to each input and output role.<br>// The &quot;arity&quot; field indicates whether the user can associate several datasets to the role (&#39;NARY&#39;)<br> // or at most one (&#39;UNARY&#39;). The &quot;required&quot; field indicates whether the user is allowed to<br> // associate no dataset with the role.</pre><p>More on the parameters in Dataiku plugin <a href="https://doc.dataiku.com/dss/latest/plugins/reference/params.html">Parameters — Dataiku DSS 12 documentation</a></p><p>Different input parameters can be specified in recipe.json</p><pre>    &quot;params&quot;: [<br>        {<br>            &quot;name&quot;: &quot;drink&quot;,<br>            &quot;label&quot;: &quot;quality of what drink is analysed?&quot;,<br>            &quot;type&quot;: &quot;STRING&quot;,<br>            &quot;description&quot;: &quot;drink for which quality is analysed&quot;,<br>            &quot;defaultValue&quot;: &quot;wine&quot;,<br>            &quot;mandatory&quot;: true<br>        },<br>        {<br>            &quot;name&quot;: &quot;number of iterations&quot;,<br>            &quot;type&quot;: &quot;INT&quot;,<br>            &quot;description&quot;: &quot;number of model runs&quot;,<br>            &quot;defaultValue&quot;: 100<br>        },<br><br>        // A &quot;SELECT&quot; parameter is a multi-choice selector. Choices are specified using the selectChoice field<br>        {<br>            &quot;name&quot;: &quot;model&quot;,<br>            &quot;type&quot;: &quot;SELECT&quot;,<br>            &quot;selectChoices&quot;: [<br>                {<br>                    &quot;value&quot;: &quot;regression&quot;,<br>                    &quot;label&quot;: &quot;regression model&quot;<br>                },<br>                {<br>                    &quot;value&quot;: &quot;classification&quot;,<br>                    &quot;label&quot;: &quot;classification model&quot;<br>                }<br>            ]<br>        },<br><br>        // A &#39;COLUMN&#39; parameter is a string, whose value is a column name from an input schema.<br>        // To specify the input schema whose column names are used, use the &quot;columnRole&quot; field like below.<br>        // The column names will come from the schema of the first dataset associated to that role.<br>        {<br>            &quot;name&quot;: &quot;quality&quot;,<br>            &quot;type&quot;: &quot;COLUMN&quot;,<br>            &quot;description&quot;: &quot;choose the column that contains quality information&quot;,<br>            &quot;columnRole&quot;: &quot;input&quot;<br>        },<br>        {<br>            &quot;name&quot;: &quot;density&quot;,<br>            &quot;type&quot;: &quot;COLUMN&quot;,<br>            &quot;columnRole&quot;: &quot;input&quot;<br>        },     <br>        {<br>            &quot;name&quot;: &quot;features&quot;,<br>            &quot;desciption&quot;: &quot;explanatory varialbes to predict quality&quot;,<br>            &quot;type&quot;: &quot;COLUMNS&quot;,<br>            &quot;columnRole&quot;: &quot;input&quot;<br>        }    <br>        // The &#39;COLUMNS&#39; type works in the same way, except that it is a list of strings.<br>    ],<br><br>    // The field &quot;resourceKeys&quot; holds a list of keys that allows to limit the number<br>    // of concurrent executions and activities triggered by this recipe.<br>    //<br>    // Administrators can configure the limit per resource key in the Administration &gt; Settings &gt; Flow build<br>    // screen.<br><br>    &quot;resourceKeys&quot;: []<br><br>}</pre><p>Now let us see how we can read input and output, create json and store it in the managed output folder in recipe.py</p><p>Input was sepcified as a dataset, so we read all the input datasets</p><pre># import the classes for accessing DSS objects from the recipe<br>import dataiku<br># Import the helpers for custom recipes<br>from dataiku.customrecipe import *<br># Import libraries<br>import pandas as pd, numpy as np<br>from dataiku import pandasutils as pdu<br>import json<br>from io import StringIO<br><br># Inputs and outputs are defined by roles. In the recipe&#39;s I/O tab, the user can associate one<br># or more dataset to each input and output role.<br># Roles need to be defined in recipe.json, in the inputRoles and outputRoles fields.<br><br># To  retrieve the datasets of an input role named &#39;input&#39; as an array of dataset names:<br>input_names = get_input_names_for_role(&#39;input&#39;)<br># The dataset objects themselves can then be created like this:<br>input_datasets = [dataiku.Dataset(name) for name in input_names]<br></pre><p>Output was specified as a folder, so we read it as a folder</p><pre># For outputs, the process is the same:<br>output_names = get_output_names_for_role(&#39;main_output&#39;)<br>output_folders = [dataiku.Folder(name) for name in output_names]</pre><p>The next step would be to create json from the dictionary</p><pre>dictionary = {<br>    &quot;quality&quot;: get_recipe_config()[&#39;quality&#39;],<br>    &quot;density&quot;: get_recipe_config()[&#39;density&#39;],<br>    &quot;drink&quot;: get_recipe_config()[&#39;drink&#39;],<br>    &quot;model&quot;: get_recipe_config()[&#39;model&#39;],<br>    &quot;features&quot;: &#39;, &#39;.join(get_recipe_config()[&#39;features&#39;]),<br>    &quot;iterations&quot;: get_recipe_config()[&#39;iterations&#39;],<br>    }<br>json_object = json.dumps(dictionary, indent=4)</pre><p>And finally store in in the managed folder</p><pre># Write recipe outputs<br><br>output_folder =  output_folders[0]<br><br># Write the json to the managed folder<br>output_folder.upload_stream(f&quot;/{get_recipe_config()[&#39;drink&#39;]}.json&quot;, StringIO(json_object))</pre><h3>Step 5: Test the plugin</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P44fYtk16vp17xuZ_t66Rw.png" /></figure><p>Choos the wine_quality as an input and create the new managed folder as an output</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/978/1*8NWBUHEf1QBIMHnUNxiG2Q.png" /></figure><p>The user interface of the plugin now shows the defined parameters:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/907/1*Py3YFaTXCXi8XqW55oW38g.png" /></figure><p>Then you press <strong>Run</strong> and wait for the plugin to finish the job. The output json will be in the managed folder you specified as an output</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RSn2u60JNE8IHy7jLGsNbQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/287/1*bxoT2--95mqB0zOL4ToyLw.png" /><figcaption>json file that was created by the plugin</figcaption></figure><h3>Appendix</h3><p>full code of recipe. json and recipe.py</p><pre>#  - Replace the hardcoded params values by acccess to the configuration map<br><br># See sample code below for how to do that.<br># The code of your original recipe is included afterwards for convenience.<br># Please also see the &quot;recipe.json&quot; file for more information.<br><br># import the classes for accessing DSS objects from the recipe<br>import dataiku<br># Import the helpers for custom recipes<br>from dataiku.customrecipe import *<br># Import libraries<br>import pandas as pd, numpy as np<br>from dataiku import pandasutils as pdu<br>import json<br>from io import StringIO<br><br><br># Inputs and outputs are defined by roles. In the recipe&#39;s I/O tab, the user can associate one<br># or more dataset to each input and output role.<br># Roles need to be defined in recipe.json, in the inputRoles and outputRoles fields.<br><br><br># To  retrieve the datasets of an input role named &#39;input&#39; as an array of dataset names:<br>input_names = get_input_names_for_role(&#39;input&#39;)<br># The dataset objects themselves can then be created like this:<br>input_datasets = [dataiku.Dataset(name) for name in input_names]<br><br># For outputs, the process is the same:<br>output_names = get_output_names_for_role(&#39;main_output&#39;)<br>output_folders = [dataiku.Folder(name) for name in output_names]<br><br>dictionary = {<br>    &quot;quality&quot;: get_recipe_config()[&#39;quality&#39;],<br>    &quot;density&quot;: get_recipe_config()[&#39;density&#39;],<br>    &quot;drink&quot;: get_recipe_config()[&#39;drink&#39;],<br>    &quot;model&quot;: get_recipe_config()[&#39;model&#39;],<br>    &quot;features&quot;: &#39;, &#39;.join(get_recipe_config()[&#39;features&#39;]),<br>    &quot;iterations&quot;: get_recipe_config()[&#39;iterations&#39;],<br>    }<br>json_object = json.dumps(dictionary, indent=4)<br><br># Write recipe outputs<br><br>output_folder =  output_folders[0]<br><br># Write the json to the managed folder<br>output_folder.upload_stream(f&quot;/{get_recipe_config()[&#39;drink&#39;]}.json&quot;, StringIO(json_object))</pre><p>recipe.json</p><pre>// This file is the descriptor for the Custom code recipe tutorial-json<br>{<br>    // Meta data for display purposes<br>    &quot;meta&quot;: {<br>        // label: name of the recipe as displayed, should be short<br>        &quot;label&quot;: &quot;Tutorial json&quot;,<br>        // description: longer string to help end users understand what this recipe does<br>        &quot;description&quot;: &quot;tutorial for dataiku plugin&quot;,<br>        // icon: must be one of the FontAwesome 3.2.1 icons, complete list here at https://fontawesome.com/v3.2.1/icons/<br>        &quot;icon&quot;: &quot;icon-puzzle-piece&quot;<br>    },<br><br>    &quot;kind&quot;: &quot;PYTHON&quot;,<br><br>    // Inputs and outputs are defined by roles. In the recipe&#39;s I/O tab, the user can associate one<br>    // or more dataset to each input and output role.<br><br>    // The &quot;arity&quot; field indicates whether the user can associate several datasets to the role (&#39;NARY&#39;)<br>    // or at most one (&#39;UNARY&#39;). The &quot;required&quot; field indicates whether the user is allowed to<br>    // associate no dataset with the role.<br><br>    &quot;inputRoles&quot;: [<br>        {<br>            &quot;name&quot;: &quot;input&quot;,<br>            &quot;label&quot;: &quot;dataset with an information about the drink&quot;,<br>            &quot;description&quot;: &quot;Input Dataset&quot;,<br>            &quot;arity&quot;: &quot;UNARY&quot;,<br>            &quot;required&quot;: true,<br>            &quot;acceptsDataset&quot;: true<br>        }<br>    ],<br><br>    &quot;outputRoles&quot;: [<br>        {<br>            &quot;name&quot;: &quot;main_output&quot;,<br>            &quot;label&quot;: &quot;managed folder to store json&quot;,<br>            &quot;description&quot;: &quot;output folder&quot;,<br>            &quot;arity&quot;: &quot;UNARY&quot;,<br>            &quot;required&quot;: true,<br>            &quot;acceptsManagedFolder&quot; : true<br>        }<br>        // ...<br>    ],<br>    /* The field &quot;params&quot; holds a list of all the params<br>       for wich the user will be prompted for values in the Settings tab of the recipe.<br><br>       The available parameter types include:<br>       STRING, STRINGS, INT, DOUBLE, BOOLEAN, SELECT, MULTISELECT, MAP, TEXTAREA, PRESET, COLUMN, COLUMNS<br><br>       For the full list and for more details, see the documentation: https://doc.dataiku.com/dss/latest/plugins/reference/params.html<br>    */<br><br>    &quot;params&quot;: [<br>        {<br>            &quot;name&quot;: &quot;drink&quot;,<br>            &quot;label&quot;: &quot;quality of what drink is analysed?&quot;,<br>            &quot;type&quot;: &quot;STRING&quot;,<br>            &quot;description&quot;: &quot;drink for which quality is analysed&quot;,<br>            &quot;defaultValue&quot;: &quot;wine&quot;,<br>            &quot;mandatory&quot;: true<br>        },<br>        {<br>            &quot;name&quot;: &quot;iterations&quot;,<br>            &quot;type&quot;: &quot;INT&quot;,<br>            &quot;description&quot;: &quot;number of model runs&quot;,<br>            &quot;defaultValue&quot;: 100<br>        },<br><br>        // A &quot;SELECT&quot; parameter is a multi-choice selector. Choices are specified using the selectChoice field<br>        {<br>            &quot;name&quot;: &quot;model&quot;,<br>            &quot;type&quot;: &quot;SELECT&quot;,<br>            &quot;selectChoices&quot;: [<br>                {<br>                    &quot;value&quot;: &quot;regression&quot;,<br>                    &quot;label&quot;: &quot;regression model&quot;<br>                },<br>                {<br>                    &quot;value&quot;: &quot;classification&quot;,<br>                    &quot;label&quot;: &quot;classification model&quot;<br>                }<br>            ]<br>        },<br><br>        // A &#39;COLUMN&#39; parameter is a string, whose value is a column name from an input schema.<br>        // To specify the input schema whose column names are used, use the &quot;columnRole&quot; field like below.<br>        // The column names will come from the schema of the first dataset associated to that role.<br>        {<br>            &quot;name&quot;: &quot;quality&quot;,<br>            &quot;type&quot;: &quot;COLUMN&quot;,<br>            &quot;description&quot;: &quot;choose the column that contains quality information&quot;,<br>            &quot;columnRole&quot;: &quot;input&quot;<br>        },<br>        {<br>            &quot;name&quot;: &quot;density&quot;,<br>            &quot;type&quot;: &quot;COLUMN&quot;,<br>            &quot;columnRole&quot;: &quot;input&quot;<br>        },     <br>        {<br>            &quot;name&quot;: &quot;features&quot;,<br>            &quot;desciption&quot;: &quot;explanatory varialbes to predict quality&quot;,<br>            &quot;type&quot;: &quot;COLUMNS&quot;,<br>            &quot;columnRole&quot;: &quot;input&quot;<br>        }    <br>        // The &#39;COLUMNS&#39; type works in the same way, except that it is a list of strings.<br>    ],<br><br>    // The field &quot;resourceKeys&quot; holds a list of keys that allows to limit the number<br>    // of concurrent executions and activities triggered by this recipe.<br>    //<br>    // Administrators can configure the limit per resource key in the Administration &gt; Settings &gt; Flow build<br>    // screen.<br><br>    &quot;resourceKeys&quot;: []<br><br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f18f8639c405" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>