<?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 Manjusha N G on Medium]]></title>
        <description><![CDATA[Stories by Manjusha N G on Medium]]></description>
        <link>https://medium.com/@manjushang?source=rss-c8c0fb961ef2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*Os7-BUe76qpyJO2R</url>
            <title>Stories by Manjusha N G on Medium</title>
            <link>https://medium.com/@manjushang?source=rss-c8c0fb961ef2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 02:15:47 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@manjushang/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[Using Generative AI to Transform Your Business]]></title>
            <link>https://medium.com/@manjushang/using-generative-ai-to-transform-your-business-db1f4e0af46d?source=rss-c8c0fb961ef2------2</link>
            <guid isPermaLink="false">https://medium.com/p/db1f4e0af46d</guid>
            <category><![CDATA[generative-ai-solution]]></category>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Manjusha N G]]></dc:creator>
            <pubDate>Tue, 26 Nov 2024 09:56:49 GMT</pubDate>
            <atom:updated>2024-11-26T10:02:02.295Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Do you ever wonder, “How can I make use of Generative AI and Large Language Models (LLMs) for my business?”</strong></p><p>Here’s the good news: leveraging the power of AI doesn’t have to be complicated. With the help of tools, AI can go beyond just answering general questions — it can directly interact with your business data and processes. Today, we’re sharing a simple example of how a hotel owner can use AI tools to enhance customer interactions.</p><p>Imagine your customers interacting with an assistant that can accurately answer questions like, <em>“What’s the price of biriyani?”</em> or <em>“Can you show me the menu?”</em> by pulling real-time data from your systems. This is the power of tools — specialized functions that make AI smarter, more accurate, and deeply integrated with your business.</p><h3>Why Tools are a Game-Changer for Generative AI</h3><p>Generative AI models are excellent at understanding and generating natural language. However, they don’t have built-in access to your business-specific data. This is where <strong>tools</strong> come in. Tools act as extensions that allow the AI to interact with your backend systems, databases, or external APIs.</p><p>For instance, in our hotel example:</p><ul><li>Tools fetch menu prices directly from the hotel’s database.</li><li>Tools list all available items dynamically, ensuring responses are always up-to-date.</li></ul><h3>How Tools Work in Generative AI</h3><p>Tools are pre-defined functions or APIs that the AI can call when it needs specific information or wants to perform a task. These tools are described using structured schemas, which the AI model understands and uses to invoke them as needed.</p><p>Here’s how the process works:</p><ol><li><strong>User Query</strong>: A customer asks, <em>“What’s the price of biriyani?”</em></li><li><strong>Tool Detection</strong>: The AI identifies that the query requires a tool (get_menu_price).</li><li><strong>Tool Execution</strong>: The backend system executes the function with the required input (item=&quot;biriyani&quot;).</li><li><strong>Response Integration</strong>: The AI integrates the result (e.g., 100) into a natural language response: <em>“The price of biriyani is 100.”</em></li></ol><p>This seamless integration of tools makes the AI capable of delivering accurate, real-time, and context-specific responses.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/929/1*jW7i4vtM-crhKm25zfVuPw.png" /></figure><h3>A Practical Example for Hotel Owners</h3><p>In our hotel chatbot example, we use tools to fetch menu details. The menu is stored as a dictionary:</p><pre>menu = {&quot;biriyani&quot;: &#39;100&#39;, &quot;fried rice&quot;: &#39;120&#39;, &quot;porotta&quot;: &#39;30&#39;, &quot;chicken 65&quot;: &#39;150&#39;}<br>def get_menu_price(item):<br>    return menu.get(item.lower(),&quot;unknown&quot;)<br>def get_menu():<br>    return &quot;,&quot;.join(menu.keys())</pre><p>We’ve written two simple helper functions to interact with this data:</p><ul><li><strong>get_menu_price(item)</strong>: Returns the price of a menu item.</li><li><strong>get_menu()</strong>: Lists all available items.</li></ul><p>Here’s how the tools are defined. Make sure that the descriptions are written in detail .</p><pre>price_function = {<br>&quot;name&quot;: &quot;get_menu_price&quot;,<br>&quot;description&quot;: &quot;Get the price of an item in the menu.&quot;,<br>&quot;parameters&quot;: {&quot;type&quot;: &quot;object&quot;, &quot;properties&quot;: {&quot;item&quot;: {&quot;type&quot;: &quot;string&quot;}}}<br>}<br>menu_function = {<br>&quot;name&quot;: &quot;get_menu&quot;,<br>&quot;description&quot;: &quot;Get all items available in the hotel.&quot;<br>}</pre><p>When a customer asks for the menu or the price of a specific item, the AI calls the appropriate tool, executes the logic, and integrates the result into its response.</p><h3>Building the Conversation Flow</h3><p>The conversational flow includes:</p><ol><li>A <strong>system message</strong> to define the assistant’s tone:</li></ol><pre>system_message = &#39;&#39;&#39;You are a helpful assistant working for my hotel Sagar.  Give short answers in 1 sentence. Always be accurate. If you don&#39;t know, say so.&#39;&#39;&#39;</pre><p>A <strong>chat function</strong> that processes user messages and determines when to use tools:</p><pre>def chat(message, history):<br>    messages = [{&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: system_message}] + history + [{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: message}]<br>    response = openai.chat.completions.create(model=MODEL, messages=messages, tools=tools)<br>    <br>    if response.choices[0].finish_reason == &quot;tool_calls&quot;:<br>        message = response.choices[0].message<br>        <br>        # Check if message has tool_calls (use dot notation to check if it exists)<br>        tool_calls = getattr(message, &#39;tool_calls&#39;, None)<br>        <br>        if tool_calls:<br>            response = handle_tool_call(message)<br>            messages.append(message)<br>            messages.append(response)<br>            response = openai.chat.completions.create(model=MODEL, messages=messages)<br>    <br>    return response.choices[0].message.content</pre><p>A <strong>tool handler</strong> to execute tool calls and return results:</p><pre>  def handle_tool_call(message):<br>    # Assuming message is of type ChatCompletionMessage, and tool_calls is an attribute or part of the response structure.<br>    # Check if the message contains &#39;tool_calls&#39; attribute and access it directly using dot notation<br>    tool_calls = getattr(message, &#39;tool_calls&#39;, None)  # Safely access &#39;tool_calls&#39; using getattr<br>    <br>    if not tool_calls:<br>        return {&quot;error&quot;: &quot;No tool call found in the message&quot;}<br><br>    # Assuming only one tool call in the response<br>    tool_call = tool_calls[0]  # Get the first tool call if there&#39;s one<br>    tool_call_id = getattr(tool_call, &#39;id&#39;)<br><br>    <br>    function_name = tool_call.function.name  # Access function name using dot notation<br>    arguments = json.loads(tool_call.function.arguments)  # Parse arguments from the function&#39;s arguments field<br><br>    # Call the appropriate function based on the function name<br>    if function_name == &quot;get_menu_price&quot;:<br>        result = get_menu_price(arguments[&quot;item&quot;])<br>        content = {&quot;item&quot;: arguments[&quot;item&quot;], &quot;price&quot;: result}<br>    elif function_name == &quot;get_menu&quot;:<br>        result = get_menu()<br>        content = {&quot;menu&quot;: result}<br>    else:<br>        content = {&quot;error&quot;: &quot;Unknown function&quot;}<br><br>    # Craft the response for the tool call<br>    tool_response = {<br>        &quot;role&quot;: &quot;tool&quot;,<br>        &quot;content&quot;:  json.dumps(content),<br>        &quot;tool_call_id&quot;: message.tool_calls[0].id<br>    }<br>    <br>    return tool_response</pre><p>This ensures a smooth, interactive experience for customers while integrating AI with your business data.</p><p><strong>Interactive User Interface</strong></p><p>Using <strong>Gradio</strong>, the chatbot can be deployed with just a few lines of code, providing an intuitive interface:</p><pre>gr.ChatInterface(fn=chat, type=&quot;messages&quot;).launch()</pre><p><strong>Why This Approach Works</strong></p><ul><li><strong>Custom Data Utilization</strong>: The AI integrates with your own database, ensuring responses are accurate and relevant.</li><li><strong>Scalability</strong>: Tools and functions can be expanded to handle more complex queries as your business grows.</li><li><strong>Efficiency</strong>: Customers get quick answers, reducing the load on your staff.</li></ul><p>Generative AI with tools offers limitless possibilities for transforming your business. Whether you’re a hotel owner looking to simplify customer interactions or a retailer automating product inquiries, tools empower AI to act as an intelligent, reliable assistant.</p><p>This example is just the beginning. By integrating tools that access your data, you can create AI solutions tailored to your unique business needs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=db1f4e0af46d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kubeflow Pipelines: A Step-by-Step Guide]]></title>
            <link>https://medium.com/@manjushang/kubeflow-pipelines-a-step-by-step-guide-46db51184735?source=rss-c8c0fb961ef2------2</link>
            <guid isPermaLink="false">https://medium.com/p/46db51184735</guid>
            <category><![CDATA[gcp]]></category>
            <category><![CDATA[kubeflow]]></category>
            <category><![CDATA[kubeflow-pipelines]]></category>
            <category><![CDATA[vertex-ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Manjusha N G]]></dc:creator>
            <pubDate>Mon, 13 Nov 2023 10:45:19 GMT</pubDate>
            <atom:updated>2023-11-13T11:28:58.357Z</atom:updated>
            <content:encoded><![CDATA[<p>Welcome to the world of Kubeflow pipelines, where machine learning workflows become seamless and scalable. In this blog post, we’ll break down the intricacies of Kubeflow pipelines, exploring their structure and shedding light on the key components that make them powerful tools for data scientists and machine learning engineers.</p><p><strong>Understanding Kubeflow Pipelines Structure</strong></p><p>1. Components of a Kubeflow Pipeline:</p><p>Kubeflow pipelines consist of two crucial components: <strong>@component</strong> and <strong>DSL.Pipeline</strong>. The <strong>@component</strong> decorator, prefixed with an at-the-rate sign (@), turns any Python function following it into a step in the pipeline. This function could be anything from data validation to model training. Each function marked as a component is encapsulated as a standalone Docker image with its runtime and version dependencies.</p><p>2. DSL.Pipeline Decorator:</p><p>The <strong>DSL.Pipeline</strong> decorator, where DSL stands for Domain Specific Language, marks the function following it as the core of the entire pipeline. This function comprises a series of steps executed in a specified order. Parameters, if needed, are passed to this function. Think of it as the orchestrator of your machine learning workflow.</p><p><strong>Example Python Script:</strong></p><p>Below gives an example script. The script can be run over the cloud using Vertex AI Workbench.</p><pre>from kfp import dsl<br>from kfp.dsl import (Output,Metrics,component)<br>from google.cloud.aiplatform import pipeline_jobs<br>from typing import NamedTuple<br>from kfp import compiler<br><br>@component(<br>packages_to_install=[&quot;gcsfs&quot;,&quot;pandas&quot;,&quot;google-cloud-storage&quot;]<br>)<br>def validate_input_ds(filename:str)-&gt; NamedTuple(&quot;output&quot;, [(&quot;input_validation&quot;, str)]):<br><br>    import logging<br>    from google.cloud import storage<br>    import pandas as pd<br><br>    logging.basicConfig(level=logging.INFO)<br><br>    logging.info(f&quot;Reading file: {filename}&quot;)<br>    df = pd.read_csv(filename)<br>    expected_num_cols = 21<br>    num_cols = len(df.columns)<br><br>    logging.info(f&quot;Number of columns: {num_cols}&quot;)<br>    logging.info(f&quot;expected_num_cols: {expected_num_cols}&quot;)<br>    logging.info(f&quot;num_cols != expected_num_cols: {num_cols != expected_num_cols}&quot;)<br>    input_validation=&quot;true&quot;<br>    <br>    if num_cols != expected_num_cols:<br>        input_validation=&quot;false&quot;<br>    <br>    logging.info(f&quot;input_validation: {input_validation}&quot;)<br>    <br>    return (input_validation,)</pre><p>This code defines a Kubeflow component for input dataset validation in machine learning pipelines. The component accepts a CSV file path as input, reads the file using Pandas, and verifies whether the number of columns matches the expected count of 21. Logging essential information, including the filename and validation result, the component returns a NamedTuple with the validation status. The component serves as a crucial step in ensuring data integrity before advancing to subsequent stages of a Kubeflow pipeline.</p><pre><br>@component(<br>packages_to_install=[&quot;google-cloud-aiplatform&quot;,&quot;gcsfs&quot;,&quot;xgboost&quot;,&quot;category_encoders&quot;,&quot;imblearn&quot;,&quot;pandas&quot;,&quot;google-cloud-storage&quot;]<br>)<br>def custom_training_job_component(<br>    max_depth:int,<br>    learning_rate:float,<br>    n_estimators:int,<br>    metrics: Output[Metrics]<br>)-&gt;NamedTuple(&quot;output&quot;, [(&quot;model_validation&quot;, str)]):<br>    import pandas as pd<br>    from sklearn.metrics import precision_score, recall_score, roc_auc_score, accuracy_score<br>    from sklearn.model_selection import train_test_split<br>    from category_encoders import HashingEncoder<br>    from imblearn.over_sampling import SMOTE<br>    from xgboost import XGBClassifier<br>    from google.cloud import storage<br><br>    storage_client = storage.Client()<br>    bucket = storage_client.bucket(&quot;mng-kubeflow&quot;)<br><br>    def load_data(file_path):<br>        df = pd.read_csv(file_path)<br>        return df<br><br>    def split_data(df):<br>        X_train, X_test, y_train, y_test = train_test_split(df.drop(&#39;CREDIT_STANDING_CODE&#39;, axis=1), <br>                                                            df[&#39;CREDIT_STANDING_CODE&#39;], test_size=0.30)<br>        return X_train, X_test, y_train, y_test<br><br><br>    def train_model(X_train, y_train,max_depth,learning_rate,n_estimators):    <br>        model = XGBClassifier(<br>            max_depth=max_depth,<br>            learning_rate=learning_rate,<br>            n_estimators=n_estimators,<br>            random_state=42,<br>            use_label_encoder=False<br>        )    <br>        model.fit(X_train, y_train)<br>        return model<br><br>    def save_model_artifact(pipeline):<br>        artifact_name = &#39;model.bst&#39;<br>        pipeline.save_model(artifact_name)<br>        model_artifact = bucket.blob(&#39;credit-scoring/artifacts/&#39;+artifact_name)<br>        model_artifact.upload_from_filename(artifact_name)<br><br>    def evaluate_model(model, X_test, y_test):<br>        y_pred = model.predict(X_test)<br>        accuracy = accuracy_score(y_test, y_pred)<br>        precision = precision_score(y_test, y_pred)<br>        recall = recall_score(y_test, y_pred)<br>        #confusion_matrix1 = confusion_matrix(y_test, y_pred)<br><br>        return accuracy,precision,recall<br><br>    def encode_features(x, n_components=27):<br>        hashing_ros_enc = HashingEncoder(cols=[&#39;passanger_destination&#39;, &#39;marital_hasChildren&#39;, &#39;occupation&#39;, &#39;coupon&#39;,<br>                                               &#39;temperature_weather&#39;], n_components=n_components).fit(x)<br>        x_test_hashing = hashing_ros_enc.transform(x.reset_index(drop=True))<br>        return x_test_hashing<br><br>    def oversample_data(x_train_hashing, y_train):<br>        sm = SMOTE(random_state=42)<br>        x_sm_train_hashing, y_sm_train = sm.fit_resample(x_train_hashing, y_train)<br>        return x_sm_train_hashing, y_sm_train<br><br>    def save_model_artifact(pipeline):<br>        artifact_name = &#39;model.bst&#39;<br>        pipeline.save_model(artifact_name)<br>        model_artifact = bucket.blob(&#39;credit-scoring/artifacts/&#39;+artifact_name)<br>        model_artifact.upload_from_filename(artifact_name)<br><br>    input_file = &quot;gs://mng-kubeflow/credit-scoring/credit_files.csv&quot;<br>    df = load_data(input_file)<br>    X_train, X_test, y_train, y_test = split_data(credit_df)<br><br>    X_train.fillna(X_train.mode().iloc[0], inplace=True)<br>    X_test.fillna(X_train.mode().iloc[0], inplace=True)<br>    <br>    max_depth=5<br>    learning_rate=0.2<br>    n_estimators=40<br>    pipeline = train_model(X_train, y_train,max_depth,learning_rate,n_estimators)<br><br>    accuracy,precision,recall = evaluate_model(pipeline, X_test, y_test)<br>    metrics.log_metric(&quot;accurancy&quot;, accuracy)<br>    metrics.log_metric(&quot;precision&quot;, precision)<br>    metrics.log_metric(&quot;recall&quot;, recall)<br>    <br>    model_validation = &quot;true&quot;<br>    if accuracy&gt;0.5 and precision&gt;0.5 and recall&gt;0.5 :<br>        save_model_artifact(pipeline)<br>        model_validation=&quot;true&quot;<br>    else :<br>        model_validation=&quot;false&quot;<br><br>    return (model_validation,)</pre><p>The provided code defines a Kubeflow (KFP) component for a custom training job using the XGBoost algorithm. The component, marked for installation of required packages, takes hyperparameters for the XGBoost model, performs data loading, preprocessing, and model training. The data is split into training and testing sets, and the XGBoost model is trained with specified hyperparameters. After evaluation using accuracy, precision, and recall metrics, the results are logged using KFP’s <strong>Metrics</strong> output. If the model’s performance metrics meet certain criteria (accuracy, precision, recall all above 0.5), the trained model is saved as an artifact in Google Cloud Storage. The component returns a NamedTuple indicating the success of the model validation. This component is designed for integration into a larger Kubeflow pipeline for end-to-end machine learning workflows.</p><pre>@component(<br>packages_to_install=[&quot;google-cloud-aiplatform&quot;]<br>)<br>def model_deployment()-&gt; NamedTuple(&quot;endpoint&quot;, [(&quot;endpoint&quot;, str)]):<br>from google.cloud import aiplatform<br>aiplatform.init(project=&quot;cedar-talent-404909&quot;, location=&quot;us-central1&quot;, staging_bucket=&quot;gs://mng-kubeflow&quot;)<br>model = aiplatform.Model.upload(<br>display_name=&quot;Credit Scoring-model&quot;,<br>artifact_uri=&quot;gs://mng-kubeflow/credit-scoring/artifacts/&quot;,<br>serving_container_image_uri = &quot;us-docker.pkg.dev/vertex-ai/prediction/xgboost-cpu.1–6:latest&quot;,<br>sync=False<br>)<br>DEPLOYED_NAME = &quot;creditscore-model-endpoint&quot;<br>TRAFFIC_SPLIT = {&quot;0&quot;: 100}<br>MIN_NODES = 1<br>MAX_NODES = 1<br>endpoint = model.deploy(<br>deployed_model_display_name=DEPLOYED_NAME,<br>traffic_split=TRAFFIC_SPLIT,<br>machine_type=&quot;n1-standard-4&quot;,<br>min_replica_count=MIN_NODES,<br>max_replica_count=MAX_NODES<br>)</pre><p>The provided code defines a Kubeflow (KFP) component for deploying a machine learning model using Google Cloud AI Platform. This component, with dependencies installed for Google Cloud AI Platform, initializes the platform with project details, uploads a pre-trained model to AI Platform, and deploys it. The deployed model, named “Credit Scoring-model,” uses a specified serving container image URI (“us-docker.pkg.dev/vertex-ai/prediction/xgboost-cpu.1–6:latest”). The deployment is asynchronous, and the component returns the endpoint where the deployed model is accessible. Configuration parameters for the deployment include a traffic split of 100%, a machine type of “n1-standard-4,” and both minimum and maximum replica counts set to 1. This component is intended for integration into a larger Kubeflow pipeline for model deployment in machine learning workflows.</p><pre>@dsl.pipeline(<br>pipeline_root=&quot;gs://mng-kubeflow/credit-scoring-pipeline-v1&quot;,<br>name=&quot;credit-scoring-pipeline&quot;,<br>)<br>def pipeline(<br>project: str = &quot;cedar-talent-404909&quot;,<br>region: str = &quot;us-central1&quot;<br>):<br>max_depth=5<br>learning_rate=0.2<br>n_estimators=40<br>file_name = &quot;gs://mng-kubeflow/credit-scoring/credit_files.csv&quot;<br>input_validation_task = validate_input_ds(filename=file_name)<br>with dsl.If(input_validation_task.outputs[&quot;input_validation&quot;] == &quot;true&quot;):<br>model_training = custom_training_job_component(<br>max_depth=max_depth,<br>learning_rate=learning_rate,<br>n_estimators=n_estimators,<br>).after(input_validation_task)<br>with dsl.If(model_training.outputs[&quot;model_validation&quot;] == &quot;true&quot;):<br>task_deploy_model = model_deployment().after(model_training)</pre><p>This Kubeflow (KFP) pipeline, named “credit-scoring-pipeline,” orchestrates an end-to-end machine learning workflow. Configured to run in the “cedar-talent-404909” project with a pipeline root at “gs://mng-kubeflow/credit-scoring-pipeline-v1,” the pipeline consists of three main steps. First, it validates the input dataset using the <strong>validate_input_ds</strong> component, ensuring its correctness. If validation is successful, it proceeds to the second step, which involves training a custom XGBoost model with specified hyperparameters using the <strong>custom_training_job_component</strong>. If both input validation and model training are successful, the third step deploys the trained model using the <strong>model_deployment</strong> component. The entire pipeline is compiled into a JSON package and executed in the Google Cloud AI Platform environment in the “us-central1” region, enabling seamless automation of the credit scoring model’s validation, training, and deployment.</p><p><strong>Pipeline Compilation and Execution</strong></p><p>After defining the pipeline, the next steps involve compilation and execution:</p><p><strong>Compilation:</strong></p><p>The <strong>compiler.compile</strong> function compiles the pipeline, specifying the pipeline function (<strong>ml_pipeline</strong>) and the package path (e.g., ‘ML_Pipeline.json’). This step writes all the compiled steps to a JSON file.</p><p><strong>Execution:</strong></p><p>The pipeline job function is invoked, passing the compiled JSON file as a parameter. This kicks off the execution of your Kubeflow pipeline.</p><pre>compiler.Compiler().compile(pipeline_func=pipeline,package_path=&#39;credit-scoring-pipeline.json&#39;)<br>start_pipeline = pipeline_jobs.PipelineJob(<br>display_name=&quot;simple-kubeflow-pipeline&quot;,<br>template_path=&quot;credit-scoring-pipeline.json&quot;,<br>enable_caching=False,<br>location=&quot;us-central1&quot;,<br>)<br>start_pipeline.run()</pre><p>The kuberflow pipeline can be seen at the vertex AI Page</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*yFchNIZ0pWDrtPKbyTpi6A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*R8CMQnIxFzm0HVffyeNMhg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*JQW4KfzYRShBr8To_c-5Rw.png" /></figure><p><strong>Conclusion</strong></p><p>Understanding Kubeflow pipelines is pivotal for anyone navigating the world of data science and machine learning. The structure, although initially daunting, becomes straightforward with practice. As you embark on your Kubeflow journey, remember that the real power lies in the simplicity and scalability Kubeflow brings to your machine learning workflows.</p><p>Happy Kubeflow coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=46db51184735" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Complex Queries in PySpark]]></title>
            <link>https://medium.com/@manjushang/how-to-write-queries-in-pyspark-c85742d6bf68?source=rss-c8c0fb961ef2------2</link>
            <guid isPermaLink="false">https://medium.com/p/c85742d6bf68</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[pyspark]]></category>
            <dc:creator><![CDATA[Manjusha N G]]></dc:creator>
            <pubDate>Fri, 06 Oct 2023 11:25:53 GMT</pubDate>
            <atom:updated>2023-10-06T13:00:48.544Z</atom:updated>
            <content:encoded><![CDATA[<p>In this Article I will show how to write some complex queries in PySpark. The Questions are largely available over the internet, I created only PySpark Solutions.</p><ol><li><strong>Analyzing Brand Performance: Finding Brands with Consistently Increasing Prices Using PySpark</strong></li></ol><p>The Data</p><pre>create table brands<br>(<br> Year int,<br> Brand varchar(20),<br> Amount int<br>);<br>insert into brands values (2018, &#39;Apple&#39;, 45000);<br>insert into brands values (2019, &#39;Apple&#39;, 35000);<br>insert into brands values (2020, &#39;Apple&#39;, 75000);<br>insert into brands values (2018, &#39;Samsung&#39;, 15000);<br>insert into brands values (2019, &#39;Samsung&#39;, 20000);<br>insert into brands values (2020, &#39;Samsung&#39;, 25000);<br>insert into brands values (2018, &#39;Nokia&#39;, 21000);<br>insert into brands values (2019, &#39;Nokia&#39;, 17000);<br>insert into brands values (2020, &#39;Nokia&#39;, 14000);</pre><p>SQL Query.</p><pre>SELECT * FROM brands WHERE brand NOT IN (<br>SELECT brand FROM (<br>SELECT year,brand,amount,amount- LAG(amount) <br>OVER(PARTITION BY brand ORDER BY year) AS amt_inc<br>FROM brands)a WHERE amt_inc&lt;0 );</pre><p><strong>PySpark Solution</strong></p><p>First let us create a PySpark dataframe to work with.</p><pre>brandsdf=spark.createDataFrame([(2018, &#39;Apple&#39;, 45000),<br>(2019, &#39;Apple&#39;, 35000),<br>(2020, &#39;Apple&#39;, 75000),<br>(2018, &#39;Samsung&#39;, 15000),<br>(2019, &#39;Samsung&#39;, 20000),<br>(2020, &#39;Samsung&#39;, 25000),<br>(2018, &#39;Nokia&#39;, 21000),<br>(2019, &#39;Nokia&#39;, 17000),<br>(2020, &#39;Nokia&#39;, 14000)],[&#39;Year&#39;,&#39;Brand&#39;,&#39;Amount&#39;])<br>brandsdf.show()<br><br>+----+-------+------+<br>|Year|  Brand|Amount|<br>+----+-------+------+<br>|2018|  Apple| 45000|<br>|2019|  Apple| 35000|<br>|2020|  Apple| 75000|<br>|2018|Samsung| 15000|<br>|2019|Samsung| 20000|<br>|2020|Samsung| 25000|<br>|2018|  Nokia| 21000|<br>|2019|  Nokia| 17000|<br>|2020|  Nokia| 14000|<br>+----+-------+------+</pre><p>Next, lets create some intermediate dataframes.A LAG function along with the window specification is used to get price of the previous year.</p><p>and then, we use the ‘when’ condition to segregate the difference in amounts is a profit or loss.Marked 1 as profit and 0 as loss. While working with BIGDATA, the intermediete results will always be useful.</p><pre>from pyspark.sql.window import Window<br>from pyspark.sql.functions import lag,when<br>Windowspec=Window.partitionBy(&#39;Brand&#39;).orderBy(&#39;Year&#39;)<br># create a new column for Previous year Amount<br>profitLossdf=brandsdf.withColumn(&#39;PrevYearAmount&#39;,lag(&#39;Amount&#39;,1,0).over(Windowspec))<br><br>#Find out whether its a profit or loss, Profit 1 ,loss 0.<br>profitLossdf=profitLossdf.withColumn(&#39;profLoss&#39;,when((profitLossdf.Amount-profitLossdf.PrevYearAmount)&lt;=0,0).otherwise(1))<br>profitLossdf.show()<br>----+-------+------+--------------+--------+<br>|Year|  Brand|Amount|PrevYearAmount|profLoss|<br>+----+-------+------+--------------+--------+<br>|2018|  Apple| 45000|             0|       1|<br>|2019|  Apple| 35000|         45000|       0|<br>|2020|  Apple| 75000|         35000|       1|<br>|2018|  Nokia| 21000|             0|       1|<br>|2019|  Nokia| 17000|         21000|       0|<br>|2020|  Nokia| 14000|         17000|       0|<br>|2018|Samsung| 15000|             0|       1|<br>|2019|Samsung| 20000|         15000|       1|<br>|2020|Samsung| 25000|         20000|       1|<br>+----+-------+------+--------------+--------+</pre><p>Now that we got the year wise report of the company. We can use crosstab function to find the count of years of loss and profit.</p><p>Then finally filter the Brands no years of loss.</p><pre>companystatus=profitLossdf.crosstab(&#39;Brand&#39;,&#39;profLoss&#39;).withColumnRenamed(&#39;0&#39;,&#39;YearsLoss&#39;).withColumnRenamed(&#39;1&#39;,&#39;YearsProfit&#39;).withColumnRenamed(&#39;Brand_profLoss&#39;,&#39;Brand&#39;)<br>companystatus.show()<br><br>+-------+---------+-----------+<br>|  Brand|YearsLoss|YearsProfit|<br>+-------+---------+-----------+<br>|  Apple|        1|          2|<br>|  Nokia|        2|          1|<br>|Samsung|        0|          3|<br>+-------+---------+-----------+<br>companystatus.filter(&#39;YearsLoss==0&#39;).select(&#39;Brand&#39;).show()<br><br>+-------+<br>|  Brand|<br>+-------+<br>|Samsung|<br>+-------+p</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c85742d6bf68" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Large Language Model (LLM)]]></title>
            <link>https://medium.com/@manjushang/large-language-model-llm-a0ffb4a1cf8d?source=rss-c8c0fb961ef2------2</link>
            <guid isPermaLink="false">https://medium.com/p/a0ffb4a1cf8d</guid>
            <dc:creator><![CDATA[Manjusha N G]]></dc:creator>
            <pubDate>Thu, 05 Oct 2023 13:27:15 GMT</pubDate>
            <atom:updated>2023-10-06T06:16:47.307Z</atom:updated>
            <content:encoded><![CDATA[<p>A brief introduction on LLMs in Layman’s language.</p><p>In simple terms, an LLM, or Large Language Model, is a super-smart computer program that understands and generates human language. LLM is a type of artificial intelligence model that has been trained on a vast amount of text data. It’s incredibly skilled at understanding and generating human-like text. Think of it as a very smart virtual assistant that can answer questions, write essays, or even have a conversation with you. It’s the brainpower behind many natural language processing tasks.</p><p>We must be using ChatGPT by now. What is the difference between ChatGPT and LLM? While using ChatGPT, we use the ChatGPT UI to connect to the LLM (GPT-3.5 or GPT 4). The ChatGPT UI, or screen, is a user interface that allows users to interact with the ChatGPT LLM. Many LLMs provide APIs for programmatic interaction, but it is not free.</p><p>The following are some of the most famous LLMs available in the market in 2023:</p><p>GPT-4 (OpenAI)<br>PaLM 2 (Google AI)<br>Bard (Google AI)<br>LLaMA (Google AI)<br>GPT-3.5 (OpenAI)<br>LaMDA (Google AI)<br>BERT (Google AI)<br>Cohere (Cohere)<br>Claude v1 (Anthropic)<br>Megatron-Turing NLG (Nvidia)<br>Jurassic-1 Jumbo (AI21 Labs)</p><h4><strong>How do we connect to LLM</strong></h4><p>We can use the UI to connect to the Language models</p><p>Examples</p><p><a href="https://bard.google.com/chat">https://bard.google.com/chat</a><br><a href="https://chat.openai.com/">https://chat.openai.com/</a></p><p>Alternatively, we can connect to their APIs programmatically using tools such as Langchain, LlamaIndex, and FlowiseAI.</p><h4>Cons of LLMs</h4><p>Large language models (LLMs) have many advantages, such as the ability to generate human-quality text, translate languages, write different kinds of creative content, and answer your questions in an informative way. However, they also have some disadvantages, including:</p><p><strong>Bias</strong>: LLMs are trained on massive datasets of text and code, which can reflect the biases that exist in the real world. This means that LLMs can generate text that is biased against certain groups of people or that promotes harmful stereotypes.<br><strong>Misinformation</strong>: LLMs can be used to generate fake news and other forms of misinformation. This is because LLMs are able to generate text that is grammatically correct and factually plausible, even if it is false.<br><strong>Cost</strong>: LLMs are very expensive to train and deploy. This means that they are not accessible to everyone.<br><strong>Privacy</strong>: LLMs can be used to analyze people’s personal data and to generate profiles of their interests and behaviors. This raises concerns about privacy and data security.<br><strong>Safety</strong>: LLMs can be used to create harmful content, such as hate speech and violent threats. This is because LLMs are able to learn from the data they are trained on, even if that data is negative.</p><p>In summary, Large Language Models (LLMs) like GPT-4 and Bard are powerful tools for understanding and generating human language. However, they face challenges related to bias, misinformation, cost, and privacy concerns. While they offer significant benefits, responsible development and usage are essential to mitigate these drawbacks and maximize their potential for enhancing natural language processing and communication.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a0ffb4a1cf8d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>