<?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 Sksujanislam on Medium]]></title>
        <description><![CDATA[Stories by Sksujanislam on Medium]]></description>
        <link>https://medium.com/@786sksujanislam786?source=rss-e59740db5fe0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*DLzaZYoYcn8uK-VK</url>
            <title>Stories by Sksujanislam on Medium</title>
            <link>https://medium.com/@786sksujanislam786?source=rss-e59740db5fe0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 12:47:36 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@786sksujanislam786/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[Bring your Own SKLearn algorithm in Sagemaker]]></title>
            <link>https://medium.com/@786sksujanislam786/bring-your-own-sklearn-algorithm-in-sagemaker-fe573784926e?source=rss-e59740db5fe0------2</link>
            <guid isPermaLink="false">https://medium.com/p/fe573784926e</guid>
            <category><![CDATA[sagemaker-studio]]></category>
            <category><![CDATA[aws-machine-learning]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[sagemaker]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Sksujanislam]]></dc:creator>
            <pubDate>Thu, 19 Oct 2023 12:41:54 GMT</pubDate>
            <atom:updated>2023-10-19T12:41:54.282Z</atom:updated>
            <content:encoded><![CDATA[<p>End-to-end explanation with code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*uAmQ7IV2279cutqDrYJ8Ug.png" /></figure><p>In this tutorial, we are going to do a classification test on the iris dataset using a random forest algorithm in AWS Sagemaker.</p><p>Before starting to the code, let’s understand what things we need to know to do this prediction test.</p><ol><li>What is AWS sagemaker?</li><li>What is S3?</li></ol><h3><strong>AWS Sagemaker :</strong></h3><p>Nowadays we all know that everything is happening on the cloud only. There is a lot of company that provides us the cloud service. But 3 of them are widely used. These are Google Cloud, Amazon AWS, and Microsoft Azure.</p><p>Here we used AWS to prepare the machine learning model. AWS provides us with a great platform named “Sagemaker” which is used for “Data Science” purposes. Here we can create our jupyter notebooks and run our programs.</p><p>In Sagemaker we have a lot of build in algorithms that we can use to make a perfect model. But here we will see how to bring our own algorithm in Sagemaker by doing script mode.</p><p>if you are new to Sagemaker follow this links and you will have a basic understanding of it -</p><ol><li><a href="https://www.youtube.com/watch?v=AVNqdT5ilOg">https://www.youtube.com/watch?v=AVNqdT5ilOg</a></li><li><a href="https://aws.amazon.com/getting-started/hands-on/build-train-deploy-machine-learning-model-sagemaker/">https://aws.amazon.com/getting-started/hands-on/build-train-deploy-machine-learning-model-sagemaker/</a></li></ol><h3><strong>S3 Bucket:</strong></h3><p>S3 bucket is the storage system in AWS, where you can save your data and models. In sagemaker if we want a train a model and create an endpoint , we have to store the data in the S3 bucket first. it’s an important step to use the sagemaker. Also after all the training is done, the output model will be saved in the S3 bucket only. So, you have to create your own bucker in S3 first.</p><p>[Important Note: Please, while creating the bucket, check the location you selected, your bucket location and your sagemaker jupyter notebook location need to be the same, or else you’ll get errors]</p><h3><strong>Create your S3 bucket:</strong></h3><p>Login to your AWS account and on the top search bar, write S3, you’ll see the option, click on it. After that click on ‘create bucket’, give a name to your bucket, and check the region, you have to use the same region for sagemaker as well. Go down, and click “Create Bucket”. Now you can see your S3 bucket there.</p><h3>Create your first Sagemaker Notebook:</h3><p>Now come back to the home page of AWS, and on the search bar, type ‘Sagemaker’, you’ll get the option, to go inside. In Sagemaker you can run your Python code in two ways-</p><p><em>i. Sagemaker Studio</em></p><p><em>ii. Notebook instance</em></p><p>We will follow the 2nd way here, you can search for Sagemaker Studio on the internet, it’s almost similar.</p><p>After going inside Sagemaker, see your left side of the screen, you’ll get a lot of options, click on ‘Notebook’ → ‘Notebook instances’. Now click on ‘Create Notebook instance’.</p><p>Now let’s do the instance creation part together —</p><ol><li><em>Notebook instance name</em>: Give a suitable unique name for your notebook</li><li><em>Notebook instance type</em>: By default, it&#39;s ‘ml.t2.medium’, you can change it based on your requirements, it indicates your RAM and CPU size. If you are in the free tier or you are just doing normal practice, no need to change the instance, use the default one. See the below link to check the size and price for each instance</li></ol><p><a href="https://aws.amazon.com/sagemaker/pricing/">Unified data, analytics and AI</a></p><p>3. <em>IAM role</em>: Click on the drop-down and create a new role, if you are new to sagemaker.</p><p>Let’s keep the other things default as of now.</p><p>and then click on ‘create notebook instance’</p><p>Now you have to wait for some minutes as it will take some time to be in service.</p><p>When your notebook is ready to use, in status you’ll see — ‘InSerivce’</p><p>You can open jupyter notebook or jupyter lab.</p><p>We completed the setup of our instance in the cloud. Now, it&#39;s time to start the model training.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/1*6WylsNPAovm3c1OVec7XqA.jpeg" /></figure><p>Inside your Jupyter instance create a new notebook, choose “conda_python3”</p><h4>1. Import Necessary Libraries</h4><pre>import numpy as np<br>import pandas as pd<br>from sklearn.model_selection import train_test_split<br>from sklearn.preprocessing import StandardScaler, LabelEncoder</pre><p>This section imports essential Python libraries for data handling and preprocessing. It includes NumPy and Pandas for data manipulation, as well as scikit-learn for machine learning tasks. The SageMaker library is also imported for working with AWS SageMaker.</p><h4>2. SageMaker Configuration</h4><pre>import sagemaker<br>from sagemaker import get_execution_role<br>from sagemaker.sklearn.estimator import SKLearn<br>sagemaker_session = sagemaker.Session()<br>role = get_execution_role()<br>region = sagemaker_session.boto_session.region_name</pre><p>In the above part, we configure the SageMaker environment. This involves importing necessary SageMaker modules, setting up the SageMaker session, obtaining the AWS IAM role required for SageMaker, and determining the AWS region for the session.</p><p>Now let’s read the iris dataset</p><pre>df=pd.read_csv(&quot;iris.csv&quot;)<br>df.head()<br>df[&#39;class&#39;].value_counts()</pre><p>[Note: AWS sagemaker has many build-in algorithms like XGBoost, DeepAR, etc, where we don’t have to do the data splitting into X and Y columns, we just have to pass the data and do the other task by itself. In these types of cases, sagemaker asks you to create the data frame in a needed format <strong>where the Y or target column should be placed first, followed by the feature columns. </strong>So, for build-in algorithm cases, it’s mandatory to follow the position, but in the case of script mode, it really does not matter.</p><p>Adding this reference for build in XGboost Algorithm, just go through it.</p><p><a href="https://aws.amazon.com/getting-started/hands-on/build-train-deploy-machine-learning-model-sagemaker/">How to build, train, and deploy a machine learning model with Amazon SageMaker</a></p><p>Sagemaker supports many ML frameworks like SKlearn, Tensorflow, Pytorch, and HuggingFace to deploy your own model. This process is known as ‘Script mode’. Here we’ll create the model using this process only.</p><p>To train a model in Sagemaker, we need to follow some rules. The data which we are going to use to train our model, are needed to be placed inside the S3 bucket.</p><p>So in this notebook, there will be 4 steps</p><ol><li>Data preprocessing and train test split</li><li>Upload the train and test data to s3</li><li>train the sklearn estimator with the data and upload the model to the s3 location</li><li>deploy the final endpoint</li></ol><p>Now let’s do the needed preprocessing and train test split</p><pre># 1. Renaming Columns<br>df.columns = [&quot;sepal_length&quot;, &quot;sepal_width&quot;, &quot;petal_length&quot;, &quot;petal_width&quot;, &quot;target&quot;]<br><br># This line of code renames the columns in the dataset. The columns are renamed to more descriptive names.<br><br># 2. Printing Dataset Shape<br>print(df.shape)<br><br># This code prints the shape of the dataset, which includes the number of rows and columns. <br># It provides an overview of the dataset&#39;s size.<br><br># 3. Checking for Missing Values<br>missing_values = df.isnull().sum()<br><br># This code calculates and stores the count of missing values in each column of the dataset.We used label encoder to change the species categories to numbers. Now let’s shuffle the dataset and do the train test split</pre><p>Now let&#39;s split the data in train and test and then save it to the local directory</p><pre># 1. Selecting the Target Variable<br>y = df[&quot;target&quot;]<br><br># Here, we extract the target variable from the dataset and store it in the variable &#39;y&#39;.<br><br># 2. Train-Test Split<br>train_data, test_data = train_test_split(df, test_size=0.2, stratify=y)<br><br># This code splits the dataset into two parts: a training set and a testing set. <br># The &#39;stratify&#39; parameter ensures that the class distribution in the target variable &#39;y&#39; is preserved in both sets.<br><br># 3. Exporting the Training and Testing Data<br>train_data.to_csv(&#39;iris_train.csv&#39;, index=False)<br>test_data.to_csv(&#39;iris_test.csv&#39;, index=False)<br><br># The training and testing datasets are saved as CSV files. &#39;iris_train.csv&#39; contains the training data, <br># and &#39;iris_test.csv&#39; contains the testing data. The &#39;index=False&#39; option ensures that the index column is not included in the CSV files.</pre><p>Now our train and test data are saved in our local location.</p><p>It’s time to upload them inside the s3 bucket.</p><pre># 1. Define Local File Paths<br>train_file = &#39;iris_train.csv&#39;<br>test_file = &#39;iris_test.csv&#39;<br><br># These variables store the local file paths for the training and testing datasets.<br><br># 2. Set AWS S3 Bucket and Folders<br>bucket_name = &#39;ml-exp-storage&#39;  #change it with your bucket name<br>training_folder = r&#39;ml-iris/train&#39;<br>test_folder = r&#39;ml-iris/test&#39;<br>model_folder = r&#39;ml-iris/model/&#39;<br><br># Here, we specify the AWS S3 bucket name and the respective folders within the bucket for training data, <br># testing data, and model data.<br><br># 3. Create S3 Data Locations<br>training_data_loc = r&#39;s3://&#39; + bucket_name + r&#39;/&#39; + training_folder<br>testing_data_loc = r&#39;s3://&#39; + bucket_name + r&#39;/&#39; + test_folder<br>model_data_loc = r&#39;s3://&#39; + bucket_name + r&#39;/&#39; + model_folder<br><br># These variables store the full S3 paths for the training data, testing data, and model data. <br># These locations are used for storing and retrieving data from Amazon S3.</pre><p>Now, in the above code, we specified the s3 location to upload the train data, test data, and the location to save the model after training. Now run the bellow commands to upload the datasets in the s3 location</p><pre># 1. Upload the Training Data to S3<br>sagemaker_session.upload_data(train_file,<br>                              bucket=bucket_name,<br>                              key_prefix=training_folder)<br><br># This line of code uploads the training dataset (&#39;iris_train.csv&#39;) to the specified Amazon S3 bucket<br># under the &#39;training_folder&#39; key prefix.<br><br># 2. Upload the Testing Data to S3<br>sagemaker_session.upload_data(test_file,<br>                              bucket=bucket_name,<br>                              key_prefix=test_folder)<br><br># Here, we upload the testing dataset (&#39;iris_test.csv&#39;) to the same Amazon S3 bucket under the &#39;test_folder&#39; key prefix.</pre><p>Now as we discussed above, we are going to deploy the Sklearn model using script mode, we have to use the SKLearn estimator from the sagemaker, which will give us a built-in container to train our model. There are certain parameters we have to pass to use the estimator.</p><pre># 1. Set Instance Type<br>instance_type = &#39;ml.m5.xlarge&#39;<br><br># The &#39;instance_type&#39; is configured to specify the type of SageMaker instance to be used for model training.<br># In this case, &#39;ml.m5.xlarge&#39; is chosen.<br><br># 2. Configure the SKLearn Estimator<br>estimator = SKLearn(entry_point=&#39;train.py&#39;,<br>                    framework_version=&quot;0.23-1&quot;,<br>                    py_version=&#39;py3&#39;,<br>                    instance_type=instance_type,<br>                    role=role,<br>                    output_path=model_data_loc,<br>                    base_job_name=&#39;sklearn-iris&#39;,<br>                    hyperparameters={&#39;n_estimators&#39;: 50, &#39;max_depth&#39;: 5})<br><br></pre><p>instance type defines the size and number of CPUs we want to train the model. The advantage of using Sagemaker is that we can use any small instance to create the notebook instance like ml.t3.medium but to train the model we can pass any type of instance like a large-based instance or GPU instance to save time and run the code faster.</p><p>Here’s a more detailed breakdown of each configuration setting for the SageMaker SKLearn Estimator:</p><p><strong>1.</strong> <strong>entry_point:</strong> This parameter specifies the name of the script that serves as the entry point for model training. In this case, it’s set to train.py, indicating that ‘train.py’ is the script responsible for training the machine learning model.</p><p><strong>2. framework_version</strong>: This configuration setting specifies the version of the scikit-learn framework to use. In your code, it’s set to 0.23–1, indicating that version 0.23–1 of scikit-learn is used for the training.</p><p><strong>3. py_version</strong>: This parameter defines the Python version to use for the training job. In your code, it’s set to py3, indicating Python 3 is the selected version.</p><p><strong>4. instance_type</strong>: The instance_type parameter determines the type of Amazon SageMaker instance to use for training. In your code, it’s set to ml.m5.xlarge’, specifying the use of an m5.xlarge instance type.</p><p><strong>5. role</strong>: This setting specifies the AWS Identity and Access Management (IAM) role used by SageMaker for accessing AWS resources. It ensures that SageMaker has the necessary permissions to interact with data and resources. You would typically replace the role with the actual IAM role used in your environment.</p><p><strong>6.output_path</strong>: The output_path is the location where the trained model artifacts will be saved after training. In your code, it’s set to model_data_loc, which is an Amazon S3 path where the model data will be stored.</p><p><strong>7.base_job_name:</strong> This parameter defines a base name for the SageMaker training job. The base name helps in identifying and organizing different SageMaker jobs. In your code, it’s set to sklearn-iris.</p><p><strong>8. hyperparameters:</strong> This configuration allows you to pass hyperparameters to your machine-learning model. In your code, it includes hyperparameters such as n_estimators and max_depth, which are specific to the scikit-learn model being trained. These values are used to configure the behavior of the model during training.</p><p>Each of these configuration settings plays a crucial role in setting up the SageMaker SKLearn Estimator for your machine learning model training job.</p><p>you can check the pricing <a href="https://aws.amazon.com/sagemaker/pricing/">here</a> or you can search for AWS Calculator.</p><p>Now let&#39;s pass our dataset locations into the estimator.</p><pre>estimator.fit({&#39;training&#39;:training_data_loc,&#39;testing&#39;:testing_data_loc})</pre><p>The above code will start training the model.</p><p>Now, if you check the estimator we passed an entry point named train.py, so what&#39;s this? Guess Guess…..</p><p>So that&#39;s the code, where the model training and saving are happening.</p><p>Did u fit the estimator and start the training? okay now it will take some time, meanwhile, let’s check what is there inside train.py</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*-sumOpwTJ-TlbyKZ0OkjXQ.jpeg" /><figcaption><a href="https://imgflip.com/memegenerator/120900523/Heres-the-script">https://imgflip.com/memegenerator/120900523/Heres-the-script</a></figcaption></figure><pre># Import Necessary Libraries<br>from __future__ import print_function<br>import argparse<br>import os<br>import pandas as pd<br>import json<br>import numpy as np<br>from sklearn import ensemble<br>import joblib<br>from io import StringIO<br><br># Define the Training and Evaluation Model<br>def model(args, x_train, y_train, x_test, y_test):<br>    &quot;&quot;&quot;<br>    Train a Random Forest Classifier on the provided data.<br><br>    Args:<br>        args: Parsed command-line arguments containing hyperparameters.<br>        x_train: Features of the training dataset.<br>        y_train: Labels of the training dataset.<br>        x_test: Features of the testing dataset.<br>        y_test: Labels of the testing dataset.<br><br>    Returns:<br>        model: A trained Random Forest Classifier model.<br>    &quot;&quot;&quot;<br>    model = ensemble.RandomForestClassifier(n_estimators=args.n_estimators, max_depth=args.max_depth)<br>    model.fit(x_train, y_train)<br>    <br>    print(&quot;Training Accuracy: {:.3f}&quot;.format(model.score(x_train, y_train)))<br>    print(&quot;Testing Accuracy: {:.3f}&quot;.format(model.score(x_test, y_test))<br>    <br>    return model<br><br># Load Training Data<br>def load__train_data(file_path):<br>    &quot;&quot;&quot;<br>    Load and preprocess the training data.<br><br>    Args:<br>        file_path: Path to the directory containing the training data.<br><br>    Returns:<br>        features: Features of the training dataset.<br>        label: Labels of the training dataset.<br>    &quot;&quot;&quot;<br>    df = pd.read_csv(os.path.join(file_path, &quot;iris_train.csv&quot;)<br>    features = df.iloc[:, :-1]<br>    label = df.iloc[:, -1]<br>    return features, label<br><br># Load Testing Data<br>def load__test_data(file_path):<br>    &quot;&quot;&quot;<br>    Load and preprocess the testing data.<br><br>    Args:<br>        file_path: Path to the directory containing the testing data.<br><br>    Returns:<br>        features: Features of the testing dataset.<br>        label: Labels of the testing dataset.<br>    &quot;&quot;&quot;<br>    df = pd.read_csv(os.path.join(file_path, &quot;iris_test.csv&quot;))<br>    features = df.iloc[:, :-1]<br>    label = df.iloc[:, -1]<br>    return features, label<br><br># Parse Command-Line Arguments<br>def _parse_args():<br>    &quot;&quot;&quot;<br>    Parse command-line arguments.<br><br>    Returns:<br>        args: Parsed command-line arguments.<br>        unknown: Unrecognized arguments.<br>    &quot;&quot;&quot;<br>    parser = argparse.ArgumentParser()<br>    <br>    # Hyperparameters are described here.<br>    parser.add_argument(&#39;--n_estimators&#39;, type=int, default=100)<br>    parser.add_argument(&#39;--max_depth&#39;, type=int, default=5)<br>    <br>    parser.add_argument(&#39;--output-data-dir&#39;, type=str, default=os.environ[&#39;SM_OUTPUT_DATA_DIR&#39;])<br>    parser.add_argument(&#39;--model-dir&#39;, type=str, default=os.environ.get(&#39;SM_MODEL_DIR&#39;))<br>    parser.add_argument(&#39;--train&#39;, type=str, default=os.environ.get(&#39;SM_CHANNEL_TRAINING&#39;))<br>    parser.add_argument(&#39;--test&#39;, type=str, default=os.environ.get(&#39;SM_CHANNEL_TESTING&#39;))<br>    <br>    parser.add_argument(&#39;--hosts&#39;, type=list, default=json.loads(os.environ.get(&#39;SM_HOSTS&#39;))<br>    parser.add_argument(&#39;--current-host&#39;, type=str, default=os.environ.get(&#39;SM_CURRENT_HOST&#39;))<br>    <br>    return parser.parse_known_args()<br><br>if __name__ == &#39;__main__&#39;:<br>    # Parse Command-Line Arguments<br>    args, unknown = _parse_args()<br>    <br>    # Load Training and Testing Data<br>    train_data, train_labels = load__train_data(args.train)<br>    eval_data, eval_labels = load__test_data(args.test)<br>    <br>    # Train the Model<br>    classifier = model(args, train_data, train_labels, eval_data, eval_labels)<br>    <br>    # Save the Model<br>    joblib.dump(classifier, os.path.join(args.model_dir, &quot;model.joblib&quot;))<br><br># Define Model Deserialization Function<br>def model_fn(model_dir):<br>    &quot;&quot;&quot;<br>    Deserialized and return the fitted model.<br><br>    Args:<br>        model_dir: Directory containing the serialized model.<br><br>    Returns:<br>        model: Deserialized model.<br>    &quot;&quot;&quot;<br>    model = joblib.load(os.path.join(model_dir, &quot;model.joblib&quot;))<br>    return model<br><br># Define Input Function<br>def input_fn(request_body, content_type):<br>    &quot;&quot;&quot;<br>    Parse and preprocess input data for prediction.<br><br>    Args:<br>        request_body: Input data in CSV format.<br>        content_type: Content type of the input data.<br><br>    Returns:<br>        test_df: Preprocessed input data in a Pandas DataFrame.<br>    &quot;&quot;&quot;<br>    if content_type == &#39;text/csv&#39;:<br>        # Use StringIO to create a file-like object<br>        data_io = StringIO(request_body)<br>        # Read the file-like object into a DataFrame<br>        test_df = pd.read_csv(data_io)<br>        return test_df<br>    else:<br>        raise ValueError(&quot;This model only supports text/csv input&quot;)<br><br># Define Prediction Function<br>def predict_fn(test_df, model):<br>    &quot;&quot;&quot;<br>    Perform predictions using the trained model.<br><br>    Args:<br>        test_df: Preprocessed input data in a Pandas DataFrame.<br>        model: Trained model.<br><br>    Returns:<br>        pred: Model predictions.<br>    &quot;&quot;&quot;<br>    pred = model.predict(test_df)<br>    return pred<br><br># Define Output Function<br>def output_fn(pred, content_type):<br>    &quot;&quot;&quot;<br>    Format and return model predictions.<br><br>    Args:<br>        pred: Model predictions.<br>        content_type: Content type for the output.<br><br>    Returns:<br>        pred: Formatted model predictions.<br>    &quot;&quot;&quot;<br>    pred = &#39;,&#39;.join([str(x) for x in pred])<br>    print(pred)<br>    return pred</pre><p>Now, if you see the _parse_args function, you’ll get the basic idea of the script. We are passing the necessary parameters as arguments inside the script file like n-estimator, max_depth, model directory, training data path, testing data path, etc.</p><p>When we run estimator.fit, it will download the data from S3 and it will save it inside the temporary location (/opt/ml). We’ll just use those arguments to load the datasets and fit a Random Forest model. After the training is done we are going to save the model in joblib format in our model directory which refers to an S3 location.</p><p>The input_fn, model_fn, predict_fn, and output_fn, these functions help us to get the output in our needed format. We can train the model without these 4 functions as well, in that case, the endpoint will load the data and give the output in the default format which is set by AWS. Change it based on your needs.</p><p>Now let’s talk about the parameters of those functions. Inside model_fn it&#39;s the path of the s3 location where the model is saved, it will fetch the location automatically if we are using the function inside the train.py only.</p><p>It returns the model which will be passed inside the predict_fn as the second parameter.</p><p>While using the final endpoint, we pass the dataset inside our model, which passes through the input_fn function, and then after changing the inputs in our needed format, we return it, which will be passed in the predict_fn as the first parameter.</p><p>Now, is your training completed?</p><p>let’s check…..</p><p>yooohoooo mine is done.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/822/1*DNO8pibLYA_reiTEPlHFLg.png" /><figcaption>Training Success</figcaption></figure><p>Now it&#39;s time to deploy the model which is stored in our s3 path. To deploy a model directly using the estimator, we use estimator.deploy</p><pre>predictor = estimator.deploy(initial_instance_count=1, <br>                           instance_type=instance_type,endpoint_name=&quot;checkIrisV3&quot;)</pre><p>Now our model with get deployed as a real-time endpoint using ml.m5.xlarge instance.</p><p>(Note: Please remember to delete the endpoint once your work is done, as it will cost us money for every second till you delete it)</p><p>Now let&#39;s test the endpoint by sending some testing data, but before that you have to make your endpoint compatible with CSV data.</p><pre># Import Necessary SageMaker Modules<br>from sagemaker.serializers import CSVSerializer<br>from sagemaker.deserializers import CSVDeserializer<br><br># Configure Predictor for CSV Serialization and Deserialization<br>predictor.serializer = CSVSerializer()<br>predictor.deserializer = CSVDeserializer()</pre><p>In this section, we configure the SageMaker Predictor for CSV serialization and deserialization. This means that when sending data to the model for inference, it will be serialized into CSV format, and when receiving model predictions, the output will be deserialized as CSV.</p><p>The CSVSerializer is used to format the input data into CSV format before sending it to the model. This format is often preferred when dealing with structured data, as it allows for easy representation of tabular data.</p><p>On the other hand, the CSVDeserializer is used to interpret the model&#39;s output, which is expected to be in CSV format. This ensures that the model&#39;s predictions are correctly parsed and can be further processed as structured tabular data.</p><p>Now let&#39;s use the predictor to predict on some data</p><pre># 1. Define Test Data<br>test_data = [<br>    {&#39;sepal_length&#39;: 6.7, &#39;sepal_width&#39;: 3.1, &#39;petal_length&#39;: 5.6, &#39;petal_width&#39;: 2.4},<br>    {&#39;sepal_length&#39;: 5.5, &#39;sepal_width&#39;: 2.3, &#39;petal_length&#39;: 4.0, &#39;petal_width&#39;: 1.3},<br>    {&#39;sepal_length&#39;: 5.1, &#39;sepal_width&#39;: 3.3, &#39;petal_length&#39;: 1.7, &#39;petal_width&#39;: 0.5},<br>    {&#39;sepal_length&#39;: 5.7, &#39;sepal_width&#39;: 2.5, &#39;petal_length&#39;: 5.0, &#39;petal_width&#39;: 2.0},<br>    {&#39;sepal_length&#39;: 5.0, &#39;sepal_width&#39;: 2.0, &#39;petal_length&#39;: 3.5, &#39;petal_width&#39;: 1.0}<br>]<br><br># This list &#39;test_data&#39; contains dictionaries representing different data points for testing.<br><br># 2. Create a Pandas DataFrame<br>df1 = pd.DataFrame(test_data)<br><br># This line of code creates a Pandas DataFrame &#39;df1&#39; from the provided test data.<br><br># 3. Convert DataFrame to CSV<br>csv_body = df1.to_csv(index=False)<br><br># The DataFrame &#39;df1&#39; is converted to CSV format and stored in the &#39;csv_body&#39; variable.<br><br># 4. Make Predictions<br>predictions = predictor.predict(csv_body)</pre><p>The output of this is-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/368/1*h3ST6XdP3SQCnuCc8UL-Qw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/573/1*ozXnd7LHrxGYKpRoJozVVQ.png" /></figure><p>it’s not the format that we want right? in the output_fn the format we wrote is different, then why this??</p><p>So, predictor.predict will perform like the way the AWS did the setup. Teh default settings for the output. (Maybe there are ways to modify this as well??)</p><p>But it&#39;s fine I mean in the end we have something more in our hands to do the predictions and to be honest we should practice that approach only as we also need to use AWS Lambda to deploy the model as an API.</p><p>So to do that we’ll use “boto3”.</p><pre><br>import os<br>import io<br>import boto3<br>import json<br>import csv<br>import pandas as pd<br><br># Initialize the SageMaker Runtime Client<br>client = boto3.client(service_name=&#39;sagemaker-runtime&#39;)<br><br># Define a Function for Data Transformation<br>def transform_data(values):<br><br>    for i in values:<br>        if i == &quot;0&quot;:<br>            values = values.replace(&quot;0&quot;, &quot;Iris-setosa&quot;)<br>        if i == &quot;1&quot;:<br>            values = values.replace(&quot;1&quot;, &#39;Iris-versicolor&#39;)<br>        if i == &quot;2&quot;:<br>            values = values.replace(&quot;2&quot;, &#39;Iris-virginica&#39;)<br>    return values<br><br># Define a Function for Inference<br>def give_output(event):<br><br>    # Create a DataFrame from the input data<br>    df1 = pd.DataFrame(event)<br>    csv_body = df1.to_csv(index=False)<br><br>    # Invoke the SageMaker endpoint for inference<br>    result = client.invoke_endpoint(EndpointName=&#39;checkIrisV3&#39;,<br>                                   Body=csv_body,<br>                                   ContentType=&#39;text/csv&#39;)<br>    result = result[&#39;Body&#39;].read().decode(&#39;utf-8&#39;)<br>    <br>    print(result)<br>    # Transform numeric class labels to class names<br>    transformed_result = transform_data(result)<br>   <br>    return transformed_result</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*yPNn3jS3x7xEQ77oEXjhyQ.png" /></figure><p>Cool!!!! Now the output came in our needed format.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/735/1*dpCkBxh_KZl8905qlxxTHg.png" /></figure><p>So that&#39;s the whole end-to-end process to deploy a sklearn model in Sagemaker using script-mode.</p><p>For beginners, it might look a little confusing, but don’t worry slowly you’ll understand it.</p><p>Just remember to delete the endpoints at the end for sure or else it will cost you extra money. And if you don&#39;t need the notebook instance just delete it to save money.</p><blockquote>I have created YouTube videos for the same on my channel, if you want to have a look at it please check. I have started a playlist called <strong>ML-with-AWS</strong> where I’ll complete all the processes to deploy ML models not just sklearn but also pytorch, huggingFace, TensorFlow, etc models in AWS Sagemaker and other services.</blockquote><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fvideoseries%3Flist%3DPLidiugslirPCyZUq8Etx1vGZACAhyhIR6&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fplaylist%3Flist%3DPLidiugslirPCyZUq8Etx1vGZACAhyhIR6%26si%3DlR_LN5zuUmQ6uZgo&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F6Gc2t1mzv9o%2Fhqdefault.jpg%3Fsqp%3D-oaymwEWCKgBEF5IWvKriqkDCQgBFQAAiEIYAQ%3D%3D%26rs%3DAOn4CLB8_boIYHAkspQYJtfTPerE63duNw%26days_since_epoch%3D19649&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="853" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/219630c1575bd5422841ce7eb89a0997/href">https://medium.com/media/219630c1575bd5422841ce7eb89a0997/href</a></iframe><blockquote>Like, share, and subscribe if you wanna stay along with me for the whole series. I’ll also upload videos on LLM/GenAI and other NLP stuff.</blockquote><blockquote><strong><em>The GitHub link of the code is added to my YouTube videos’s description.</em></strong></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fe573784926e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to OpenAI and LangChain]]></title>
            <link>https://medium.com/@786sksujanislam786/introduction-to-openai-and-langchain-131fb629becb?source=rss-e59740db5fe0------2</link>
            <guid isPermaLink="false">https://medium.com/p/131fb629becb</guid>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[gpt-4]]></category>
            <dc:creator><![CDATA[Sksujanislam]]></dc:creator>
            <pubDate>Tue, 17 Oct 2023 08:43:11 GMT</pubDate>
            <atom:updated>2023-11-03T17:53:35.649Z</atom:updated>
            <content:encoded><![CDATA[<p>In the realm of Natural Language Processing (NLP), leveraging the power of pre-trained language models has become increasingly essential. OpenAI’s GPT models are at the forefront of this revolution. In this blog post, we will explore how to use OpenAI’s GPT-4 model for NLP tasks and introduce Langchain, a Python library for simplifying interactions with these models.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*mQdMN7RYPkkenj7-QaG53A.jpeg" /><figcaption>source: medium</figcaption></figure><h3>Setting Up OpenAI</h3><p>Before diving into the code, make sure you have your OpenAI API key handy. If you don’t have one, you can sign up for access to the OpenAI API on their website.</p><p>Let’s start by importing the necessary libraries and setting up your API key using environment variables:</p><pre>import openai<br>import os<br>from dotenv import load_dotenv<br></pre><pre># Set the OPENAI_API_KEY from environment variables<br>os.environ[&quot;OPENAI_API_KEY&quot;] = os.getenv(&quot;OPENAI_API_KEY&quot;)<br>openai.api_key = os.getenv(&quot;OPENAI_API_KEY&quot;)</pre><p>With the API key configured, we are ready to interact with OpenAI’s GPT-4 model.</p><h3>Generating output with OpenAI</h3><p>OpenAI provides a straightforward way to generate text using their Chat API. We can define a prompt and use the API to obtain a response. Here’s how you can do it:</p><pre># Define a prompt for the OpenAI Chat API<br>prompt = &quot;&quot;&quot;<br>Please tell me some key importants about data science<br>&quot;&quot;&quot;</pre><pre># Use OpenAI&#39;s ChatCompletion API to generate a response<br>response = openai.ChatCompletion.create(<br>    model=&quot;gpt-4&quot;,<br>    messages=[<br>        {&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: &quot;You are a helpful assistant.&quot;},<br>        {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: prompt},<br>    ],<br>)<br># Extract the generated text from the response<br>generated_text = response[&#39;choices&#39;][0][&#39;message&#39;][&#39;content&#39;]</pre><p>Finally, print the generated text:</p><pre># Print the generated text<br>print(generated_text)</pre><p>With these simple steps, you can use OpenAI’s GPT-4 to generate text based on a given prompt.</p><h3>Leveraging Langchain</h3><p>Langchain is a Python library that simplifies interactions with various language models, including OpenAI’s GPT models. Let’s see how we can use Langchain to achieve the same result.</p><p>First, you need to import the required modules and create instances of Langchain objects:</p><pre># Import necessary libraries for Langchain<br>from langchain.llms import OpenAI<br>from langchain.chat_models import ChatOpenAI</pre><pre># Create instances of Langchain objects<br>llm = OpenAI()<br>chat_model = ChatOpenAI()</pre><p>Now, you can easily predict a response using Langchain:</p><pre># Use Langchain to predict a response<br>chat_model.predict(&quot;Tell me about data science&quot;)</pre><p>Langchain simplifies the process of interacting with language models, making it more accessible for developers.</p><h3>Using Prompts with Langchain</h3><p>Prompts are a powerful way to instruct language models on how to respond. Langchain provides tools for constructing prompts efficiently. Here’s how to set up prompts with Langchain</p><p>To get started with prompts in Langchain, you need to import the required modules. Langchain provides specific templates for constructing prompts, and you’ll need to import them:</p><pre>from langchain.prompts.chat import (<br>    SystemMessagePromptTemplate,<br>    AIMessagePromptTemplate,<br>    HumanMessagePromptTemplate,<br>    ChatPromptTemplate<br>)<br>from langchain.chains import LLMChain</pre><p>Next, you’ll create an instance of the <strong>ChatOpenAI </strong>class, which represents an OpenAI language model. You can specify settings for the model, such as the temperature (which controls the randomness of responses), model_name (specifying the model to use), and n(the number of tokens in the response):</p><pre>llm = ChatOpenAI(temperature=0.7, model_name=&quot;gpt-4&quot;, n=3)</pre><p>To set up a structured conversation with the language model, you’ll define message templates. These templates include a system message that provides context and a user message with a placeholder for the actual user prompt. In this example, we set the system message to convey that the assistant is an expert in Data Science and Machine Learning, and we use {user_prompt} as a placeholder for the user’s input</p><pre>system_template = SystemMessagePromptTemplate.from_template(&quot;You are an expert in Data Science and Machine Learning&quot;)<br>user_template = HumanMessagePromptTemplate.from_template(&quot;{user_prompt}&quot;)</pre><p>After defining message templates, you’ll create a ChatPromptTemplate by combining these templates into a list. This template structures the conversation by specifying the roles of the system and user messages:</p><pre>template = ChatPromptTemplate.from_messages([system_template, user_template])</pre><p>Now, you create an LLMChain instance, representing a chain of language models. You provide the Langchain model ( llm ) and the prompt template (template) to this chain. The chain will handle interactions with the language model:</p><pre>chain = LLMChain(llm=llm, prompt=template)</pre><p>Before running the chain, you define the user’s prompt. This prompt is the user’s input or question that you want to use in the conversation. In this example, the user is asking about handling outliers in dirty datasets:</p><pre>user_prompt = &quot;How to handle outliers in dirty datasets&quot;</pre><p>Finally, you use the <strong>chain.run()</strong> method to start the conversation. You pass a dictionary with the user’s prompt, replacing the <strong>{user_prompt}</strong> placeholder in the template with the actual user’s question. Langchain will then interact with the language model and provide a response based on the defined system message, user message, and the user’s prompt.</p><pre># Run the Langchain chain with the user prompt<br>chain.run({&quot;user_prompt&quot;: user_prompt})</pre><p>With this structured approach to prompts, you can have more meaningful and context-aware interactions with language models, enhancing the capabilities of your NLP applications.</p><p>So, in this blog, we’ve explored the fundamentals of OpenAI and LangChain. I am planning to do a series on generative AI and LLMs on my YouTube Channel which I recently opened, I already started uploading videos on a playlist called “ML with AWS” where I am showing different techniques to deploy ML models. Go check it out , subscribe and share if you like it</p><p><a href="https://www.youtube.com/@TheDataGuyHere">The Data Guy Here</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=131fb629becb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MULTIVARIATE TIME SERIES FORECASTING USING LSTM]]></title>
            <link>https://medium.com/@786sksujanislam786/multivariate-time-series-forecasting-using-lstm-4f8a9d32a509?source=rss-e59740db5fe0------2</link>
            <guid isPermaLink="false">https://medium.com/p/4f8a9d32a509</guid>
            <category><![CDATA[lstm]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[future-prediction]]></category>
            <category><![CDATA[time-series-forecasting]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Sksujanislam]]></dc:creator>
            <pubDate>Thu, 06 Jan 2022 10:22:23 GMT</pubDate>
            <atom:updated>2023-10-13T09:45:50.327Z</atom:updated>
            <content:encoded><![CDATA[<p>end to end time series forecasting using LSTM with explanation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*Q5I2EaFygA1EjoyEITjDMA.jpeg" /></figure><p><strong><em>Before we start, guys if you like to check out my YouTube channel please click the link — </em></strong><a href="https://www.youtube.com/@TheDataGuyHere"><strong><em>https://www.youtube.com/@TheDataGuyHere</em></strong></a></p><p><strong><em>I’ll upload videos about machine learning, NLP, LLM, GenAI, AWS, etc. (I started my channel recently , and started a new ML series where I&#39;ll show how to do ML tasks in the AWS cloud)</em></strong></p><p>In this tutorial, we are going to perform multivariate time series forecasting with the Deep Learning method (LSTM).</p><p>Let’s first understand two topics-</p><ul><li>What is time series analysis?</li><li>What is LSTM?</li></ul><h4>Time Series Analysis:</h4><p>A time-series represents a series of data based on time orders. It can be Seconds, Minutes, Hours, Days, Weeks, Months, Years. The future data would be dependent on it’s previous values.</p><p>In real world cases we have majorly two type of time series analysis —</p><ol><li>Univariate Time Series</li><li>Multivariate time series</li></ol><p>In case of univariate time series data we will have single column to use to do forecasting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/222/1*Ldx0nUo_DXAvr1Ro24vxFw.png" /><figcaption>Univariate time series data</figcaption></figure><p>As we can see there is only one column , so the upcoming future values will depend on it’s previous values only.</p><p>But in case of multivariate time series data we will have different type of feature values, and the target data would be dependent on those features.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/989/1*3Ql08T9QCjhJUk-4PwtHjA.png" /><figcaption>Multivariate time series data</figcaption></figure><p>As we can see in the picture, in multivariate we would have multiple columns like this to do the forecasting for the target value. (On the above picture “count” is the target value)</p><p>In the above picture data the the count value is not only dependent on it’s previous values but also dependent on the other features. So, to predict the upcoming count values we have to consider all the columns including target column to do the forecasting for the target value.</p><p>One thing we have to remember while performing multivariate time series analysis. You can see that we were using those multiple features to perform forecast for the future target data, so when we will go for predictions we need the feature values (excluding target column as we will do prediction for that only) for the prediction future days</p><p>Let’s understand with an example-</p><p>While training if we use 5 columns [feature1, feature2, feature3, feature4, target] to train the model, we need to provide the 4 columns [feature1, feature2, feature3, feature4] for the upcoming prediction days.</p><p>(Don’t worry if you did not understand the above two paragraphs properly , in coding part everything will be cleared)</p><h4>Long Short Term Memory (LSTM)</h4><p>I am not going to discuss in details about LSTM. I hope you all know what it is. So, I will just give you a small description of it and if you don’t have much knowledge on LSTM don’t worry, I attached some important links to study about LSTM.</p><p>LSTM is basically a Recurrent Neural Network which is capable of handling long-term dependencies.</p><p>Let’s say you are watching a movie. So when any kind of situation is happening in that movie , you already knew what happened earlier and understand , because of the past reasons this new situation occurred. RNN also works in the same way only, they remember the past information and use it to process the current input. The problem with RNN is , they can’t remember Long term dependencies due to Vanishing gradient. So, to avoid long-tern dependency problems LSTMs are designed.</p><p>If you want to know more about LSTM , check this links —</p><ol><li>https://youtu.be/rdkIOM78ZPk</li><li><a href="https://medium.com/analytics-vidhya/in-depth-tutorial-of-recurrent-neural-network-rnn-and-long-short-term-memory-lstm-networks-3a782712a09f">https://medium.com/analytics-vidhya/in-depth-tutorial-of-recurrent-neural-network-rnn-and-long-short-term-memory-lstm-networks-3a782712a09f</a></li></ol><p>Now as we discussed both Time series forecasting and LSTM theory part. Let’s start the coding.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*zvxkRTisTH1CxLJfa9BPPg.jpeg" /></figure><p>Let’s first import the needed libraries to do the forecasting-</p><p>[At the end I attached dataset link for you]</p><pre>import numpy as np<br>import pandas as pd<br>from matplotlib import pyplot as plt<br>from tensorflow.keras.models import Sequential<br>from tensorflow.keras.layers import LSTM<br>from tensorflow.keras.layers import Dense, Dropout<br>from sklearn.preprocessing import MinMaxScaler<br>from keras.wrappers.scikit_learn import KerasRegressor<br>from sklearn.model_selection import GridSearchCV</pre><p>Now let’s load the data using pandas and check the output-</p><pre>df=pd.read_csv(&quot;train.csv&quot;,parse_dates=[&quot;Date&quot;],index_col=[0])<br>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/725/1*Hfr1OhFKRWFohn17nDdVcg.png" /></figure><pre>df.tail()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/793/1*pOKIB4ui8bpDsvN21vNwzw.png" /></figure><p>Okay, now let’s spend some seconds with the data. As we can see the csv file contains the stock data of google from 2001–01–25 to 2021–09–29 and we can see that the data is following day wise frequency.</p><p>[If you want you can convert the frequency to “B” [Business Days only] or “D” As we are not going to use the date, I am just keeping it as it is.]</p><p><strong><em>Here we are trying to predict the future value of “Open” column, so “Open” is the target column here</em></strong></p><p>Let’s check the shape of the data-</p><pre>df.shape</pre><p>The shape of the data is — (5203,5)</p><p>Now let’s do train test split. Remember here we can’t shuffle the data, because in time series we must follow the order.</p><pre>test_split=round(len(df)*0.20)<br>df_for_training=df[:-1041]<br>df_for_testing=df[-1041:]<br>print(df_for_training.shape)<br>print(df_for_testing.shape)</pre><p>df_for training shape- (4162, 5)<br>df_for_testing shape- (1041, 5)</p><p>If you see the data, we can notice that the data range is very high, and they are not scaled in a same range, so to avoid prediction errors let’s scale the data first using MinMaxScaler.</p><p>(You can also use StandardScaler as well)</p><pre>scaler = MinMaxScaler(feature_range=(0,1))<br>df_for_training_scaled = scaler.fit_transform(df_for_training)<br>df_for_testing_scaled=scaler.transform(df_for_testing)<br>df_for_training_scaled</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*3maAD87ZUQujg-nkpCOrow.png" /></figure><p>Hurray! our data is scaled now.</p><p>Now, let’s split the data in X and Y.</p><p>This is the most important part , read each steps properly.</p><pre>def createXY(dataset,n_past):<br>    dataX = []<br>    dataY = []<br>    for i in range(n_past, len(dataset)):<br>            dataX.append(dataset[i - n_past:i, 0:dataset.shape[1]])<br>            dataY.append(dataset[i,0])<br>    return np.array(dataX),np.array(dataY)</pre><pre>trainX,trainY=createXY(df_for_training_scaled,30)<br>testX,testY=createXY(df_for_testing_scaled,30)</pre><p>Let’s discuss what we did in the above code-</p><p>[I will discuss about trainX and trainY for the above code, testX anf testY follow the same idea]</p><p>n_past is the number of step we will look in the past to predict the next target value.</p><p>So here I used 30, means we will use past 30 values (which have all the features including the target column) to predict the 31st target value.</p><p>So, in trainX we will have all the feature values and in trainY we will have only target value.</p><p>Let’s breakdown each and every part of the for loop —</p><p>for training, dataset = df_for_training_scaled , n_past=30</p><p>When i=30:</p><p>data_X.append(df_for_training_scaled[i — n_past:i, 0:df_for_training.shape[1]])</p><p>As you can see the range started from n_past means 30 so for the first time the data range will be- [30 – 30 : 30, 0 : 5] means [0:30 ,0 : 5]</p><p>So for the first time in the dataX list the df_for_training_scaled[0:30,0:5] array will go.</p><p>Now , dataY.append(df_for_training_scaled[i,0])</p><p>As you know right now i = 30 , so it will take only the open value (because in prediction we only want open column, so column range is only 0 which represents open column) from the 30th row.</p><p>So, for the first time in the dataY list the df_for_training_scaled[30,0] value will get stored.</p><p>So, first 30 rows with 5 columns got stored in dataX and 31st row with only open column got stored in dataY. Then we converted the dataX and dataY list to array, because we need them in array format to train in LSTM.</p><p>Like this,the data will get saved in trainX and trainY till the length of the dataset.</p><p>and let’s check the shape.</p><pre>print(&quot;trainX Shape-- &quot;,trainX.shape)<br>print(&quot;trainY Shape-- &quot;,trainY.shape)</pre><p>Output → trainX Shape — (4132, 30, 5)<br> trainY Shape — (4132,)</p><pre>print(&quot;testX Shape-- &quot;,testX.shape)<br>print(&quot;testY Shape-- &quot;,testY.shape)</pre><p>Output → testX Shape — (1011, 30, 5)<br>testY Shape — (1011,)</p><p>4132 is the total number of array available in trainX in every array there is total 30 rows and 5 columns and</p><p>in trainY for each array we have the next target value to train the model.</p><p>Let’s have a look on one of the array containing (30,5) data from trainX</p><p>and trainY value for that trainX array</p><pre>print(&quot;trainX[0]-- \n&quot;,trainX[0])<br>print(&quot;trainY[0]-- &quot;,trainY[0])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/668/1*JuQpDHTulS-flhh9wqSpHg.png" /></figure><p>Now if you check trainX[1] value you will notice that it’s the same data from trainX[0] except the first column, as we are going to see the first 30 to predict the 31st column, automatically after the first prediction it will shift to the 2nd column and take the next 30 value to predict the next target value.</p><p>lets explain this all in a simple format —</p><p>trainX — — →trainY</p><p>[0 : 30,0:5] → [30,0]</p><p>[1:31, 0:5] → [31,0]</p><p>[2:32,0:5] →[32,0]</p><p>like this every data will get saved in trainX and trainY. Hope you understood now how the data is getting saved in trainX and trainY</p><p>Now lets train the model , I used girdsearchCV to do some hyperparameter tuning to find the based model.</p><pre>def build_model(optimizer):<br>    grid_model = Sequential()<br>    grid_model.add(LSTM(50,return_sequences=True,input_shape=(30,5)))<br>    grid_model.add(LSTM(50))<br>    grid_model.add(Dropout(0.2))<br>    grid_model.add(Dense(1))</pre><pre>grid_model.compile(loss = &#39;mse&#39;,optimizer = optimizer)<br>    return grid_model</pre><pre>grid_model = KerasRegressor(build_fn=build_model,verbose=1,validation_data=(testX,testY))<br>parameters = {&#39;batch_size&#39; : [16,20],<br>              &#39;epochs&#39; : [8,10],<br>              &#39;optimizer&#39; : [&#39;adam&#39;,&#39;Adadelta&#39;] }</pre><pre>grid_search  = GridSearchCV(estimator = grid_model,<br>                            param_grid = parameters,<br>                            cv = 2)</pre><p>You can do more hyperparameter tunings and also add more layers if you want for you model. If the dataset is very large I suggest you to increase the epochs and units in LSTM model.</p><p>You can see in the first LSTM layer the input shape is (30,5). It’s came from trainX shape. (trainX.shape[1],trainX.shape[2]) → (30,5)</p><p>Now let’s fit the model in out trainX and trainY data.</p><pre>grid_search = grid_search.fit(trainX,trainY)</pre><p>It will take some time to run as we are doing hyperparameter tuning.</p><p>you can see the loss will decrease like this —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oH3giDeeWPXSXBNhlgxoWw.png" /></figure><p>Now let’s check the best parameters of our model.</p><pre>grid_search.best_params_</pre><p>The output is — {‘batch_size’: 20, ‘epochs’: 10, ‘optimizer’: ‘adam’}</p><p>Now save the best model in my_model variable.</p><pre>my_model=grid_search.best_estimator_.model</pre><p>We created our model to do the predictions for time series.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/225/1*vPd8rNjonZKmuo_7qGIycg.png" /></figure><p>Now let’s test the model with our test data set.</p><pre>prediction=my_model.predict(testX)<br>print(&quot;prediction\n&quot;, prediction)<br>print(&quot;\nPrediction Shape-&quot;,prediction.shape)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/428/1*aexBSF_g3_Hv-aVXKMqfHg.png" /></figure><p>Check the length of testY and prediction, it’s same. Now let’s compare testY with prediction.</p><p>But , here is the twist, I hope you guys remembered we scaled our data at the starting, so first we have to do some inverse scaling process.</p><p>Now, the inverse scaling is little bit tricky, let’s see everything by code</p><pre>scaler.inverse_transform(prediction)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IQ4zECDrnH3IcoOqp0ScnA.png" /></figure><p>If you see the error you can understand the problem. While scaling the data we had 5 column for each row, right now we are having only 1 column which is the target column.</p><p>So we have to change shape to use inverse_transform</p><pre>prediction_copies_array = np.repeat(prediction,5, axis=-1)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/841/1*U7muAXDvyMs-IZUXPcCslA.png" /></figure><p>Now if you see the output you would realize that the 5 column values are similar. It’s just noramlly copied the single prediction column 4 times .</p><p>So Now we have 5 columns [Same column 5 times] .</p><p>Let’s check the shape now-</p><pre>prediction_copies_array.shape</pre><p>output → (1011,5)</p><p>Now we can easily use inverse_transform function.</p><pre>pred=scaler.inverse_transform(np.reshape(prediction_copies_array,(len(prediction),5)))[:,0]</pre><p>We just need the first column after inverse transform, so we used → [:,0] at the end.</p><p>Now we need to compare this pred values with testY. But our testY is also scaled. So, let’s use inverse transform with the same above codes.</p><pre>original_copies_array = np.repeat(testY,5, axis=-1)<br>original=scaler.inverse_transform(np.reshape(original_copies_array,(len(testY),5)))[:,0]</pre><p>Now let’s check the prediction and original values →</p><pre>print(&quot;Pred Values-- &quot; ,pred)<br>print(&quot;\nOriginal Values-- &quot; ,original)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hx5uRUf2xnIkLf7RjofFAQ.png" /></figure><p>Now let’s make a plot to check our pred and original data .</p><pre>plt.plot(original, color = &#39;red&#39;, label = &#39;Real Stock Price&#39;)<br>plt.plot(pred, color = &#39;blue&#39;, label = &#39;Predicted Stock Price&#39;)<br>plt.title(&#39;Stock Price Prediction&#39;)<br>plt.xlabel(&#39;Time&#39;)<br>plt.ylabel(&#39;Google Stock Price&#39;)<br>plt.legend()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/703/1*gx64UsBzHLJZNktl29fk2Q.png" /></figure><p>Yoooo! We did it.</p><p>Okay, Now let’s take some more steps.</p><p>Till now we trained our model , checked that model with test values. Now let’s predict some future values.</p><p>Now let’s take the last 30 values from the main df dataset what we loaded at the beginning[Why 30? because that’s the number of past values we want, to predict the 31st value]</p><pre>df_30_days_past=df.iloc[-30:,:]<br>df_30_days_past.tail()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*Ciq1QpezpdGKnLIMZ5kAkg.png" /></figure><p>We can see that we have all the columns including target column(“Open”).</p><p>Now let’s predict future 30 values.</p><p>As I told you guys before, in multivariate time series forecasting if we want to predict single column by using different features, while doing the prediction we need the feature values(except the target column) to do the upcoming predictions.</p><p>So , here we need the upcoming 30 values of “High”, “Low”, “Close”, “Adj Close” columns to do the prediction of the “Open” column.</p><pre>df_30_days_future=pd.read_csv(&quot;test.csv&quot;,parse_dates=[&quot;Date&quot;],index_col=[0])<br>df_30_days_future</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/584/1*adzxP34n1FgQcsogKx449w.png" /></figure><p>As we can see we have all the columns except “Open” column.</p><p>Now we have to do some steps before doing the prediction using our model →</p><ol><li>We have to scale the past and future data. As you can see in our future data we don’t have “Open” column , so before scaling it , just add a “open” column in the future data with all “0” values.</li><li>After scaling replace the “Open” column value with “nan” in the future data</li><li>Now attach the 30 days old value with 30 days new value (where last 30 “Open” values are nan)</li></ol><pre>df_30_days_future[&quot;Open&quot;]=0<br>df_30_days_future=df_30_days_future[[&quot;Open&quot;,&quot;High&quot;,&quot;Low&quot;,&quot;Close&quot;,&quot;Adj Close&quot;]]<br>old_scaled_array=scaler.transform(df_30_days_past)<br>new_scaled_array=scaler.transform(df_30_days_future)<br>new_scaled_df=pd.DataFrame(new_scaled_array)<br>new_scaled_df.iloc[:,0]=np.nan<br>full_df=pd.concat([pd.DataFrame(old_scaled_array),new_scaled_df]).reset_index().drop([&quot;index&quot;],axis=1)</pre><p>Now check the full_df . The shape will be (60,5) with 30 nan values for the first column at the end.</p><p>Now to do the prediction we have to use the for loop again, what we made while spliting the data in trainX and trainY. But this time we have only X, no Y value is there</p><pre>full_df_scaled_array=full_df.values<br>all_data=[]<br>time_step=30<br>for i in range(time_step,len(full_df_scaled_array)):<br>    data_x=[]<br>    data_x.append(<br>     full_df_scaled_array[i-time_step :i , 0:full_df_scaled_array.shape[1]])<br>    data_x=np.array(data_x)<br>    prediction=my_model.predict(data_x)<br>    all_data.append(prediction)<br>    full_df.iloc[i,0]=prediction</pre><p>let’s discuss the above code. for the first prediction we have previous 30 values. Means, when the for loop run for the first time, it checked the previous 30 values and predict the 31st “Open” data.</p><p>Bur when the 2nd for loop will try to run, it will skip first row and try to get next 30 values means [1:31] , here we will start getting error as in the last row for the open column we have “nan”, so we have replace the “nan” with the prediction each time .</p><p>Now let’s do the inverse transform on our prediction to check the real value like we did before →</p><pre>new_array=np.array(all_data)<br>new_array=new_array.reshape(-1,1)<br>prediction_copies_array = np.repeat(new_array,5, axis=-1)<br>y_pred_future_30_days = scaler.inverse_transform(np.reshape(prediction_copies_array,(len(new_array),5)))[:,0]<br>print(y_pred_future_30_days)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*NgKTH7RMnsXevEWaz9QBCQ.png" /></figure><p>Well done guys!!!!!!</p><p>We predicted 30 future values….</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/531/1*rGRP1EPbn6RTuAhHpIG7eQ.jpeg" /></figure><p>To check the whole notebook and dataset → <a href="https://github.com/sksujan58/Multivariate-time-series-forecasting-using-LSTM">Github</a></p><p><em>[Guys , this is my first ever blog in medium, So please let me know if you found any kind of mistakes.]</em></p><p><strong><em>guys if you like to check out my YouTube channel please click the link — </em></strong><a href="https://www.youtube.com/@TheDataGuyHere"><strong><em>https://www.youtube.com/@TheDataGuyHere</em></strong></a></p><p><strong><em>My other Medium Profile where I’ll upload new topics about AI/ML, Generative AI, LLMs, AWS, etc- </em></strong><a href="https://medium.com/@thedataguyhere"><strong><em>https://medium.com/@thedataguyhere</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4f8a9d32a509" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>