<?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 Vineet Jaiswal on Medium]]></title>
        <description><![CDATA[Stories by Vineet Jaiswal on Medium]]></description>
        <link>https://medium.com/@vineetjaiswal?source=rss-cb477254feab------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*rt7Nvw1l3O5fU0b3.</url>
            <title>Stories by Vineet Jaiswal on Medium</title>
            <link>https://medium.com/@vineetjaiswal?source=rss-cb477254feab------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 10:38:19 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vineetjaiswal/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[GCP Vertex AI learning: Chapter 1— Custom algorithm training and serving]]></title>
            <link>https://medium.com/@vineetjaiswal/gcp-vertex-ai-learning-chapter-1-custom-algorithm-training-and-serving-e2e3c94ceae3?source=rss-cb477254feab------2</link>
            <guid isPermaLink="false">https://medium.com/p/e2e3c94ceae3</guid>
            <category><![CDATA[vertex-ai]]></category>
            <category><![CDATA[gcp]]></category>
            <category><![CDATA[serving]]></category>
            <dc:creator><![CDATA[Vineet Jaiswal]]></dc:creator>
            <pubDate>Thu, 03 Oct 2024 07:59:12 GMT</pubDate>
            <atom:updated>2024-10-03T07:59:12.753Z</atom:updated>
            <content:encoded><![CDATA[<p>The basic assumption while creating this document is, you already know why you need vertex.ai and its offerings.</p><p>As per the official documentation</p><p><em>“Build, deploy, and scale machine learning (ML) models faster, with fully managed ML tools for any use case”</em></p><p>For essential detail, refer to this link: <a href="https://cloud.google.com/vertex-ai#section-1">https://cloud.google.com/vertex-ai</a></p><p>This document is part of the GCP vertex.ai learning series where you will learn</p><ul><li>Custom algorithm training: How to host a custom algorithm docker and do the training on vertex.ai custom training job</li><li>Custom serving: How to build a custom serving module using a vertex.ai custom prediction routine(CPR).</li></ul><h3>Prerequisite</h3><p>Basic assumption: You already have access to the below major component and related service account and access-related stuff is out of the scope of this blog</p><p>Execute these before doing anything from your local to GCP environment, to ensure the connectivity</p><pre>gcloud auth login<br>gcloud config set project PROJECT_ID<br>gcloud config get project<br>gcloud auth application-default login</pre><h3>Data used</h3><p>for the sake of simplicity, using the standard Titanic dataset <a href="https://www.kaggle.com/competitions/titanic/data">https://www.kaggle.com/competitions/titanic/data</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BgmLLGu-H5AX5jIoXhgykA.png" /></figure><p>In an actual scenario, you will almost never get ready to use data, and you need to consider data cleaning activity before reaching such kind of clean data.</p><h3>Custom algorithm training</h3><h3>Custom algorithm docker creation</h3><p>This is one of the most simplified code structures you may follow</p><pre>root <br>- app (it will hold all core logic)<br>    - training.py<br>- dococker file<br>- cloudbuuld congiguration <br>- requirement.txt</pre><p><strong>training.py</strong></p><p>It really is not realistic training code for practical purposes, but it&#39;s most simplified to understand the core logic behind it</p><p>Simple training</p><pre><br>-- name spaces -- <br><br>def main(model_dir, data_dir):<br>    &quot;&quot;&quot;_summary_<br><br>    Args:<br>        model_dir (sting): path of model directory on GCS bucket <br>        data_dir (string) : path of data directory on GCS bucket<br>    &quot;&quot;&quot;<br><br>    # check model path exists <br>    if not os.path.exists(model_dir):<br>        os.makedirs(model_dir)<br><br>    # read the provided data file<br>    # hardcoded file name but it can be changed for actual project<br>    train_data = pd.read_csv(os.path.join(data_dir, &quot;train.csv&quot;))<br><br>    # the most simplified version of pre-processing <br>    # replace categorical values with numerical values<br>    gender_map = {&quot;male&quot;: 1, &quot;female&quot;: 0}<br>    embarked_map = {&quot;C&quot;:0, &quot;Q&quot;: 1, &quot;S&quot;: 2}<br><br>    # select columns to be used for training<br>    train_columns = [&quot;Age&quot;, &quot;Pclass&quot;, &quot;SibSp&quot;, &#39;Parch&#39;, &#39;Fare&#39;, &quot;Embarked&quot;]<br><br>    # drop rows with missing values<br>    train_data.dropna(axis=0, subset=[&quot;Embarked&quot;], inplace=True)<br>    <br>    # fill missing values with median<br>    train_data[&quot;Age&quot;] = train_data[&quot;Age&quot;].fillna(train_data[&quot;Age&quot;].median())<br><br>    # replace categorical values with numerical values<br>    train_data[&quot;Sex&quot;] = train_data[&quot;Sex&quot;].apply(lambda x: gender_map[x])<br>    train_data[&quot;Embarked&quot;] = <br>          train_data[&quot;Embarked&quot;].apply(lambda x: embarked_map[x])<br><br>    # split data into X and Y<br>    X = train_data[train_columns]<br>    Y = train_data[&quot;Survived&quot;]<br><br>    # split data into train and test<br>    train_x, test_x, train_y, test_y = <br>          train_test_split(X,Y, test_size=0.2, random_state=43)<br><br>    # train the model, the basic regression model <br>    model = LogisticRegression()<br>    model.fit(train_x, train_y)<br><br>    # dump the model into a pickle file on GCS bucket<br>    with open(os.path.join(model_dir,&quot;model.pkl&quot;), &quot;wb&quot;) as f:<br>        pickle.dump(model, f )<br><br>    print(&quot;\n...the training job has been done &quot;)<br></pre><p>support to pass the argument</p><pre># main function<br>if __name__ == &quot;__main__&quot;:<br><br>    # parse the arguments<br>    ARGS_PARSER = argparse.ArgumentParser()<br>    ARGS_PARSER.add_argument(<br>        &quot;--data-dir&quot;,<br>        default=&quot;/trainer&quot;,<br>        type=str,<br>        help=&quot;The directory where the input data is stored.&quot;<br>        &quot;Default: /trainer.&quot;<br>    )<br>    ARGS_PARSER.add_argument(<br>        &quot;--model-dir&quot;,<br>        default=&quot;/output&quot;,<br>        type=str,<br>        help=&quot;The directory where the model will be stored.&quot;<br>    )<br>    ARGS = ARGS_PARSER.parse_args()<br><br>    # call the main function<br>    main(**vars(ARGS))</pre><p><strong>Docker file</strong></p><pre>FROM python:3.8<br><br>RUN apt-get update &amp;&amp; apt-get install -y --no-install-recommends <br>RUN pip3 install --upgrade pip setuptools<br><br># Set the working directory to /trainer<br>ENV PATH &quot;${PATH}:/&quot;<br>ENV PYTHONPATH &quot;${PYTHONPATH}:/trainer&quot;<br><br># Copy the requirements file to the image.<br>WORKDIR /<br>COPY ./requirements.txt /<br>RUN pip install -r requirements.txt<br><br># Copy the trainer code to the image.<br>COPY app /trainer<br><br># Run the trainer when the container launches.<br>CMD [&quot;python&quot;, &quot;-m&quot;, &quot;training&quot;]</pre><h3>Push docker on GCS Artifact registry</h3><p>First, you need to create an artifact registry on GCS</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZPXoAvs0W6dAwl10MijWKA.png" /></figure><p>in the same repository, you may have training and prediction images or you may also have different repositories</p><p>in the same prediction root file, you should also have this file</p><p><strong>cloudbuild.yaml</strong></p><p>for a more modular approach, you should create this configuration separately else you can also pass the same parameter while pushing the image on the artifact registry</p><pre>steps:<br>  # Build the container image<br>  - name: &quot;gcr.io/cloud-builders/docker&quot;<br>    args:<br>      [<br>        &quot;build&quot;,<br>        &quot;-t&quot;,<br>        &quot;us-central1-docker.pkg.dev/*******/training-prediction/training&quot;,<br>        &quot;.&quot;,<br>      ]<br>  # Push the container image to Container Registry<br>  - name: &quot;gcr.io/cloud-builders/docker&quot;<br>    args:<br>      [<br>        &quot;push&quot;,<br>        &quot;us-central1-docker.pkg.dev/*******/training-prediction/training&quot;,<br>      ]<br>images:<br>  - us-central1-docker.pkg.dev/*******/training-prediction/training</pre><p>push the image using this command</p><pre>gcloud builds submit --config cloudbuild.yaml</pre><p>it will push your image on the GCP artifact registry and you can check that via your local terminal or GCP console</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6z_Vh4yxiS-jUho-9EQskA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J-AGVjjAKLeTQtI8g-sWVw.png" /></figure><h3>Execute the training job</h3><p>Now your training code has been pushed and you need to execute it to train the model. To do the same, you should have these files in the same root</p><p><strong>trainingconfig.yaml</strong></p><p>having environment and instance configuration</p><pre># vertex environment configuration<br>vertexai-env-config:<br>  input_bucket: titanic-training<br>  output_bucket: titanic-model-output<br>  staging_bucket: titanic-staging<br>  project_id: *********<br>  training_location: training<br>  model_location: model<br>  region: us-central1<br><br># training job instance configuration<br>vertexai-usecase-config:<br>  repository_name: training-prediction<br>  image_name: training<br>  algorithm_version: latest<br>  instance_type: n1-standard-4<br>  num_instance: 1<br>  replica_count: 1</pre><p><strong>runtraining.py</strong></p><p>run the Python file to do the training job, you may create below a file in the same root folder</p><pre><br>def custom_training_job(<br>    display_name, worker_pool_specs, project, location, staging_bucket<br>):<br>    &quot;&quot;&quot;_summary_<br><br>    Args:<br>        display_name (str): training job display name <br>        worker_pool_specs (str): worker pool specification <br>        project (str): GCP project<br>        location (str): gcs location for training job<br>        staging_bucket (str): in between bucket <br>    &quot;&quot;&quot;<br><br>    #  create custom training job <br>    custom_job = aiplatform.CustomJob(<br>        display_name=display_name,<br>        worker_pool_specs=worker_pool_specs,<br>        project=project,<br>        location=location, <br>        staging_bucket = staging_bucket<br>    )<br>    custom_job.run()<br><br># Open custom job environment and training job configuration file<br>with open(f&quot;./training_config.yml&quot;, &quot;r&quot;) as f:<br>    config = yaml.load(f, Loader=yaml.SafeLoader)<br><br># Read configs for custom training job instance<br>PROJECT_ID = config[&quot;vertexai-env-config&quot;][&quot;project_id&quot;]<br>REGION = config[&quot;vertexai-env-config&quot;][&quot;region&quot;]<br>INPUT_BUCKET = config[&quot;vertexai-env-config&quot;][&quot;input_bucket&quot;]<br>OUTPUT_BUCKET = config[&quot;vertexai-env-config&quot;][&quot;output_bucket&quot;]<br>STAGING_BUCKET = config[&quot;vertexai-env-config&quot;][&quot;staging_bucket&quot;]<br>TRAINING_LOC = config[&quot;vertexai-env-config&quot;][&quot;training_location&quot;]<br>MODEL_LOC = config[&quot;vertexai-env-config&quot;][&quot;model_location&quot;]<br><br># Read configs for training job<br>repo_name = config[f&quot;vertexai-usecase-config&quot;][&quot;repository_name&quot;]<br>image_name = config[f&quot;vertexai-usecase-config&quot;][&quot;image_name&quot;]<br>instance_type = config[f&quot;vertexai-usecase-config&quot;][&quot;instance_type&quot;]<br>num_instances = config[f&quot;vertexai-usecase-config&quot;][&quot;num_instance&quot;]<br>replica_count = config[f&quot;vertexai-usecase-config&quot;][&quot;replica_count&quot;]<br><br># Set the input and output data folder<br>input_data = (f&quot;/gcs/{INPUT_BUCKET}/{TRAINING_LOC}&quot;)<br>output_model = f&quot;/gcs/{OUTPUT_BUCKET}/{MODEL_LOC}&quot;<br><br><br># Set the container image URI<br>CONTAINER_IMAGE_URI = <br>(f&quot;{REGION}-docker.pkg.dev/{PROJECT_ID}/{repo_name}/{image_name}:latest&quot;)<br><br># Set the command to run the training job<br>CUSTOM_JOB_COMMAND = [&quot;python&quot;, &quot;-m&quot;, f&quot;trainer.training&quot;]<br><br># Set the arguments for the training job<br>CMD_ARGS = [<br>    &quot;--data-dir&quot;,<br>    input_data,<br>    &quot;--model-dir&quot;,<br>    output_model<br>]<br>CUSTOM_JOB_COMMAND.extend(CMD_ARGS)<br><br># Set the worker pool specs<br>WORKER_POOL_SPECS = [<br>    {<br>        &quot;machine_spec&quot;: {<br>            &quot;machine_type&quot;: instance_type,<br>            # &quot;accelerator_type&quot;: accelerator_type,<br>            # &quot;accelerator_count&quot;: num_instances,<br>        },<br>        &quot;replica_count&quot;: replica_count,<br>        &quot;container_spec&quot;: {<br>            &quot;image_uri&quot;: CONTAINER_IMAGE_URI,<br>            &quot;command&quot;: CUSTOM_JOB_COMMAND,<br>        },<br>    }<br>]<br><br># Run the training job<br>custom_training_job(<br>    display_name=f&quot;training_{CURR_TIMESTAMP}&quot;,<br>    worker_pool_specs=WORKER_POOL_SPECS,<br>    project=PROJECT_ID,<br>    location=REGION, <br>    staging_bucket=STAGING_BUCKET<br>)<br>print(&quot;\n...the training job executed successfully... &quot;)</pre><p>run the Python file</p><pre>python runtraining.py</pre><p>in your local terminal, GCP cloud console, and GCP logging, you can see the progress of the training job and once done, you can validate this from all the places</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uFif-T50oInLAeK4Rx9XmQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oOLTt4Feztqad5tUUnkH1g.png" /></figure><p>you can also find your model on GCS location</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ju_2SFn3Bj5z2tFVjvkCKQ.png" /></figure><h3>Custom serving</h3><p>you can build custom docker here too with ngnix, gunicorn but GCP already provided CPR feature, so you don’t need to do all these custom packagings, you can directly use it and only write custom serving code</p><p>you may follow this folder structure</p><pre>root <br>- prediction (it will hold all core logic)<br>    - handler.py<br>    - predictor.py<br>    - requirements.txt<br>- createendpoint.py<br>- endpointconfig.yaml</pre><p><strong>handler.py</strong></p><pre><br>import json<br>from fastapi import Response<br>from google.cloud.aiplatform.prediction.handler import PredictionHandler<br><br># Standard CPR handler<br>class CprHandler(PredictionHandler):<br>    &quot;&quot;&quot;Default prediction handler for the prediction requests sent to the application.&quot;&quot;&quot;<br><br>    async def handle(self, request):<br>        &quot;&quot;&quot;Handles a prediction request.&quot;&quot;&quot;<br>        request_body = await request.body()<br>        print(&quot;request_body&quot;, request_body)<br>        prediction_results = self._predictor.predict(request_body)<br><br>        return Response(content=json.dumps(prediction_results))</pre><p><strong>predictor.py</strong></p><p>Most of the things are pre-defined and based on GCP recommendations but you can fit your custom logic within that</p><pre>from google.cloud.aiplatform.prediction.predictor import Predictor<br>from google.cloud.aiplatform.utils import prediction_utils<br><br><br>class CprPredictor(Predictor):<br><br>    def __init__(self):<br>        self.model = None<br><br>    def load(self, artifacts_uri: str):<br>        &quot;&quot;&quot;Load artifacts required for predictions<br>        Args:<br>            artifacts_uri (str): GCS path<br>        &quot;&quot;&quot;<br>        prediction_utils.download_model_artifacts(artifacts_uri)<br><br>        with open(os.path.join(&quot;model.pkl&quot;), &quot;rb&quot;) as inp:<br>            self.model = pickle.load(inp)<br><br><br>    def preprocess(self, prediction_input):<br>        &quot;&quot;&quot;_summary_<br>        put data pre-processing logic if any<br>        &quot;&quot;&quot;<br>        pass<br><br><br><br>    def predict(self, instances):<br>        &quot;&quot;&quot;Return prections<br><br>        Args:<br>            instances (dictionary): user request<br><br>        Returns:<br>            dictionary: predictions dictionary<br>        &quot;&quot;&quot;<br><br>        prediction_input = json.loads(instances)<br>        prediction_input = prediction_input[&quot;instances&quot;]<br><br>        # custom predictor setup<br>        prediction_input_df = pd.DataFrame(prediction_input, columns=[&quot;Age&quot;, &quot;Pclass&quot;, &quot;SibSp&quot;, &quot;Parch&quot;, &quot;Fare&quot;, &quot;Embarked&quot;])<br>        final_output = self.model.predict(prediction_input_df)<br><br>        return {&quot;predictions&quot;: final_output.tolist()}</pre><p><strong>endpointconfig.yaml</strong></p><pre>vertex-env-config: <br>    region: us-central1<br>    project_id: ***********<br><br>container-config:<br>    repository: training-prediction<br>    image: prediction<br>    source_dir: prediction<br>    <br>endpoint-config: <br>    endpoint_name_suffix: vertex_ai_endpoint<br>    instance_type: n1-standard-4<br>    endpoint_name: vertex_endpoint<br>    <br>model-config:<br>    model_artifact_dir: model<br>    model_display_name: vertex_endpoint<br>    bucket_uri: **************</pre><p><strong>createendpoint.py</strong></p><pre>def get_args():<br>    args_parser = argparse.ArgumentParser()<br>    args_parser.add_argument(<br>        &quot;--config_file_path&quot;, type=str, help=&quot;enter endpoint config file path&quot;<br>    )<br><br>    args = args_parser.parse_args()<br>    return args<br><br><br>def get_config(config_file_path):<br>    with open(config_file_path) as f:<br>        config = yaml.load(f, Loader=yaml.SafeLoader)<br>    return config<br><br><br>def build_push_prediction_container():<br>    &quot;&quot;&quot;_summary_<br>    CPR feature to create docker <br>    &quot;&quot;&quot;<br>    os.system(f&quot;gcloud auth configure-docker {region}-docker.pkg.dev --quiet&quot;)<br>    local_model = LocalModel.build_cpr_model(<br>        source_path,<br>        f&quot;{region}-docker.pkg.dev/{project_id}/{repository}/{image_name}&quot;,<br>        predictor=CprPredictor,<br>        handler=CprHandler,<br>        requirements_path=os.path.join(source_path, &quot;requirements.txt&quot;),<br>    )<br><br>    # pushing to docker image <br>    local_model.push_image()<br>    return local_model<br><br><br>def model_registry_upload(local_model):<br>    model = aiplatform.Model.upload(<br>        local_model=local_model,<br>        display_name=model_display_name,<br>        artifact_uri=f&quot;{bucket_uri}/{model_artifact_dir}&quot;,<br>        labels=labels,<br>    )<br>    return model<br><br><br>def create_endpoint():<br>    # check if endpoint exists<br>    endpoints = aiplatform.Endpoint.list(<br>        filter=&#39;display_name=&quot;{}&quot;&#39;.format(endpoint_name),<br>        order_by=&quot;create_time desc&quot;,<br>        project=project_id,<br>        location=region,<br>    )<br><br>    if len(endpoints) &gt; 0:<br>        # updating the endpoint <br>        endpoint = endpoints[0]  # most recently created#<br>        endpoint.update(display_name=endpoint_name, labels=labels)<br>    else:<br>        # creating the endpoint <br>        endpoint = aiplatform.Endpoint.create(<br>            display_name=endpoint_name,<br>            project=project_id,<br>            location=region,<br>            labels=labels,<br>        )<br>    return endpoint<br><br><br>def deploy_endpoint():<br>    # deploy updated model in endpoint<br>    model.deploy(endpoint=endpoint, machine_type=machine_type, traffic_percentage=100)<br><br>    # undeploy older model<br>    old_models = []<br>    for dep_model in endpoint.list_models():<br>        print(&quot;deployed model id&quot;, dep_model.id)<br>        print(&quot;traffic split&quot;, endpoint.traffic_split)<br><br>        if (dep_model.id not in endpoint.traffic_split) or (<br>            endpoint.traffic_split[dep_model.id] == 0<br>        ):<br>            old_models.append(dep_model.id)<br>            print(&quot;undeploying old model&quot;, dep_model.id)<br>            endpoint.undeploy(deployed_model_id=dep_model.id)<br><br><br># reading arguments and config file path <br>args = get_args()<br>config_file_path = vars(args)[&quot;config_file_path&quot;]<br>config = get_config(config_file_path)<br>region = config[&quot;vertex-env-config&quot;][&quot;region&quot;]<br>project_id = config[&quot;vertex-env-config&quot;][&quot;project_id&quot;]<br>labels = config[&quot;vertex-env-config&quot;][&quot;labels&quot;]<br>source_path = config[&quot;container-config&quot;][&quot;source_dir&quot;]<br>repository = config[&quot;container-config&quot;][&quot;repository&quot;]<br>image_name = config[&quot;container-config&quot;][&quot;image&quot;]<br>model_display_name = config[&quot;model-config&quot;][&quot;model_display_name&quot;]<br>model_artifact_dir = config[&quot;model-config&quot;][&quot;model_artifact_dir&quot;]<br>bucket_uri = config[&quot;model-config&quot;][&quot;bucket_uri&quot;]<br>endpoint_suffix = config[&quot;endpoint-config&quot;][&quot;endpoint_name_suffix&quot;]<br>machine_type = config[&quot;endpoint-config&quot;][&quot;instance_type&quot;]<br>endpoint_name = config[&quot;endpoint-config&quot;][&quot;endpoint_name&quot;]<br><br>print(&quot;#######################################&quot;)<br>print(f&quot;source path= {source_path}&quot;)<br>print(f&quot;image_path: {region}-docker.pkg.dev/{project_id}/{repository}/{image_name}&quot;)<br>print(f&quot;artifact_uri={bucket_uri}/{model_artifact_dir}&quot;)<br>print(&quot;model display name:&quot;, model_display_name)<br>print(&quot;endpoint name:&quot;, endpoint_name)<br>print(&quot;#######################################&quot;)<br><br><br># build and push docker container<br>local_model = build_push_prediction_container()<br><br># upload built container in model registry for deployment in endpoint <br>aiplatform.init(project=project_id, location=region)<br>model = model_registry_upload(local_model)<br><br># create endpoint <br>endpoint = create_endpoint()<br><br># deploy model to endpoint<br>deploy_endpoint()</pre><p>Create the endpoint using the below command</p><pre>python createendpoint.py --config_file_path endpointconfig.yaml</pre><p>you can see the entire progress via the local terminal, GCP console, or GCP logging</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vfOLpejzOqIsOTZVP18obw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mVPN5wxgIR8M5i0MADsgmg.png" /></figure><h3>Validation of endpoint</h3><p>you can get all the basic detail of the endpoint from here</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aBzrZTV6lbygsB6JuFYOAg.png" /></figure><p>here, vertex.ai provides multiple integration methods, you may create a python file like this to test the endpoint prediction functionality</p><p><strong>test_endpoint.py</strong></p><pre><br>def endpoint_predict(project: str, location: str, instances: dict, <br>                                                    endpoint: str):<br>    aiplatform.init(project=project, location=location)<br>    endpoint = aiplatform.Endpoint(endpoint)<br>    prediction = endpoint.predict(instances=instances)<br>    return prediction.predictions<br><br><br># sample payload to validation the prediction <br>payload = {&quot;Age&quot;: &quot;16&quot;, &quot;Pclass&quot;: &quot;3&quot;, &quot;SibSp&quot;: &quot;2&quot;,<br>           &quot;Parch&quot;: &quot;0&quot;, &quot;Fare&quot;: &quot;18.0&quot;, &quot;Embarked&quot;: &quot;2&quot;}<br>endpoint_id = &quot;************&quot;<br><br>start = time.time()<br><br># final prediction call <br>output = endpoint_predict(<br>    project=&quot;****************&quot;,<br>    endpoint=endpoint_id,<br>    location=&quot;us-central1&quot;,<br>    instances=[payload],<br>)<br><br>print(&quot;\n&quot;, output, &quot;\n&quot;)<br>print(&quot;time needed: &quot;, time.time() - start)</pre><p>once you execute this Python file, you will get results like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/556/1*HOaSqnLuixBo6rZzTsCr4g.png" /></figure><h3>References</h3><p>· <a href="https://cloud.google.com/vertex-ai">https://cloud.google.com/vertex-ai</a></p><p>· <a href="https://github.com/GoogleCloudPlatform/vertex-ai-samples/tree/main/notebooks/community">https://github.com/GoogleCloudPlatform/vertex-ai-samples/tree/main/notebooks/community</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e2e3c94ceae3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simplifying GenAI : Development to observability (OpenSource)]]></title>
            <link>https://medium.com/@vineetjaiswal/simplifying-genai-development-to-observability-opensource-b6ea61e0b0f8?source=rss-cb477254feab------2</link>
            <guid isPermaLink="false">https://medium.com/p/b6ea61e0b0f8</guid>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[langgraph]]></category>
            <category><![CDATA[langfuse]]></category>
            <dc:creator><![CDATA[Vineet Jaiswal]]></dc:creator>
            <pubDate>Mon, 30 Sep 2024 16:04:42 GMT</pubDate>
            <atom:updated>2024-10-01T07:45:08.401Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p5RORJ00YtwKflcR6p3l9w.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@mrnuclear?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">ZHENYU LUO</a> on <a href="https://unsplash.com/photos/a-room-with-many-machines-kE0JmtbvXxM?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a> hu</figcaption></figure><h3>Simplifying GenAI : Development to observability (OpenSource)</h3><p>Suppose we have this problem statement</p><p><em>“Create a system that classifies user input as sports or non-sports. Based on the classification, provide detailed sports info or relevant general knowledge tailored to the query.”</em></p><p>Consider, we already know we need to go via agentic workflow with GenAI, so next we are going to discuss how to build it with opensource stack which covers from development till observability.</p><p>A very high level view with key component details</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JqdUr8Lwq_3EnY9fAjgC5Q.jpeg" /><figcaption>Created by : Vineet Jaiswal</figcaption></figure><p>These are main tools which we are using for end to end process</p><p><a href="https://github.com/langchain-ai/langchain"><strong><em>LangChain</em></strong></a>: Most popular framework for developing applications powered by LLMs, offering chains to connect various components.</p><p><a href="https://github.com/langchain-ai/langgraph"><strong><em>LangGraph</em></strong></a><em>:</em> A library for building stateful, multi-actor applications with LLMs, used to create agent and multi-agent workflows.</p><p><a href="https://github.com/langfuse/langfuse"><strong><em>Langfuse</em></strong></a>: A observability tool for LLM-powered applications, providing detailed traces and performance insights.</p><h3><strong>Implementation</strong></h3><p>Assuming you’re already familiar with GenAI development, you’re now looking for an open-source ecosystem for production to help lower your production costs, you also need trace all LLM calls which you will use in future</p><p>let’s directly jump to the coding part of it, and with flow, let’s understand the eco-system, here are the key steps</p><h4>1. Graph creation using langgraph</h4><pre>graph = StateGraph(AgentState)  <br># Key aspect which hold agent state, and based on this, entire langgraph works <br>  <br># Add node (agents)<br>graph.add_node(&quot;classification_agent&quot;, classification_agent)  <br>graph.add_node(&quot;sports_agent&quot;, sports_agent)  <br>graph.add_node(&quot;non_sports_agent&quot;, non_sports_agent)  <br><br>graph.set_entry_point(&quot;classification_agent&quot;)  <br># Set the entry point of the graph to the classification agent<br><br># Add conditional edges (will explain _router in later section&#39;<br>graph.add_conditional_edges(<br>    &quot;classification_agent&quot;,  <br>    _router,  # Routing function to determine the next agent<br>    {&quot;sports_agent&quot;: &quot;sports_agent&quot;, &quot;non_sports_agent&quot;: &quot;non_sports_agent&quot;},  <br>    # Mapping of classification results to agents<br>)<br><br># Define the end points<br>graph.add_edge(&quot;sports_agent&quot;, END)  <br>graph.add_edge(&quot;non_sports_agent&quot;, END)  <br>  <br>app = graph.compile()  # Compile the graph into an executable application<br><br># when you want to execute it<br>output_data = app.invoke(inputs)  # Invoke the application with the prepared inputs<br>final_success_message = output_data.get(&quot;messages&quot;)[-1]  # Retrieve the final message from agent state</pre><ul><li>StateGraph is something, which actually passes to each agents and it hold the entire execution states, this is AgentState class</li></ul><pre>class AgentState(TypedDict):<br>    messages: Annotated[Sequence[BaseMessage], operator.add]</pre><ul><li>Edge and Nodes are conventional graph concepts</li><li>_router is defining condition edge, in general its defining all routing among agents, simple code which just pass message content</li></ul><pre>def _router(state):<br>    messages = state[&quot;messages&quot;]<br>    last_message = messages[-1]<br>    return last_message.content</pre><p>the simplified graph</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/842/1*ASE6SBGaHhBX3NTCSupPUA.png" /></figure><h4>2. Agent Creation with langchain</h4><p>the simple agent is like this (Without langfuse for now)</p><pre><br>def classification_agent(state):<br>    messages = state.get(&quot;messages&quot;)<br>    question = messages[-1]<br>    print(f&quot;inside classification_agent {question}&quot;)<br>    llm = ChatOpenAI(temperature=0.7)<br>    prompt = ChatPromptTemplate.from_messages(<br>        [<br>            (&quot;system&quot;, &quot;you are an AI bot who can classify&quot;),<br>            (<br>                &quot;user&quot;,<br>                &quot;classify input either in sports_agent if related to sports or non_sports_agent if not related to sports category, input: {question}&quot;,<br>            ),<br>        ]<br>    )<br>    retrieval_chain = {&quot;question&quot;: RunnablePassthrough()} | prompt | llm<br>    output_data = retrieval_chain.invoke(<br>        {&quot;question&quot;: question},<br>    )<br>    print(f&quot;classification_agent output: {output_data}&quot;)<br>    return {&quot;messages&quot;: [output_data]}<br><br>def sports_agent(state):<br>    messages = state.get(&quot;messages&quot;)<br>    question = messages[0]<br>    llm = ChatOpenAI(temperature=0.7)<br>    print(f&quot;inside sports_agent {question}&quot;)<br>    prompt = ChatPromptTemplate.from_messages(<br>        [<br>            (&quot;system&quot;, &quot;you are an AI bot who can generate more details&quot;),<br>            (&quot;user&quot;, &quot;Give me top 10 world cup winner team in json format  for : {question}&quot;),<br>        ]<br>    )<br>    retrieval_chain = {&quot;question&quot;: RunnablePassthrough()} | prompt | llm<br>    output_data = retrieval_chain.invoke(<br>        {&quot;question&quot;: question},<br>    )<br><br>    return {&quot;messages&quot;: [output_data]}<br><br>def non_sports_agent(state):<br>    messages = state.get(&quot;messages&quot;)<br>    question = messages[0]<br>    llm = ChatOpenAI(temperature=0.7)<br>    print(f&quot;inside non_sports_agent {non_sports_agent}&quot;)<br>    prompt = ChatPromptTemplate.from_messages(<br>        [<br>            (&quot;system&quot;, &quot;you are an AI bot who can generate more details&quot;),<br>            (&quot;user&quot;, &quot;give me more detail from wikipedia for : {question}&quot;),<br>        ]<br>    )<br>    retrieval_chain = {&quot;question&quot;: RunnablePassthrough()} | prompt | llm<br>    output_data = retrieval_chain.invoke(<br>        {&quot;question&quot;: question},<br>    )<br>    return {&quot;messages&quot;: [output_data]}</pre><p>very simple langchain based agents, one for classifiy and rest for specific agentic workflow</p><h4>3. Integration with Langfuse</h4><p>Assuming you already setup langfuse and you have access on its dashboard, looks like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/892/1*W0wDimgJk83j6PDg-s0Y7w.png" /><figcaption>From : <a href="https://langfuse.com/">https://langfuse.com/</a></figcaption></figure><p>there are two methods to implement, you can use both or one of them, here are examples</p><p><strong>3.1 With decorators method</strong></p><p>you need to pass python decorator over the methods like this</p><pre>@observe() # over main thread or unit of one logical operation<br>@observe(as_type=&quot;generation&quot;) # where you actually generate something </pre><p>you can also extend it like (code inside the method)</p><pre>langfuse_context.update_current_observation(<br>      usage={<br>          &quot;input&quot;: response.usage.input_tokens,<br>          &quot;output&quot;: response.usage.output_tokens<br>      }<br>  )</pre><p>the output looks like this, entire trace of request with all input/output detail like below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kbS70YvFi_ttzcKbfAPJyQ.png" /><figcaption>Created by : Vineet Jaiswal</figcaption></figure><p><strong>3.2 With CallbackHandler</strong></p><p>you need to defined callback handler like this</p><pre>def create_handler(user_identifier, trace_name):<br>    langfuse_handler = CallbackHandler(<br>        session_id=user_identifier,<br>        metadata={&quot;a&quot;: &quot;b&quot;},<br>        trace_name=trace_name,<br>    )<br>    return langfuse_handler</pre><p>and while calling the agents, add some more metadata and pass it will llm chains, complete example</p><pre>def non_sports_agent_generation(llm, prompt, question, langfuse_handler):<br>    retrieval_chain = {&quot;question&quot;: RunnablePassthrough()} | prompt | llm<br>    output_data = retrieval_chain.invoke(<br>        {&quot;question&quot;: question},<br>        config={<br>            &quot;callbacks&quot;: [langfuse_handler],<br>        },<br>    )<br><br>    return output_data</pre><p>you can more detailed and formatted observability for such handers like</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V_zdbkFCj2OQqTXO963cYg.png" /><figcaption>Created by : Vineet Jaiswal</figcaption></figure><p>you can find entire code : <a href="https://github.com/jaiswalvineet/langchain_langgraph_langfuse">https://github.com/jaiswalvineet/langchain_langgraph_langfuse</a></p><p>the entire execution looks like</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eAeVOuahb2kG1XfHSdNfkQ.png" /><figcaption>Created by : Vineet Jaiswal</figcaption></figure><h3>Conclusion</h3><p>With all the above implementations, you can build a complete open-source platform ready for enterprise-grade adoption.</p><p>Just to ensure it’s easy to understand for beginner users, I’ve used simple examples, which may not be the most optimized. So, please review the details carefully before using them. Also, I used the paid OpenAI LLM for simplicity, but you can use any open-source LLM, such as Llama, etc.</p><p>Comments and feedback are most welcome. Let me know if you’d like further refinements!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b6ea61e0b0f8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The rise of full-stack data professionals]]></title>
            <link>https://medium.com/@vineetjaiswal/the-rise-of-full-stack-data-professionals-1c36d5bf47b1?source=rss-cb477254feab------2</link>
            <guid isPermaLink="false">https://medium.com/p/1c36d5bf47b1</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Vineet Jaiswal]]></dc:creator>
            <pubDate>Tue, 23 May 2023 07:01:35 GMT</pubDate>
            <atom:updated>2023-05-23T07:01:35.160Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WaiNorcQoMjoWatpiMoaWw.png" /><figcaption>Typical data-related roles in the IT industry</figcaption></figure><p>Full-stack data professional: The one who can participate in all aspects associated with any data-centric applications, from start to finish, might only be excellent in some aspects but can learn and implement the rest as per demand. In this blog, I am focusing on why such professionals are needed in the current scenario.</p><p>If you go with the current data world for applied science(consider it as non-research organizations) place, you will majorly find these header image positions, and if you want to see it combined</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/1*WBTpFrTTV4SXkiWewNxx9w.png" /></figure><p>you can clearly see four different segments, and these are majorly titled <strong>Data Engineering(DE)</strong>, <strong>Data Analyst(DA)</strong>, <strong>Data Scientist(DS),</strong> and <strong>Machine Learning Engineer(MLE)</strong> meanwhile one minor section called <strong>Citizen Data Scientist(CDS) </strong>was recently introduced to do basic data scientist work till the project not staffed some specialist data scientist. Apart from that, a few additional roles also help the entire process like statisticians, application developers, front-end developers, cloud developers, testers, program managers, etc.</p><p>let’s analyze each major role with a work profile and the missing things for that role</p><h3>Data Engineer</h3><p><strong>key role and responsibilities</strong></p><ul><li>Data collection: gathering data from a variety of sources and managing its integration</li><li>Data-related infra management: to support storing, processing, transforming, and loading of the data efficient and secure way</li><li>Automated pipelines: orchestrate entire data pipelines including machine learning pipelines</li><li>Transformation of data: as per the consumer like DS, DA, and other need</li><li>Governance, Lineage, Compliance, Security: to support all standard enterprise process</li></ul><p><strong>What missing</strong></p><ul><li>This person does all the data processing but most of the time works in silos and is not much aware of the inception of that need and also the use of most of the changes</li><li>Not much aware of other people&#39;s work in the team, doing most engineering-heavy jobs but not the cognitive or business side of work</li></ul><h3>Data Scientist</h3><p><strong>key role and responsibilities</strong></p><ul><li>Exploratory data analysis: to understand more about the data and its hidden capability, also share the possibilities with the client with data points</li><li>Data pre-processing and Feature engineering: to enhance the quality of the data and create derived attributes</li><li>ML experiments and model development: Core work of any data scientist to hit and try with multiple algorithms and engineer a core solution to fulfill a business need</li><li>Model Evaluation and business acceptance: its continuous process to improve the model with respect to changing data attributes</li><li>Monitor and enhancement: validate the model performance in real-world scenarios</li></ul><p><strong>What missing</strong></p><ul><li>Most of the engineering work is done by someone else, and sometimes missing to calculate the non-technical factors like infra cost, return on investment, value proposition, and actual use case acceptance</li><li>For data and automation of work, dependent on other people like Data engineers or cloud engineer</li></ul><h3>Data Analyst</h3><p><strong>key role and responsibilities</strong></p><ul><li>Data analysis: to understand data patterns, share valuable information with the client, and find data that help in decision making</li><li>Data visualization: to create a simplified view of the larger dataset to identify the key findings of the entire data and keep it most updated</li><li>Business Reporting: directly interact with clients and create a required business report and provide supporting data points, like an Analytics report</li></ul><p><strong>What missing</strong></p><ul><li>Most of the engineering, cognitive, and application-related space</li><li>Mostly work on specified tools like PowerBI, Google Analytics etc, and does not have that good hands-on programming skills</li></ul><h3>ML Engineer</h3><p><strong>key role and responsibilities</strong></p><ul><li>Training on the scale: to utilize the most optimum and efficient infra and related process, utilize cloud capabilities</li><li>Serving on the scale: to cope with changing end use-case demand and best utilization of cloud infrastructure</li><li>Monitoring and MLOps: to monitor all kinds of performance and end-to-end MLOps</li></ul><p><strong>What missing</strong></p><ul><li>Most of the model development process and also not much involved with an entire background of development</li><li>Missing the business context and data key knowledge and much focused on the ML engineering part</li></ul><p>Other than that, in general, all profiles are missing API development or Serverless function development process, which is pretty much required to make ML service consumable for any external applications</p><h3>Where does the world want to move?</h3><p>One thing is for sure, all the above fields are almost the entire world if anyone wants to go into deep, especially data science where almost every day we have tons of new updates and there is no limit to knowledge.</p><p>But with recent changes where most of the cloud providers and other players like OpenAI, Bard etc are starting to give their end-to-end services via simple API interfaces, where most of the non-data background developers/practitioners can also do most things or at least they can start up to a certain level.</p><p>I believe that the existence of data professionals is not the main issue, but rather an opportunity to learn something new in the field of data itself so that it&#39;s not limited to only one aspect of the entire data journey. If someone is not very much deep in research or a specialization like NLP, Computer Vision etc, <strong>the person should also learn the end-to-end of the entire journey</strong> and learn the basics of each journey aspect or at least <strong>stop saying no to learning opportunities.</strong></p><p>As a data professional, cloud computing is as essential as wring spark code as a data engineer or doing data pre-processing as Data Scientist. The world is going in a direction where writing infra as code (like terraform scripts) and writing API (like Lambda/Cloud functions), are also expected from the same person.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*rE0AT_qzLXGbtpwAN9y1Dw.png" /></figure><p>Above is the diagram, where you can see an orange circle in the middle, this represents a full-stack data professional who is not an expert in all the fields but has more acceptability in the industry, it&#39;s not mandatory as of now in the industry but just give a thought, <strong>why enterprise should not need such profiles</strong> in the era of clouds and API.</p><p>based on my last few years of experience in the data world and the recent interruption with OpenAI, it seems the demand for full-stack data professionals is growing, <strong>businesses become more data-driven, and they are looking for professionals who can help them make sense of their data but with the thin team initially.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1c36d5bf47b1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Romancing with pandas]]></title>
            <link>https://blog.gopenai.com/romancing-with-pandas-3d254593fc16?source=rss-cb477254feab------2</link>
            <guid isPermaLink="false">https://medium.com/p/3d254593fc16</guid>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[cheatsheet]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Vineet Jaiswal]]></dc:creator>
            <pubDate>Tue, 04 Apr 2023 09:32:23 GMT</pubDate>
            <atom:updated>2023-04-05T15:44:29.178Z</atom:updated>
            <content:encoded><![CDATA[<p>If you are in Data Science and using Python as a basic tool, you must be aware of Pandas, so I am directly jumping to the topic.</p><p>The main intent in creating this doc is to have all basic panda offerings in one place so we don’t need to search a lot of places once we need them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6nrbWvYrfk22PbgV4fhroQ.png" /></figure><p>list of offerings in different segments</p><h3>Data structures:</h3><h4>Series Methods:</h4><ul><li>series = pd.Series(data): creates a new series object from an array or list of data.</li><li>series.values: returns the values of the series as a NumPy array.</li><li>series.index: returns the index of the series.</li><li>series.head(n): returns the first n rows of the series.</li><li>series.tail(n): returns the last n rows of the series.</li><li>series.describe(): provides summary statistics of the series.</li><li>series.unique(): returns the unique values in the series.</li><li>series.isnull(): returns a Boolean mask indicating which values are null.</li><li>series.dropna(): returns a new series with null values removed.</li><li>df.drop(columns=[&#39;column_name&#39;]): drops a column from the DataFrame.</li><li>series.fillna(value): returns a new series with null values filled with the specified value.</li></ul><h4>DataFrame Methods:</h4><ul><li>df = pd.DataFrame(data): creates a new DataFrame object from a dictionary, NumPy array, or list of dictionaries.</li><li>df.columns: returns the column labels of the DataFrame.</li><li>df.index: returns the row labels of the DataFrame.</li><li>df.memory_usage : return the memory usage of each column in bytes.</li><li>df.head(n): returns the first n rows of the DataFrame.</li><li>df.tail(n): returns the last n rows of the DataFrame.</li><li>df.shape: returns a tuple representing the dimensions of the DataFrame.</li><li>df.info(): provides information about the DataFrame</li><li>df.describe(): provides summary statistics of the DataFrame.</li><li>df.groupby(column): groups the DataFrame by the specified column.</li><li>df.merge(other_df): merges the DataFrame with another DataFrame based on a common column.</li><li>df.pivot_table(): creates a pivot table from the DataFrame.</li></ul><h3>Statistical analysis:</h3><h4>Descriptive statistics:</h4><ul><li>df.mean(): calculates the mean</li><li>df.median(): calculates the median</li><li>df.mode(): calculates the mode</li></ul><h4>Correlation and covariance:</h4><ul><li>df.corr(): calculates the correlation between columns</li><li>df.cov(): calculates the covariance between columns</li></ul><h4>Outlier detection:</h4><ul><li>df.quantile(0.25): calculates the first quartile</li></ul><h3>Data cleaning:</h3><h4>Handling missing values:</h4><ul><li>df.isnull(): returns a DataFrame with Boolean values indicating which cells contain missing values.</li><li>df.dropna(): returns a new DataFrame with null values removed.</li><li>df.fillna(value): fills all missing values with a specified value.</li><li>df.interpolate(method=&#39;linear&#39;): Fill NaN values using an interpolation method</li></ul><h4>Handling duplicates:</h4><ul><li>df.duplicated(): returns a Boolean Series indicating which rows are duplicates.</li><li>df.drop_duplicates(): removes all duplicate rows.</li></ul><h4>Data type conversion:</h4><ul><li>df.astype(): converts the data type of a DataFrame column to a specified data type.</li></ul><h4>String manipulation:</h4><ul><li>str.replace(old, new): replaces all occurrences of a specified string with another string.</li><li>str.split(): splits a string into a list of substrings.</li><li>str.strip(): removes leading and trailing whitespace from a string.</li></ul><h4>Handling outliers:</h4><ul><li>df.clip(lower, upper): clips all values in the DataFrame to be within a specified range.</li></ul><h4>Renaming columns:</h4><ul><li>df.rename(columns={&#39;old_name&#39;: &#39;new_name&#39;}): renames a column in the DataFrame.</li></ul><h4>Handling whitespace and capitalization:</h4><ul><li>str.lower(): converts all characters in a string to lowercase.</li><li>str.upper(): converts all characters in a string to uppercase.</li><li>str.strip(): removes leading and trailing whitespace from a string.</li></ul><h4>Data normalization:</h4><ul><li>df.apply(function): applies a function to each element in a DataFrame.</li><li>df.mean(): calculates the mean of each column in the DataFrame.</li><li>df.std(): calculates the standard deviation of each column in the DataFrame.</li></ul><h3>Data manipulation:</h3><h4>Filtering data:</h4><ul><li>df.loc[condition]: returns rows of the DataFrame that meet the specified condition.</li><li>df.query(condition): returns rows of the DataFrame that meet the specified condition using a query string.</li></ul><h4>Sorting data:</h4><ul><li>df.sort_values(by=column): sorts the DataFrame by the specified column.</li><li>df.sort_index(): sorts the DataFrame by the index.</li></ul><h4>Grouping data:</h4><ul><li>df.groupby(column): groups the DataFrame by the specified column.</li><li>grouped.aggregate(function): applies an aggregation function to each group.</li></ul><h4>Joining and merging data:</h4><ul><li>df.merge(other_df): merges the DataFrame with another DataFrame based on a common column.</li><li>df.join(other_df): joins the DataFrame with another DataFrame based on the index.</li><li>pd.concat([df1, df2]): concatenates two or more DataFrames together.</li><li>df1.append(df2): appends one DataFrame to another DataFrame.</li></ul><h4>Reshaping data:</h4><ul><li>df.melt(id_vars=column): unpivots the DataFrame from wide format to long format.</li><li>df.pivot(index, columns, values): creates a new DataFrame with the specified index, columns, and values.</li><li>df.stack(): pivots the DataFrame from wide format to long format.</li></ul><h4>Aggregating data:</h4><ul><li>df.groupby(column).sum(): calculates the sum of each group.</li><li>df.groupby(column).mean(): calculates the mean of each group.</li><li>df.groupby(column).max(): calculates the maximum of each group.</li></ul><h4>Window functions:</h4><ul><li>df.rolling(window).mean(): calculates the rolling mean of a column.</li><li>df.expanding().sum(): calculates the expanding sum of a column.</li></ul><h3>Text data processing:</h3><h4>String manipulation:</h4><ul><li>df[&#39;column_name&#39;].str.lower(): converts all characters in a column to lowercase.</li><li>df[&#39;column_name&#39;].str.upper(): converts all characters in a column to uppercase.</li><li>df[&#39;column_name&#39;].str.strip(): removes leading and trailing whitespace from a column.</li><li>df[&#39;column_name&#39;].str.replace(&#39;old_value&#39;, &#39;new_value&#39;): replaces all occurrences of a value in a column with a new value.</li></ul><h4>Regular expressions:</h4><ul><li>df[&#39;column_name&#39;].str.contains(&#39;pattern&#39;): checks whether each element in a column matches a regular expression pattern.</li><li>df[&#39;column_name&#39;].str.extract(&#39;pattern&#39;): extracts the first occurrence of a regular expression pattern from each element in a column.</li></ul><h4>Tokenization:</h4><ul><li>df[&#39;column_name&#39;].str.split(&#39;delimiter&#39;): splits each element in a column into a list of tokens, based on a delimiter.</li></ul><h4>Filtering:</h4><ul><li>df[df[&#39;column_name&#39;].str.contains(&#39;pattern&#39;)]: filters rows in a DataFrame based on whether a regular expression pattern matches a value in a column.</li><li>df[df[&#39;column_name&#39;].str.len() &gt; 10]: filters rows in a DataFrame based on the length of a value in a column.</li></ul><h4>Vectorized string methods:</h4><ul><li>df[&#39;column_name&#39;].str.cat(sep=&#39;delimiter&#39;): concatenates all elements in a column into a single string, separated by a delimiter.</li><li>df[&#39;column_name&#39;].str.get_dummies(): creates a one-hot encoded DataFrame from a column containing multiple categorical values.</li></ul><h3>Data visualization:</h3><p>Line charts:</p><ul><li>df.plot(): creates a line chart of the DataFrame.</li></ul><h4>Bar charts:</h4><ul><li>df.plot(kind=&#39;bar&#39;): creates a vertical bar chart of the DataFrame.</li><li>df.plot(kind=&#39;barh&#39;): creates a horizontal bar chart of the DataFrame.</li></ul><h4>Pie charts:</h4><ul><li>df.plot(kind=&#39;pie&#39;): creates a pie chart of the DataFrame.</li></ul><h4>Scatter plots:</h4><ul><li>df.plot(kind=&#39;scatter&#39;, x=&#39;column1&#39;, y=&#39;column2&#39;): creates a scatter plot of two columns in the DataFrame.</li></ul><h4>Histograms:</h4><ul><li>df.plot(kind=&#39;hist&#39;): creates a histogram of the DataFrame.</li></ul><h4>Box plots:</h4><ul><li>df.plot(kind=&#39;box&#39;): creates a box plot of the DataFrame.</li></ul><h4>Area charts:</h4><ul><li>df.plot(kind=&#39;area&#39;): creates an area chart of the DataFrame.</li></ul><h3>Data input and output:</h3><h4>Reading data:</h4><ul><li>pd.read_csv(file_path): reads data from a CSV file into a DataFrame.</li><li>pd.read_excel(file_path): reads data from an Excel file into a DataFrame.</li><li>pd.read_sql(query, connection): reads data from a SQL database into a DataFrame.</li><li>pd.read_json(file_path): reads data from a JSON file into a DataFrame.</li><li>pd.read_html(url): reads data from an HTML page into a list of DataFrames.</li><li>pd.read_clipboard(): reads data from the clipboard into a DataFrame.</li></ul><h4>Writing data:</h4><ul><li>df.to_csv(file_path): writes data from a DataFrame to a CSV file.</li><li>df.to_excel(file_path): writes data from a DataFrame to an Excel file.</li><li>df.to_sql(table_name, connection): writes data from a DataFrame to a SQL database table.</li><li>df.to_json(file_path): writes data from a DataFrame to a JSON file.</li></ul><h3>Time series analysis:</h3><h4>Time indexing:</h4><ul><li>pd.to_datetime(date_string): converts a date string to a datetime object.</li><li>df.set_index(&#39;datetime_column&#39;): sets a datetime column as the index of the DataFrame.</li></ul><h4>Resampling:</h4><ul><li>df.resample(&#39;D&#39;).mean(): resamples a DataFrame to a daily frequency and calculates the mean for each day.</li><li>df.resample(&#39;M&#39;).sum(): resamples a DataFrame to a monthly frequency and calculates the sum for each month.</li></ul><h4>Shifting:</h4><ul><li>df.shift(1): shifts the values in a DataFrame by one period.</li></ul><h4>Rolling:</h4><ul><li>df.rolling(window=2).mean(): calculates a rolling mean of the DataFrame over a window of two periods.</li></ul><h4>Time zone handling:</h4><ul><li>df.tz_localize(&#39;UTC&#39;): sets the time zone of a DataFrame to UTC.</li><li>df.tz_convert(&#39;US/Pacific&#39;): converts the time zone of a DataFrame to US Pacific.</li></ul><h4>Date range generation:</h4><ul><li>pd.date_range(start=&#39;2020-01-01&#39;, end=&#39;2020-12-31&#39;, freq=&#39;D&#39;): generates a range of dates from January 1, 2020 to December 31, 2020 with a daily frequency.</li></ul><h3>Machine learning integration:</h3><h4>Feature engineering:</h4><ul><li>df[&#39;new_column&#39;] = df[&#39;column_1&#39;] + df[&#39;column_2&#39;]: creates a new column by adding two existing columns.</li><li>df[&#39;new_column&#39;] = df[&#39;column&#39;].apply(function): applies a function to each value in a column to create a new column.</li><li>df[&#39;new_column&#39;] = pd.cut(df[&#39;column&#39;], bins): creates a new column by binning a continuous variable.</li></ul><h3>Conclusion</h3><p>These are a list of a few regularly used methods, but pandas have much more to offer. Please go through the official pandas’ documentation for more detailed knowledge. Also, all these methods are subject to change based on the new pandas release so please check on the official release before actually using it.</p><h3>Reference</h3><ul><li><a href="https://pandas.pydata.org/">pandas</a></li><li><a href="https://pandas.pydata.org/docs/user_guide/index.html">User Guide - pandas 2.3.3 documentation</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3d254593fc16" width="1" height="1" alt=""><hr><p><a href="https://blog.gopenai.com/romancing-with-pandas-3d254593fc16">Romancing with pandas</a> was originally published in <a href="https://blog.gopenai.com/">GoPenAI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction & Comparison of MLOps platforms: AWS Sagemaker, Azure Machine Learning, GCP Vertex AI]]></title>
            <link>https://medium.com/analytics-vidhya/introduction-comparison-of-mlops-platforms-aws-sagemaker-azure-machine-learning-gcp-vertex-ai-9c1153399c8e?source=rss-cb477254feab------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c1153399c8e</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[azure-machine-learning]]></category>
            <category><![CDATA[vertex-ai]]></category>
            <category><![CDATA[sagemaker]]></category>
            <dc:creator><![CDATA[Vineet Jaiswal]]></dc:creator>
            <pubDate>Sat, 04 Dec 2021 08:32:33 GMT</pubDate>
            <atom:updated>2022-02-24T06:00:46.034Z</atom:updated>
            <content:encoded><![CDATA[<p>A lot of non-IT organizations are now moving into Artificial Intelligence(AI) and Cognitive Science world, and instead of luxury, it become new normal. This AI concept is not new, <a href="https://en.wikipedia.org/wiki/Alan_Turing">Alan Turing</a>, known as the father of AI, built a machine on the same concept while he was working on Enigma or other <a href="https://en.wikipedia.org/wiki/Computing_Machinery_and_Intelligence">papers</a> before 1950. That time it was about the future and now we are living in that time ‘future’, where AI is too mainstream that no one can’t avoid it.</p><h3>Why MLOps important?</h3><p>If any non-IT companies want to move in AI, they find it very difficult to move and manage any deliverables in the production environment, forget the Machine Learning(ML) model and feedback loops, even if you read the famous paper <a href="https://proceedings.neurips.cc/paper/2015/file/86df7dcfd896fcaf2674f757a2463eba-Paper.pdf">Hidden Technical Debt in Machine Learning Systems</a>, by Google, you can imagine how much the actual model development &amp; training contribute in the entire process, the just focus on the small black box in the below diagram</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qidpJTQcxC6NZlGld_DoZw.png" /><figcaption><a href="https://proceedings.neurips.cc/paper/2015/file/86df7dcfd896fcaf2674f757a2463eba-Paper.pdf">https://proceedings.neurips.cc/paper/2015/file/86df7dcfd896fcaf2674f757a2463eba-Paper.pdf</a></figcaption></figure><p>the ML portion is barely 10% of the entire journey, and now that organization wants to learn and manage everything, so they will manage their dependent business as usual. If we want to look in this spectrum with more specific and relatable terms, here are the key components</p><figure><img alt="Machine Learning Life-Cycle" src="https://cdn-images-1.medium.com/max/1024/1*Hf_ZyJsC2xqr0v3TBYNgTg.jpeg" /></figure><p>A lot of such organization are using any Cloud services, specifically from the big three (<a href="https://aws.amazon.com/">AWS</a>, <a href="https://azure.microsoft.com/">Azure</a>, and <a href="https://cloud.google.com/">GCP</a>) and they are providing managed services based offerings like search, image processing, speech offerings, etc, but when these organization wants to make something by their own, they start feeling the need of end-to-end ML eco-system, where they can manage starting from data capturing to final model monitoring (entire lifecycle), and a lot of open-source, small vender grab this spaces, key mentions</p><p><a href="https://www.kubeflow.org/docs/started/installing-kubeflow/"><em>KubeFlow</em></a>, <a href="https://mlflow.org/"><em>MLFlow</em></a>, <a href="https://www.dataiku.com/"><em>Dataiku</em></a>, <a href="https://c3.ai/"><em>C3.ai</em></a>, <a href="https://algorithmia.com/"><em>Algorithmia</em></a>, <a href="https://www.datarobot.com/"><em>Datarobot.com</em></a>, <a href="https://www.h2o.ai/"><em>H20.ai</em></a>, <a href="https://www.pachyderm.com/"><em>Pachyderm</em></a></p><p>If you go to these kinds of platforms&#39; websites, we can see the amount of space they have already captured, so the big cloud providers also start feeling the heat and they released their offerings on the same lines, so their customers don’t need to go to other data platforms.</p><h3>Example Use Case</h3><p>Just to make it more relatable, Let’s take any generic IoT based example from data collection to final API, generic implementation on big three cloud platforms or open-source, the journey looks something like this</p><figure><img alt="Machine learning process via AWS Sagemaker, Azure Machine Learning and GCP Vertex.ai" src="https://cdn-images-1.medium.com/max/1024/1*5GG0okT6xCEkAS9ic-KeyQ.jpeg" /></figure><p>In the above diagram, the <strong>machine learning</strong> portion has MLOps offering from all three providers, which is actually giving us a managed platform that will do major <strong>Infra and DevOps level heavy lifting</strong> so the development team will majorly focus on core domain work.</p><p>Now, the ultimate vision of these managed platforms, to <strong>do other segment work</strong> too like we can create a pipeline, feature engineering, API interface, monitoring etc via the same platform, so it will become a single point of tool for all custom data &amp; machines learning need.</p><p>In summary, MLOps is focused on the operationalization of ML models, while ModelOps covers the operationalization of all types of AI model, more concept about MLOps: <a href="https://en.wikipedia.org/wiki/MLOps">https://en.wikipedia.org/wiki/MLOps</a></p><h3>Big Three Comparision</h3><p>Finally, we are here</p><p>As usual, AWS came first in this MLOps space via <a href="https://aws.amazon.com/sagemaker/">AWS Sagemaker</a>, followed by <a href="https://azure.microsoft.com/en-in/services/machine-learning/">Azure Machine Learning </a>and recently <a href="https://cloud.google.com/vertex-ai">GCP Vertex.ai</a>, and because they are coming from these cloud providers, they already covered all major MLOps aspects, here a comparison based on my knowledge</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*s5eSap5mNsaD_NNdncYQEA.png" /></figure><h3>Final Words</h3><p>Technically, all of them are equally capable can be for all MLOps need, either via inbuilt feature or via custom implementation and any organization can easily go with their default cloud provider, but if the client is using a hybrid cloud setup, or wants to do any comparison, or want to know the key feature list, then above article can give some idea.</p><p>I personally used all three on the enterprise-scale and above analysis based on my personal and limited exposure with these tools, also these are evolving so fast so please validate it before quoting it anywhere, also let me know if I am missing or I need to update anything here.</p><h3>Reference:</h3><ol><li><a href="https://en.wikipedia.org/wiki/Alan_Turing">https://en.wikipedia.org/wiki/Alan_Turing</a></li><li><a href="https://en.wikipedia.org/wiki/Computing_Machinery_and_Intelligence">https://en.wikipedia.org/wiki/Computing_Machinery_and_Intelligence</a></li><li><a href="https://proceedings.neurips.cc/paper/2015/file/86df7dcfd896fcaf2674f757a2463eba-Paper.pdf">https://proceedings.neurips.cc/paper/2015/file/86df7dcfd896fcaf2674f757a2463eba-Paper.pdf</a></li><li><a href="https://en.wikipedia.org/wiki/MLOps">https://en.wikipedia.org/wiki/MLOps</a></li><li><a href="https://aws.amazon.com/">https://aws.amazon.com/</a></li><li><a href="https://azure.microsoft.com/">https://azure.microsoft.com/</a></li><li><a href="https://cloud.google.com/">https://cloud.google.com/</a></li><li><a href="https://www.kubeflow.org/docs/started/installing-kubeflow/">https://www.kubeflow.org/docs/started/installing-kubeflow/</a></li><li><a href="https://mlflow.org/">https://mlflow.org/</a></li><li><a href="https://www.dataiku.com/">https://www.dataiku.com/</a></li><li><a href="https://c3.ai/">https://c3.ai/</a></li><li><a href="https://algorithmia.com/">https://algorithmia.com/</a></li><li><a href="https://www.datarobot.com/">https://www.datarobot.com/</a></li><li><a href="https://www.pachyderm.com/">https://www.pachyderm.com/</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9c1153399c8e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/introduction-comparison-of-mlops-platforms-aws-sagemaker-azure-machine-learning-gcp-vertex-ai-9c1153399c8e">Introduction &amp; Comparison of MLOps platforms: AWS Sagemaker, Azure Machine Learning, GCP Vertex AI</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NLP Language Models BERT, GPT2, T-NLG: Changing the rules of the game]]></title>
            <link>https://medium.com/analytics-vidhya/nlp-language-models-bert-gpt2-t-nlg-changing-the-rules-of-the-game-3334b23020a9?source=rss-cb477254feab------2</link>
            <guid isPermaLink="false">https://medium.com/p/3334b23020a9</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[Vineet Jaiswal]]></dc:creator>
            <pubDate>Wed, 19 Aug 2020 07:25:31 GMT</pubDate>
            <atom:updated>2020-08-19T14:45:45.736Z</atom:updated>
            <content:encoded><![CDATA[<h3>NLP Language Models BERT, GPT2/3, T-NLG: Changing the rules of the game</h3><p>Summary: key concepts of popular language model capabilities</p><p>We all are aware about the current revolution in field of <a href="https://en.wikipedia.org/wiki/Artificial_intelligence">Artificial Intelligence</a>(AI) and <a href="https://en.wikipedia.org/wiki/Natural_language_processing">Natural Language Processing</a>(NLP) is one of the major contributor.</p><p>For the NLP related tasks, where we build technique related to human and computer interaction, we first develop a language specific understanding in our machine so it can extract some context out of the training data. This is also the first basic things in our parenting, our babies first understand the language then we start giving complex task gradually.</p><p>In the conventional world, we need to nurture each baby individually but on other hand if you take example of of any subject like Physics, a lot of people contributed so far and we have predefined ecosystem like books, universities to pass the earned knowledge to next person. Our conventional NLP language model was similar like this only, everyone needs to develop their own language understanding using some technique but no one can leverage others work. The <a href="https://en.wikipedia.org/wiki/Computer_vision">computer vision</a> division of AI, already achieved this using their <a href="https://en.wikipedia.org/wiki/ImageNet">ImageNet </a>object data set. This concept is called <a href="https://en.wikipedia.org/wiki/Transfer_learning">Transfer Learning</a>. As per Wikipedia</p><blockquote>Transfer learning (TL) is a research problem in machine learning (ML) that focuses on storing knowledge gained while solving one problem and applying it to a different but related problem. For example, knowledge gained while learning to recognize cars could apply when trying to recognize trucks.</blockquote><p>To reduce a lot of repetitive time intensive, cost unfriendly and compute intensive task, A lot of major companies was working on such language model, where someone can leverage their langua ge understanding but <a href="https://github.com/google-research/bert">BERT </a>from Google is major defining moment, which almost changed this industry. before that the popular one was <a href="https://allennlp.org/elmo">ELMo </a>and <a href="https://openai.com/blog/better-language-models/">GPT</a>.</p><p>Before going to these language model, we must understand few key concepts</p><p><strong>Embedding </strong>we know that most of our algorithms can’t understand native languages and we need to provide some numerical representation and embedding is doing the same, making different numerical representations of the same text. It can be simple one like count based embedding like TF-IDF, prediction based or context based. Here we are only focused on context based.</p><p><strong>No of Parameters for Neural Network </strong>All our language model use this term as a performance metric and more number of parameters is generally assumed more accurate one. It is typically the weights of the connections or parameters are learned during the training stage.</p><h4><strong>Transformers</strong></h4><p>This is where the story changed, this is not <a href="https://en.wikipedia.org/wiki/Convolutional_neural_network">CNN </a>and <a href="https://en.wikipedia.org/wiki/Recurrent_neural_network">RNN</a>, this is something totally different. Let’s go into more detail</p><p>suppose your model go through this tweet</p><figure><img alt="https://twitter.com/narendramodi/status/1234500451850018818" src="https://cdn-images-1.medium.com/max/528/1*KxQlFRMjiv_kY7NuYGEvfQ.jpeg" /><figcaption><a href="https://twitter.com/narendramodi/status/1234500451850018818">https://twitter.com/narendramodi/status/1234500451850018818</a></figcaption></figure><p>Now, your model will be confused if Narendra Modi is talking to update these social media companies like ‘I quit’ or update his followers about his decision. Even any person with basic English knowledge, can be confused if they don’t put attention, i repeat ‘<strong>attention</strong>’. This is key concept from where Transformer architecture evolved, it create a ‘<strong>self attention</strong>’ layer while reading all corpus.</p><p>If you ever have any connection with Electronics or software encryption, you know the word <strong>encoder-decoder</strong>. The first one changes original input to some cryptic one and second one do the reverse i.e. cryptic to original.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*h-LZILODPXyvDHQzko00Bw.png" /><figcaption><a href="https://arxiv.org/pdf/1706.03762v5.pdf">https://arxiv.org/pdf/1706.03762v5.pdf</a></figcaption></figure><p>This is the diagram from its white paper and here the key steps</p><ol><li>The first one is encoder which has Multi-Head attention layer followed by feed forward neural network</li><li>Second one is decoder which has one additional layer ‘masked multi head attention’</li><li>Nx denote number of layers for both encoder and decoder</li><li>first we have stack of encoder layer where output of one layer will work as input of second</li><li>The attention layer of encoder check about context using query vector, key vector and value vector</li><li>Then encoder pass their understanding to next layer and so on</li><li>The final encoder output will pass to all decoders as key vector and query vector</li><li>It will first predict the first word as final output and take that first word as input of all decoders and predict next words</li><li>This process will be repeated till it will predict the last word</li><li>Terminate the loop :) remember your early programming days</li></ol><p>Now we can discuss about popular language models</p><h3>BERT</h3><p>Bidirectional Encoder Representations from Transformers, Google</p><p>This is actual breakthrough in field of NLP pre-trained model and it can understand context like difference between ‘this painting is pretty ugly’ and ‘this watch is pretty’. Both sentence has word ‘pretty’ but BERT can understand difference context between two. As per official documentation</p><blockquote>BERT is the first <em>deeply bidirectional</em>, <em>unsupervised</em> language representation, pre-trained using only a plain text corpus.</blockquote><p>BERT mainly has two keyword a) bidirectional b) transformers. Transformers are already explained and bidirectional is implemented via masking out some of the words in the input and then condition each word bidirectionally to predict the masked words. This is not new concept but BERT is the one who successfully implemented before anyone.</p><p>before BERT, ELMo was the technique used for context based learning but here the key advantage of BERT</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*6g33e5taFzOB79fQBwRLpA.jpeg" /></figure><p><strong>What to do with BERT</strong></p><ol><li>Pre-Training : This is very compute intensive and only needed if you want to train by own for any language, Google already trained and provide two models a) BERT-Base b) BERT-Large</li><li>Fine tuning : This is task specific work where you can fine tune model. <a href="https://en.wikipedia.org/wiki/TensorFlow">Tensorflow </a>if the by default supported framework and <a href="https://en.wikipedia.org/wiki/PyTorch">PyTorch </a>and <a href="https://en.wikipedia.org/wiki/Chainer">Chainer </a>non-official support also available</li></ol><p>you can find implementation code from here and also can execute this notebook directly</p><p><a href="https://colab.research.google.com/github/tensorflow/tpu/blob/master/tools/colab/bert_finetuning_with_cloud_tpus.ipynb">Google Colaboratory</a></p><p>BERT is basically designed to <strong>fill the blank kind</strong> of activity and it support <strong>340 millions</strong> of parameters</p><h4><strong>BERT major adoptions</strong></h4><p><strong>ROBERTA </strong>FairSeq team, Facebook</p><p>This is something released in pyTorch, and as per their official documentation</p><blockquote><a href="https://arxiv.org/abs/1907.11692">RoBERTa</a> builds on BERT’s language masking strategy and modifies key hyperparameters in BERT, including removing BERT’s next-sentence pretraining objective, and training with much larger mini-batches and learning rates.</blockquote><p><a href="https://github.com/microsoft/AzureML-BERT"><strong>AzureML-BERT</strong></a><strong> </strong>Microsoft</p><p>Its cloud based adoption of BERT where Azure cloud can perform to end to end process, as per their website it has better metric than Google native</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/912/1*b6pyNeLdeNHbx7odbGlr-w.gif" /><figcaption><a href="https://azure.microsoft.com/en-in/blog/microsoft-makes-it-easier-to-build-popular-language-representation-model-bert-at-large-scale/">https://azure.microsoft.com/en-in/blog/microsoft-makes-it-easier-to-build-popular-language-representation-model-bert-at-large-scale/</a></figcaption></figure><p><strong>ALBERT: A Lite BERT </strong>Google</p><p><strong>DistilBERT</strong> a distilled version of BERT: smaller, faster, cheaper and lighter</p><h3><strong>GPT-2/3</strong></h3><p>Generative Pretrained Transformer, OpenAI</p><p>An <a href="https://en.wikipedia.org/wiki/Elon_Musk">Elon Musk </a>initiative, OpenAI, which also received 1 Billion investment from Microsoft. It has word <strong>generative </strong>in its name, as it was trained to predict the new token based on sequence of token, using unsupervised techniques.</p><p>Considering its content generation capabilities, The time it was released, the management told that they are not releasing its full version as open source, they are feared that it will be dangerous if will be used for fake news creation.</p><p>This pretrained model are mainly used content over internet, Wikipedia, Reddit and its basically developed to do content writing or generating new text. Its unidirectional language model. Unlike of BERT, its is mainly using decoder skills and generate new skills word by word.</p><p>GPT also released it’s a music generation module, used same GPT-2 to make all the music understanding</p><p><a href="https://openai.com/blog/musenet/">MuseNet</a></p><p>BERT is basically designed <strong>essay writing</strong> kind of activity and it support 1.5 billions of parameters. GPT 3 also announced which has more advance capabilities and its really a big discussion topic around the world.</p><h3><strong>T-NLG</strong></h3><p>Turing Natural Language Generation, Microsoft</p><p>Considering the recent development in field of language model, this is Microsoft bid to solve NLP tasks like conversation , language understanding, question answer, summarization etc. As per their claim, it is <strong>17 billion</strong> parameter language model which needs a different Microsoft developed optimizer called <a href="https://www.microsoft.com/en-us/research/blog/zero-2-deepspeed-shattering-barriers-of-deep-learning-speed-scale/">ZeRO </a>and a different Deep Speed optimization library called <a href="https://github.com/microsoft/DeepSpeed">DeepSpeed</a>. Using both, the model can be trained on multiple CPU.</p><p>This model is naturally solving the question and direct answer problem, very useful for AI enabled assistance. It can also answer without using context message, at this time, the model relies on knowledge gained during pre-training to generate an answer.</p><p>It support abstractive summarization like a human, not extractive where the summarization only reduce no of sentences. It can summarize multiple kind of document like email, excel etc.</p><p>Microsoft does not made most of things public here, so for this, I have taken most of content from source website.</p><p>This is USP from their website</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eR1J9JiXRY0-VEGo5y1Xbw.png" /><figcaption><a href="https://www.microsoft.com/en-us/research/blog/turing-nlg-a-17-billion-parameter-language-model-by-microsoft/">https://www.microsoft.com/en-us/research/blog/turing-nlg-a-17-billion-parameter-language-model-by-microsoft/</a></figcaption></figure><h3>Commercial vs Research</h3><p>You have seen commercial models but have a look on research benchmark too i.e. GLUE benchmark on 19th July 2020</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/493/1*OZIioZ4RSckI338-YrmWXg.jpeg" /><figcaption><a href="https://gluebenchmark.com/leaderboard">https://gluebenchmark.com/leaderboard</a></figcaption></figure><h3>Conclusion</h3><p>This place is very interesting and it will change the world currently communicating with machines, watch out this space more</p><p>PS: Transformer may learn ‘this space’ as ‘transfer learning in NLP’ :D</p><h3>Reference</h3><ol><li><a href="https://github.com/google-research/bert">https://github.com/google-research/bert</a></li><li><a href="https://allennlp.org/elmo">https://allennlp.org/elmo</a></li><li><a href="https://openai.com/blog/better-language-models/">https://openai.com/blog/better-language-models/</a></li><li><a href="https://arxiv.org/pdf/1706.03762v5.pdf">https://arxiv.org/pdf/1706.03762v5.pdf</a></li><li><a href="https://ai.googleblog.com/2018/11/open-sourcing-bert-state-of-art-pre.html">https://ai.googleblog.com/2018/11/open-sourcing-bert-state-of-art-pre.html</a></li><li><a href="https://arxiv.org/abs/1810.04805">https://arxiv.org/abs/1810.04805</a></li><li><a href="https://pytorch.org/hub/pytorch_fairseq_roberta/">https://pytorch.org/hub/pytorch_fairseq_roberta/</a></li><li><a href="https://github.com/microsoft/AzureML-BERT">https://github.com/microsoft/AzureML-BERT</a></li><li><a href="https://azure.microsoft.com/en-in/blog/microsoft-makes-it-easier-to-build-popular-language-representation-model-bert-at-large-scale/">https://azure.microsoft.com/en-in/blog/microsoft-makes-it-easier-to-build-popular-language-representation-model-bert-at-large-scale/</a></li><li><a href="https://ai.googleblog.com/2019/12/albert-lite-bert-for-self-supervised.html">https://ai.googleblog.com/2019/12/albert-lite-bert-for-self-supervised.html</a></li><li><a href="https://arxiv.org/pdf/1910.01108.pdf">https://arxiv.org/pdf/1910.01108.pdf</a></li><li><a href="https://www.latimes.com/business/story/2019-07-22/microsoft-openai">https://www.latimes.com/business/story/2019-07-22/microsoft-openai</a></li><li><a href="https://www.microsoft.com/en-us/research/blog/turing-nlg-a-17-billion-parameter-language-model-by-microsoft/">https://www.microsoft.com/en-us/research/blog/turing-nlg-a-17-billion-parameter-language-model-by-microsoft/</a></li><li><a href="https://github.com/microsoft/DeepSpeed">https://github.com/microsoft/DeepSpeed</a></li><li><a href="https://www.microsoft.com/en-us/research/blog/zero-2-deepspeed-shattering-barriers-of-deep-learning-speed-scale/">https://www.microsoft.com/en-us/research/blog/zero-2-deepspeed-shattering-barriers-of-deep-learning-speed-scale/</a></li><li><a href="https://gluebenchmark.com/leaderboard">https://gluebenchmark.com/leaderboard</a></li></ol><p>Please share your feedback and let me know if I have missed anything.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3334b23020a9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/nlp-language-models-bert-gpt2-t-nlg-changing-the-rules-of-the-game-3334b23020a9">NLP Language Models BERT, GPT2, T-NLG: Changing the rules of the game</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Artificial Neural Network(ANN) with Keras simplified, Use Case : if student pass the exam ?(Code]]></title>
            <link>https://medium.com/analytics-vidhya/artificial-neural-network-ann-with-keras-simplified-use-case-if-student-pass-the-exam-code-949ddb2a9c91?source=rss-cb477254feab------2</link>
            <guid isPermaLink="false">https://medium.com/p/949ddb2a9c91</guid>
            <category><![CDATA[keras]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[artificial-neural-network]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Vineet Jaiswal]]></dc:creator>
            <pubDate>Sat, 29 Feb 2020 11:41:34 GMT</pubDate>
            <atom:updated>2020-03-02T12:40:25.738Z</atom:updated>
            <content:encoded><![CDATA[<h3>Artificial Neural Network(ANN) with Keras simplified, Use Case : if student pass the exam ?(Code part only)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*99gDbFIkyrAtlpnnMy0VHA.jpeg" /><figcaption>Image by : <a href="https://pixabay.com/users/Monoar-2240009/?utm_source=link-attribution&amp;amp;utm_medium=referral&amp;amp;utm_campaign=image&amp;amp;utm_content=1486278">Monoar Rahman Rony, Pixabay</a></figcaption></figure><p>Prerequisite : <a href="https://jupyter.org/">Jupyter notebook</a> or <a href="https://colab.research.google.com/notebooks/intro.ipynb">Google Colab</a> or something which support python, now we have plenty of such tools.</p><h3>Before the battle</h3><p><strong>Data set:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6yM2113wPI3lXQnS0nAYmg.png" /></figure><p>Most of the columns are self explanatory, its simple student data across three schools in Delhi : Kendriya Vidyalaya, Govt Primary School and Navodaya Vidyalaya</p><p>PS: Vidyalaya means School in Hindi and its imaginary data for reference only 😊</p><p><strong>Problem Statement:</strong></p><p>Based on the previous records, create a Deep Learning based predictor who will help us to identify if the student is potentially going to fail this year, so the teacher can put more focus on that group of students.</p><p><strong>Pre-Read</strong></p><p>ANN theory: <a href="https://towardsdatascience.com/applied-deep-learning-part-1-artificial-neural-networks-d7834f67a4f6">https://towardsdatascience.com/applied-deep-learning-part-1-artificial-neural-networks-d7834f67a4f6</a></p><p>Keras theory: <a href="https://keras.io/">https://keras.io/</a></p><h4>Prepare the horses</h4><p>for any library mentioned in this document is available on your machine/tool like</p><pre>Notebook<br>! pip install keras </pre><pre>Annaconda<br>conda install -c conda-forge tensorflow</pre><h3>Battle</h3><p><strong>Feature Pre-Processing</strong></p><p>Input variables (X) and an output variable (y), this is something like</p><p><strong>y = f(X)</strong></p><pre>X=df_all_student.iloc[:, 2:12]<br>y=df_all_student.iloc[:, 12]</pre><p>We all know that that all the Machine Learning/Deep Learning (ML/DL) works on numeric data but ‘School’ and ‘Gender’ are text data, so we need to encode the text data to numeric and we know that sklearn will do this work for us</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*XsplfNVGio-MerVvxPzTQA.png" /></figure><p>You can see both ‘School’ and ‘Gender’ are now numeric but we are trapped in new problem. Based on numeric value, this can easily confuse our model if we have some order or hierarchy which is not true. So here ‘OneHotEncoder’ will help us which splits the column into multiple columns. The numbers are replaced by 1s and 0s, depending on which column has what value.</p><p>As you can see in the constructor, we specify which column has to be one hot encoded, [1] in this case.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/652/1*vQ5o_XwGPOSsZno0yt4u0A.png" /></figure><p>Now we can fall into ‘dummy variable trap’ i.e. the independent variables are multi-collinear — two or more variables are highly correlated. Solution : just drop one variable like</p><p>X = X[:, 1:]</p><p>Now, all set with data so we can split training and testing data set</p><pre>from sklearn.model_selection import train_test_split<br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0)</pre><p>80% training, 20 % test and mentioning random_state means training and test data will be same every time, if not mention random_state then it will not be deterministic or different next run.</p><p>In normal ML life cycle, we standardize or normalize the data so most of them will be in same range</p><pre>from sklearn.preprocessing import StandardScaler<br>sc = StandardScaler()<br>X_train = sc.fit_transform(X_train)<br>X_test = sc.transform(X_test)</pre><p><strong>ANN in action</strong></p><p>This is an artistic thing where you need to create first ANN schema/graph and then hyper-tuning. there is no formula and most of things is hit and trial. We only have few recommendations and rest everything is artistic here.</p><p>Initialize basic Keras Sequential model (output of each layer is input to the next layer of our implementation)</p><pre>import keras<br>from keras.models import Sequential <br>cf = Sequential()</pre><p><strong>Adding first input layer and first hidden layer</strong></p><pre>from keras.layers import Dense</pre><pre>cf.add(Dense(units = 6, kernel_initializer = ‘uniform’, activation = ‘relu’, input_dim = 11))</pre><p><strong>Dense:</strong> fully connected layer in a sequential mode, implementation of the equation output = activation(dot(input, kernel) + bias)</p><p>This means that we are taking the dot product between our input tensor and whatever the weight kernel matrix is featured in our dense layer.</p><p><strong>Parameters:</strong></p><p>Units: it denotes the output size of the layer, normally average of no of node in input layer (no of independent variable) which is 11 and no of node in output layer which is 1, we took 6 as average.</p><p><strong>Kernel_initializer </strong>: The initializer parameters tell Keras how to initialize the values of our layer, weight matrix and our bias vector</p><p><strong>Activation: </strong>Element-wise activation function to be used in the dense layer. read more about Rectified Linear Unit (ReLU)</p><p><strong>Input_dim:</strong> for first layer only, number of input independent variable. only for first hidden layer</p><p><strong>Bias:</strong> if we are going with advance implementation</p><p><strong>Dropout</strong></p><p>to avoid over-fitting, dropout is a technique where randomly selected neurons are ignored during training</p><pre>cf.add(Dropout(rate = 0.1))</pre><p>here we are dropping 10% of neuron randomly</p><p><strong>Middle Layer and final one</strong></p><pre>cf.add(Dense(units = 6, kernel_initializer = ‘uniform’, activation = ‘relu’))<br>cf.add(Dropout(rate = 0.1))<br>cf.add(Dense(units = 1, kernel_initializer = ‘uniform’, activation = ‘sigmoid’))</pre><p>last layer activation function is different than previous one. Here normally use ‘sigmoid’ for boolean and ‘softmax’ for multi class.</p><p><strong>visualize</strong></p><pre>from ann_visualizer.visualize import ann_viz;<br>ann_viz(network, title=&quot;&quot;);</pre><p>a pdf will open like</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kRsyJAJZ_nK_eRulbfWleA.png" /></figure><p><strong>Compile</strong></p><pre>cf.compile(optimizer = ‘adam’, loss = ‘binary_crossentropy’, metrics = [‘accuracy’])</pre><p>you need to configure the learning process</p><ul><li><strong>Optimizer </strong>: update the weight parameters to minimize the loss function..</li><li><strong>Loss function</strong> : acts as guides to the terrain telling <strong>optimizer</strong> if it is moving in the right direction to reach the bottom of the valley, the global minimum.</li><li><strong>Metrics</strong>: A metric function is similar to a loss except that the results from evaluating a metric are not used when training the model.</li></ul><p>Keras has provided multiple existing option for each parameter and someone can override it too</p><p><strong>Fit</strong></p><pre>cf.fit(X_train, y_train, batch_size = 10, epochs = 100)</pre><p>Actual training based on the classifier,</p><p>The batch size: hyper-parameter related to sample</p><p>epochs: hyper-parameter related to iteration</p><p>more detail: <a href="https://keras.io/models/sequential/">https://keras.io/models/sequential/</a></p><p>you will get this type of result, this dataset is not actual so getting this accuracy 😁😁</p><pre>Epoch 99/100<br>8000/8000 [==============================] - 2s 221us/step - loss: 0.6898 - accuracy: 0.5375<br>Epoch 100/100<br>8000/8000 [==============================] - 2s 225us/step - loss: 0.6900 - accuracy: 0.5381</pre><p><strong>Prediction of test result</strong></p><pre>y_prediction =cf.predict(X_test)</pre><p>you can get any specific student prediction like this cf.predict(X_test[0:1,:]) or pass the same shape and normalized array to get new student prediction.</p><h3>Cross Validation</h3><p><strong>k</strong>-<strong>Fold Cross</strong>-<strong>Validation</strong></p><p>Our model test and training data may be biased, so cross validation techniques used for better model performance measurement . In K-fold, is when the dataset is randomly split up into ‘<strong>k</strong>’ groups. One of the groups is used as the test set and the rest are used as the training set.</p><pre>from keras.wrappers.scikit_learn import KerasClassifier<br>from sklearn.model_selection import cross_val_score<br>def kera_classifier():<br> cf = Sequential()<br> cf.add(Dense(units = 6, kernel_initializer = ‘uniform’, activation = ‘relu’, input_dim = 11))<br> cf.add(Dense(units = 6, kernel_initializer = ‘uniform’, activation = ‘relu’))<br> cf.add(Dense(units = 1, kernel_initializer = ‘uniform’, activation = ‘sigmoid’))<br> cf.compile(optimizer = ‘adam’, loss = ‘binary_crossentropy’, metrics = [‘accuracy’])<br> return cf<br>cf = KerasClassifier(build_fn = kera_classifier, batch_size = 10, epochs = 100)<br>accuracies = cross_val_score(estimator = cf, X = X_train, y = y_train, cv = 10, n_jobs = -1)<br>mean = accuracies.mean()<br>variance = accuracies.std()</pre><p>same code but used sklearn to use its capabilities for k-fold validation</p><p><strong>Grid Search Cross Validation</strong></p><p>Using this, you can automatically do hyper tuning, like you will provide multiple optimizer, epochs, batch size combination and it will automatically create all permutation from them run each of them and finally show you the final best parameters and you can use it for your final production project. It will reduce a lot of time manual, and kind of automation within machine learning</p><pre>from keras.wrappers.scikit_learn import KerasClassifier<br>from sklearn.model_selection import GridSearchCV<br>def kera_classifier(optimizer):<br> cf = Sequential()<br> cf.add(Dense(units = 6, kernel_initializer = ‘uniform’, activation = ‘relu’, input_dim = 11))<br> cf.add(Dense(units = 6, kernel_initializer = ‘uniform’, activation = ‘relu’))<br> cf.add(Dense(units = 1, kernel_initializer = ‘uniform’, activation = ‘sigmoid’))<br> cf.compile(optimizer = optimizer, loss = ‘binary_crossentropy’, metrics = [‘accuracy’])<br> return cf<br>cf = KerasClassifier(build_fn = kera_classifier)<br>parameters = {‘batch_size’: [10, 15],<br> ‘epochs’: [10, 50],<br> ‘optimizer’: [‘adam’, ‘rmsprop’]}<br>gv_search = GridSearchCV(estimator = cf,<br> param_grid = parameters,<br> scoring = ‘accuracy’,<br> cv = 10)<br>gv_search = gv_search.fit(X_train, y_train)<br>best_param = gv_search.best_params_<br>best_acc = gv_search.best_score_</pre><p>The complete solution is available at : <a href="https://github.com/jaiswalvineet/Artificial-Neural-Network-ANN-with-Keras-simplified/upload">https://github.com/jaiswalvineet/Artificial-Neural-Network-ANN-with-Keras-simplified/upload</a></p><p>Now we can host the model and find if student is potentially going to fail then we know the next steps…</p><p><em>I tried to be accurate as much as possible, still if you see any issue please let me know.</em></p><p><strong>Enjoy learning !!!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=949ddb2a9c91" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/artificial-neural-network-ann-with-keras-simplified-use-case-if-student-pass-the-exam-code-949ddb2a9c91">Artificial Neural Network(ANN) with Keras simplified, Use Case : if student pass the exam ?(Code</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Natural Language Processing(NLP), Keynotes and R,Python packages]]></title>
            <link>https://medium.com/analytics-vidhya/natural-language-processing-nlp-keynotes-and-r-python-packages-3a548f4dac1e?source=rss-cb477254feab------2</link>
            <guid isPermaLink="false">https://medium.com/p/3a548f4dac1e</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[r]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[Vineet Jaiswal]]></dc:creator>
            <pubDate>Mon, 19 Feb 2018 13:22:58 GMT</pubDate>
            <atom:updated>2020-03-06T04:19:01.375Z</atom:updated>
            <content:encoded><![CDATA[<p>It’s part of Artificial intelligence in which any intelligent system communicating using natural language like English and try to teach the computers to do what comes naturally to humans. It learns directly from linguistic input without relying to predetermined equations. You may read a lot about this topic from the internet.</p><p>The input for such kind of system may be speech or input text, then it will go into NLP engines which extract the meaning of data, some decision making and then produces some action which will make it a complete AI solution.</p><h3>2 — Key concepts you must know</h3><p>Here I am leaving theoretical NLP concepts and mainly focus on the keywords using in day to day NLP system programming. The theoretical concepts are must before learning this, but that is out of scope of the article.</p><h4>2.1 — Corpus/Corpora</h4><p>A text or collection of text which we are going to analyses like Spider Man comics or articles on Narendra Modi</p><h4>2.2 — Lexicon</h4><p>A word with meaning but it can be different in different context like a word ‘Program’ can be different for a Program manager to Developer to School going to kids to a politician. Ideally, we need to develop the lexicon as the domain we are working and it will be depend on multiple factors like country, timing, context etc. It’s like a word “First Floor” has different meaning in USA i.e. floor at ground level but a floor above ground in India</p><h4>2.3 — Token/Tokenization</h4><p>Given a character sequence and a defined document unit, tokenization is the task of chopping it up into pieces, called tokens, perhaps at the same time throwing away certain characters, such as punctuation.</p><h4>2.4 — Stop Words</h4><p>Usually common words of any language which you don’t want to consider in your analysis and does not contribute much, analyzing these word is wastage of resources</p><h4>2.5 — Stemming words</h4><p>Identify and removing the words except one which have same meaning, having only one word for all these alternatives will not impact much meanwhile considering all can be performance and memory hit like democracy, democratic, and democratization. Mostly its chopping of the words from the end.</p><h4>2.6 — Lemmatization words</h4><p>Almost same as stemming but its deals with vocabulary meaning. So, removing all the words which has same dictionary meaning i.e. ‘good’ and ‘better’ can be replaced to each other, at least most of the time</p><h4>2.7 — Tagging</h4><p>Tag the words from the corpus as per part of speech, here tagging have its literal meaning</p><h4>2.8 — Chunking</h4><p>Tagging tells you whether words are nouns, verbs, adjectives, etc, but it doesn’t give you any clue about the structure of the sentence or phrases in the sentence, so group together (connected items or words) so that they can be stored or processed as single concepts. Example “Prime Minister Narendra Modi”</p><h4>2.9 — Chinking</h4><p>Removing unwanted words from Chunking is called chinking, you may use some regular expression to remove such words.</p><h4>2.10 — Named entity recognition</h4><p>Identify named objects and places within the sentence. These may include things like people, locations, and organizations</p><h4>2.11 — Semantics</h4><p>These ideas converge to form the ‘meaning’ of an utterance or text in the form of a series of sentences. The meaning of a text is called its semantics.</p><h4>2.12 — tf-idf</h4><p>Term frequency — Inverse term frequency, This is intended to measure how important a word is to a document in a collection (or corpus) of documents, It is often used as a weighting factor in searches of information retrieval, text mining, and user modeling</p><h4>2.13 — Conditional probability</h4><p>P(A|B) = P( A ∩ B) / P (B)</p><p>The probability of event A given that we know B happened = the probability of Both event A and B happened / the probability of event B happened</p><h4>2.14 — Bayes’s Theorem</h4><p>Its probability of an event, based on prior knowledge of conditions that might be related to that event</p><p>P(A|B) = P(B|A) P(A)/ P(B)</p><h4>2.15 — Naive Bayes classifier</h4><p>Based on Bayes theorem and very popular for text categorization, it is like every feature being classified is independent of the value of any other feature.</p><p>posterior probability= (conditional probability * prior probability) / evidence</p><h4>2.16 — N-Grams</h4><p>Sequence of n word like unigram, bigram, trigram etc, used to create an statistical model of word sequence</p><h4>2.17 — Backoff</h4><p>While calculate the probability of a word in text, Backoff means you go back to a n-1 gram level to calculate the probabilities when you encounter a word with probability=0</p><h4>2.18 — Smoothing Algorithms</h4><p>Let’s say we’ve calculated some n-gram probabilities, and now we’re analysing some text. What happens when we encounter a word we haven’t seen before? How do we know what probability to assign to it? We use smoothing algorithm to give it a probability.</p><h3>3 — How probability makes your life easy (or tough)</h3><pre>&gt; SentanceStart &lt;- c(&#39;You are looking very&#39;, &quot;You are looking very&quot;,<br> &quot;I love India&quot;, &quot;I love India&quot;)<br>&gt; SentanceEnd &lt;- c(&#39;Handsome&#39;, &quot;Pretty&quot;, &quot;alot&quot;, &quot;much&quot;)<br>&gt; frequency &lt;- c(10, 234, 43,83)<br>&gt; analysis &lt;- data.frame(SentanceStart,SentanceEnd, frequency)<br>&gt; analysis<br> <br>        SentanceStart SentanceEnd frequency<br>1 You are looking very    Handsome        10<br>2 You are looking very      Pretty       234<br>3         I love India        alot        43<br>4         I love India        much        83</pre><p>Now you want to find the probability of getting ‘pretty’ after ‘you are looking very’ is kind of probability question, remember conditional probability i.e. P(“Pretty” | “you are looking very” )</p><p>It’s simplest example of probability in NLP, but trust me “<strong>This night is dark and full of terror</strong>”</p><h3>4 — Before doing any NLP analysis</h3><p>Clean your data well, consider these key points</p><ol><li>Remove punctuation</li><li>Remove Control text</li><li>Remove numbers</li><li>Remove non-ASCII characters</li><li>Convert all the text to lower case</li><li>Remove duplicate data</li><li>Remove bad words (not necessary)</li><li>Do stop word filtering</li><li>Do Stemming, lemmatization etc (not necessary as it may remove essence of data too)</li><li>Store all your clean data in another place like csv and use it for all your analyses purpose, it will be major perforce boost</li><li>Create and testing and training data (so the Machine learning will work)</li></ol><h3>5 — How to implement</h3><p>After all this, you are good to go for NLP analysis (All the best). These are only few packages which I have either used or heard but this is only few drops from a bucket ( not ocean !!! )</p><h4>5.1 — R Programming</h4><p>tm: text mining package for R and it have almost all the functionality which can be supported by R, this is base package for almost all other package</p><p>OpenNLP : OpenNLP is widely used for most common tasks in NLP, such as tokenization, POS tagging, named entity recognition (NER), chunking and so on</p><p>RWeka : The RWeka package in R provides an interface to Weka. Weka is an open source software developed by a machine learning group</p><p>Tidytext : Text mining for word processing and sentiment analysis using ‘dplyr’, ‘ggplot2’, and other tidy tools. The output of tidy is always a data.frame with disposable row names.</p><h4>5.2 — Python Programming</h4><p>NLTK: Natural language toolkit, perform all the activities which can be expected from NLP package, base for almost all other packages. Knowing this is must but we may use any other which is written on top of it</p><p>TextBlob: built on top of NLTK, and it’s more easily-accessible.</p><p>SpaCy is a new NLP library that’s designed to be fast, streamlined, and production-ready.</p><h4>5.3 — Java Programming</h4><p>Stanford’s CoreNLP is a Java library, almost from where all the things begin. Still base for most of the NLP concept. Have wrapper in both Python and R named as “CoreNLP”</p><p>I tried my level best to be right, but please let me know your feedback/suggestions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3a548f4dac1e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/natural-language-processing-nlp-keynotes-and-r-python-packages-3a548f4dac1e">Natural Language Processing(NLP), Keynotes and R,Python packages</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Free books for Data Science]]></title>
            <link>https://medium.com/@vineetjaiswal/free-books-for-data-science-6152fcce80d7?source=rss-cb477254feab------2</link>
            <guid isPermaLink="false">https://medium.com/p/6152fcce80d7</guid>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Vineet Jaiswal]]></dc:creator>
            <pubDate>Sun, 18 Feb 2018 05:06:25 GMT</pubDate>
            <atom:updated>2018-02-18T06:27:23.442Z</atom:updated>
            <content:encoded><![CDATA[<p>Few Free books worth reading, Please suggest if you know more</p><h3>Statistics</h3><p>Think Stats — Probability and Statistics for Programmers, <a href="http://www.greenteapress.com/thinkstats/">http://www.greenteapress.com/thinkstats/</a></p><p>Statistical Inference for Data Science, <a href="https://leanpub.com/LittleInferenceBook">https://leanpub.com/LittleInferenceBook</a></p><p>Think Bayes — Bayesian Statistics Made Simple, <a href="http://greenteapress.com/wp/think-bayes/">http://greenteapress.com/wp/think-bayes/</a></p><h3>Data Science</h3><p>Data Jujitsu by DJ Patil, <a href="http://www.oreilly.com/data/free/data-jujitsu.csp">http://www.oreilly.com/data/free/data-jujitsu.csp</a></p><p>Data Driven — Creating a Data Culture, <a href="http://www.oreilly.com/data/free/data-driven.csp">http://www.oreilly.com/data/free/data-driven.csp</a></p><p>R for Data Science, <a href="http://r4ds.had.co.nz/">http://r4ds.had.co.nz/</a></p><p>Python Data Science Handbook, <a href="https://jakevdp.github.io/PythonDataScienceHandbook/">https://jakevdp.github.io/PythonDataScienceHandbook/</a></p><h3>Machine Learning</h3><p>An Introduction to Statistical Learning, <a href="http://www-bcf.usc.edu/~gareth/ISL/">http://www.bcf.usc.edu/~gareth/ISL/</a></p><p>The Elements of Statistical Learning, <a href="https://web.stanford.edu/~hastie/ElemStatLearn/">https://web.stanford.edu/~hastie/ElemStatLearn/</a></p><p>Machine Learning Yearning, <a href="http://www.mlyearning.org/">http://www.mlyearning.org/</a></p><h3>Deep Learning</h3><p><a href="http://www.deeplearningbook.org/">http://www.deeplearningbook.org/</a></p><h3>Programming</h3><p>Automate the Boring Stuff With Python, <a href="https://automatetheboringstuff.com/">https://automatetheboringstuff.com/</a></p><p>R For Beginners, <a href="https://cran.r-project.org/doc/contrib/Paradis-rdebuts_en.pdf">https://cran.r-project.org/doc/contrib/</a>Paradis-rdebuts_en<a href="https://cran.r-project.org/doc/contrib/Paradis-rdebuts_en.pdf">.pdf</a></p><h3>Other</h3><p>Natural Language Processing with Python, <a href="https://www.researchgate.net/publication/220691633_Natural_Language_Processing_with_Python">https://www.researchgate.net/publication/220691633_Natural_Language_Processing_with_Python</a></p><p>The Data Science Handbook — Advice &amp; Insights from Data Scientists, <a href="http://www.thedatasciencehandbook.com/">http://www.thedatasciencehandbook.com/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6152fcce80d7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Interpret R Linear/Multiple Regression output]]></title>
            <link>https://medium.com/analytics-vidhya/interpret-r-linear-multiple-regression-output-lm-output-point-by-point-also-with-python-8e53b2ee2a40?source=rss-cb477254feab------2</link>
            <guid isPermaLink="false">https://medium.com/p/8e53b2ee2a40</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[linear-regression]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[r]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Vineet Jaiswal]]></dc:creator>
            <pubDate>Sat, 17 Feb 2018 08:01:59 GMT</pubDate>
            <atom:updated>2020-03-04T08:18:25.319Z</atom:updated>
            <content:encoded><![CDATA[<h4>(lm output point by point), also with Python</h4><p>Linear regression is very simple, basic yet very powerful approach to supervised learning. This approach is very good for predictive analysis and build a generic approach to any data before going to more complex machine learning algorithm.</p><p>Linear Regression is already discussed a lot and almost all the books who teach us analysis have its description and much more material is available on internet so I am leaving much detail except basic understanding that its all about predicting the quantitative response Y based on single predictor X based on the assumption that there are linear relationship between them, of-course some coefficient, intercept also play a deciding role and don’t forget random error which makes everything more real and earthly, almost everywhere !!!. More detail available at <a href="https://en.wikipedia.org/wiki/Linear_regression">https://en.wikipedia.org/wiki/Linear_regression</a></p><p>Assuming that we know sufficient enough about this concept and trying our hand with real things i.e. writing code in R/Python. Firstly, working with R and taking an already clean standard data, why !!! because getting and cleaning data, then data wrangling is almost 60–70% of any data science or machine learning assignment.</p><h3>Know your data</h3><pre>library(alr3)<br>Loading required package: car<br>library(corrplot)<br>data(water) <em>## load the data</em><br>head(water) <em>## view the data</em><br> <br>  Year APMAM APSAB APSLAKE OPBPC  OPRC OPSLAKE  BSAAM<br>1 1948  9.13  3.58    3.91  4.10  7.43    6.47  54235<br>2 1949  5.28  4.82    5.20  7.55 11.11   10.26  67567<br>3 1950  4.20  3.77    3.67  9.52 12.20   11.35  66161<br>4 1951  4.60  4.46    3.93 11.14 15.15   11.13  68094<br>5 1952  7.15  4.99    4.88 16.34 20.05   22.81 107080<br>6 1953  9.70  5.65    4.91  8.88  8.15    7.41  67594<br><br>filter.water &lt;- water[,-1] <em>## Remove unwanted year </em><br><br><em># Visualize the data </em><br>library(GGally)<br>ggpairs(filter.water) <em>## It&#39;s multivaribale regaression</em></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/632/1*TeQoEEVLxPdDdAC8jT5hTg.jpeg" /></figure><h3>LM magic begins, thanks to R</h3><p>It is like yi = b0 + b1xi1 + b2xi2 + … bpxip + ei for i = 1,2, … n. here y = BSAAM and x1…xn is all other variables</p><pre>mlr &lt;- lm(BSAAM~., data = filter.water)<br>summary(mlr)<br><br><em># Output </em><br><br>Call:<br>lm(formula = BSAAM ~ ., data = filter.water)<br><br>Residuals:<br>   Min     1Q Median     3Q    Max <br>-12690  -4936  -1424   4173  18542 <br><br>Coefficients:<br>            Estimate Std. Error t value Pr(&gt;|t|)    <br>(Intercept) 15944.67    4099.80   3.889 0.000416 ***<br>APMAM         -12.77     708.89  -0.018 0.985725    <br>APSAB        -664.41    1522.89  -0.436 0.665237    <br>APSLAKE      2270.68    1341.29   1.693 0.099112 .  <br>OPBPC          69.70     461.69   0.151 0.880839    <br>OPRC         1916.45     641.36   2.988 0.005031 ** <br>OPSLAKE      2211.58     752.69   2.938 0.005729 ** <br>---<br>Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1<br><br>Residual standard error: 7557 on 36 degrees of freedom<br>Multiple R-squared:  0.9248,	Adjusted R-squared:  0.9123 <br>F-statistic: 73.82 on 6 and 36 DF,  p-value: &lt; 2.2e-16</pre><h3>Output Explained</h3><h3>Residuals</h3><p>Normally it gives a basic idea about difference between the observed value of the dependent variable (Y) and the predicted value (X), it gives specific detail i.e. minimum, first quarter, median, third quarter and max value, normally it does not used in our analysis</p><h3>Coefficients-Intercept</h3><p>We can see a all the remaining variable comes with one more row ‘Intercept’, Intercept is giving data when all the variables are 0 so all the measure done without considering any variable, this is again not much used in normal cases, it’s average value of y when x = 0</p><pre><em>#            Estimate    Std. Error t value Pr(&gt;|t|)    </em><br><em># (Intercept) 15944.67    4099.80   3.889 0.000416 ***</em></pre><h3>Coefficient-Estimate</h3><p>This is a one unit increase in X then expected change in Y, in this case one unit change in OPS LAKE then 2211.58 unit change in BSAAM</p><h3>Coefficient-Std. Error</h3><p>The standard deviation of an estimate is called the standard error. The standard error of the coefficient measures how precisely the model estimates the coefficient’s unknown value. The standard error of the coefficient is always positive.</p><p>Low value of this error will be helpful for our analysis, also used for checking confidence interval</p><h3>Coefficient-t value</h3><p>t value = estimate/std error</p><p>high t value will be helpful for our analysis as this would indicate we could reject the null hypothesis, it is using to calculate p value</p><h3>Coefficient Pr(&gt;|t|)</h3><p>individual p value for each parameter to accept or reject null hypothesis, this is statistical estimate of x and y. Lower the p value allow us to reject null hypothesis. all type of errors (true positive/negative, false positive/negative) are come to picture if we wrongly analysis p value.</p><p>Asterisks mark aside p value define significance of value, lower the value have high significance</p><pre># Signif. codes:  0 &#39;***&#39; 0.001 &#39;**&#39; 0.01 &#39;*&#39; 0.05 &#39;.&#39; 0.1 &#39; &#39; 1</pre><h3>Residual standard error</h3><pre>Residual standard error: 7557 on 36 degrees of freedom</pre><p>In normal work, average error of a model, how well our model is doing to predict the data on average</p><p>Degree of freedom is like no of data point taken in consideration for estimation taking parameter in account, Not sure but in this case, we total have 43 data point and 7 variable so removed 7 data points (43–7) = 36 degree of freedom</p><h3>Multiple R-squared and Adjusted R-squared</h3><pre>Multiple R-squared:  0.9248,	Adjusted R-squared:  0.9123</pre><p>Its always between 0 to 1, high value are better Percentage of variation in the response variable that is explained by variation in the explanatory variable, this is use to calculate how well the model is doing to explain the things, when we increase no of variable then it will also increase and there are no proper limit to define how much we can increase.</p><p>We are taking dusted value in which we does not take all variables, only significant variable are considered in adjusted R squared</p><h3>F-statistic</h3><pre>F-statistic: 73.82 on 6 and 36 DF</pre><p>This is showing relationship between predictor and response, higher the value will give more reasons to reject null hypothesis, its significant of overall model not any specific parameter</p><p>DF — Degree of Freedom</p><h3>p-value</h3><pre>p-value: &lt; 2.2e-16</pre><p>Overall p value on the basis of F-statistic, normally p value less than 0.05 indicate that overall model is significant</p><h3>So the Python</h3><p>I am using OLS (Ordinary least squares) approach but the same can be produced using SciPy which gives more standard result.</p><pre>import pandas as pd<br>import scipy.stats as stats<br>from statsmodels.formula.api import ols</pre><pre>mlr = ols(&quot;BSAAM~OPSLAKE+OPRC+OPBPC+APSLAKE+APSAB+APMAM&quot;, df).fit()<br>print(mlr.summary())</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/1*s_HTtaCpY9IhAIbmhoAkBw.png" /></figure><p>Most the parameters are matching with R output and the rest of parameters can be used for next research work :)</p><p>All the description is based on general perceptions, Please let me know if something wrong and your feedback is highly welcomed.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8e53b2ee2a40" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/interpret-r-linear-multiple-regression-output-lm-output-point-by-point-also-with-python-8e53b2ee2a40">Interpret R Linear/Multiple Regression output</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>