CSC310 Lecture 28

CSC310 Lecture 28

ML as a Service
(20261130)

Javier Gonzalez-Sanchez PRO

November 29, 2026

Annual Pro sale · Save $30

Have presentations of your own?

Share with private links, password protection, and more control over your work.

Transcript

45 slides
  1. CSC 5100 Modern Software Engineering Lecture 28. Machine Learning as

    a Service Dr. Javier Gonzalez-Sanchez [email protected] www.javiergs.phd ffi o ce: 14 -227
  2. Where are we? Microservices Java Lambda + API Gateway; stable

    JSON contracts. Distributed integration DynamoDB, S3, SNS, SQS and MQTT. Software Quality and Observability JUnit, CI, CloudWatch; AI Agent Integration MCP and authenticated tools.
  3. Next Rules (Algorithm) Distance, encryption and coordinate transforms have explicit

    algorithms. Machine learning A model learns a mapping or pattern from example data. Training Fit model parameters using historical or synthetic examples. Inference Apply the trained model to new inputs without retraining. Evaluate Measure latency, failures, cost and meaningful added value.
  4. ML vocabulary Features Numeric or encoded inputs: temperature, change, rolling

    mean. Labels / targets Expected category or value for supervised learning; not required by every algorithm. Prediction Class, numeric estimate, anomaly flag or detected object. Score Model-specific signal; not automatically a calibrated probability.
  5. Learning approaches Supervised Learn from labeled examples: classify or predict

    a value. (examples with Rekognition and Comprehend) Unsupervised Discover structure or anomalies without labeled targets (an example with SageMaker)
  6. Three AWS services SageMaker AI Custom model hosting • numerical

    anomaly detection • we own the model. Rekognition Managed vision • labels and optional object bounding boxes. Comprehend Managed NLP • positive, negative, neutral or mixed sentiment.
  7. Inference in a Microservice Java Lambda Business Logic Client API

    Gateway REST/JSON Routing Validation / Rules ML Adapter ML Service AWS SDK Inference
  8. Synchronous or asynchronous? Synchronous Request/response. The client waits for the

    ML prediction. Asynchronous Background processing. The client continues without waiting for inference. (Mechanisms: SQS, SNS, MQTT, S3 events)
  9. Example: Temperature anomaly Baseline A fixed upper limit catches absolute

    temperature violations. ML extension Detect unusual patterns using current reading and prior history. Model Isolation Forest trained locally on synthetic normal behavior. Boundary Advisory signal only; not a validated equipment safety detector.
  10. Define the model contract Input Six Celsius readings, oldest first,

    equally spaced. Features We extract: (1) Current reading; (2) Change from prior sample; (3) Mean and (4) standard deviation of prior five. Output Anomaly flag and Isolation Forest decision score (negative = outlier). Validation Reject missing, nonfinite, wrong-length inputs; check sampling interval upstream.
  11. Train locally: Python import numpy as np import joblib from

    sklearn.ensemble import IsolationForest rng = np.random.default_rng(42) def features(x): h = x[:-1] return [x[-1], x[-1]-h[-1], h.mean(), h.std()] w = rng.normal(22, 0.8, size=(4000, 6)) X = np.array([features(x) for x in w]) model = IsolationForest(contamination=0.02, random_state=42) model.fit(X) joblib.dump(model, 'model.joblib')
  12. Serving code: inference.py import json, os, joblib, numpy as np

    def model_fn(model_dir): return joblib.load(os.path.join(model_dir, 'model.joblib')) def input_fn(body, content_type): if content_type != 'application/json': raise ValueError('JSON required') x = np.asarray(json.loads(body)['readings'], dtype=float) if x.shape != (6,) or not np.isfinite(x).all(): raise ValueError('6 readings') h = x[:-1] return [[x[-1], x[-1]-h[-1], h.mean(), h.std()]] def predict_fn(x, model): return {'anomaly': bool(model.predict(x)[0] == -1), 'score': float(model.decision_function(x)[0])} def output_fn(result, accept): return json.dumps(result), 'application/json'
  13. Step 1 — Account and storage S3 Private, uniquely named

    bucket or approved existing bucket. Prefixes models/temperature/v1/ and images/l08/; use default encryption. Role SageMaker service role trusts sagemaker.amazonaws.com; read model prefix and required image/log permissions.
  14. Step 2 — Package and upload export AWS_REGION=us-west-2 export BUCKET=<approved-private-bucket>

    mkdir -p bundle/code cp model.joblib bundle/ cp inference.py bundle/code/ tar -C bundle -czf model.tar.gz model.joblib code aws s3 cp model.tar.gz \ s3://$BUCKET/models/temperature/v1/model.tar.gz aws s3 ls s3://$BUCKET/models/temperature/v1/
  15. Step 3 — Create the SageMaker model S3 AWS Container

    IAM Role model.tar.gz scikit-learn Permissions SageMaker Model csc5100-temperature-v1 Artifact + Runtime + Configuration Endpoint Configuration Serverless · 2 GB · Concurrency 2 SageMaker Serverless Endpoint csc5100-temperature-anomaly
  16. Step 3 — Create the SageMaker model Model name csc5100-temperature-v1

    Execution role Instructor-created SageMaker execution role. Container Supported CPU scikit-learn serving image for us-west-2; match training versions. Artifact / entrypoint S3 model.tar.gz; configure SAGEMAKER_PROGRAM=inference.py and SAGEMAKER_SUBMIT_DIRECTORY=/opt/ml/model/code for the compatible toolkit.
  17. Step 4 — Endpoint configuration aws sagemaker create-endpoint-config \ --endpoint-config-name

    csc5100-temperature-v1 \ --production-variants '[{ "VariantName":"AllTraffic", "ModelName":"csc5100-temperature-v1", "ServerlessConfig":{"MemorySizeInMB":2048,"MaxConcurrency":2} }]' aws sagemaker create-endpoint \ --endpoint-name csc5100-temperature-anomaly \ --endpoint-config-name csc5100-temperature-v1 aws sagemaker wait endpoint-in-service \ --endpoint-name csc5100-temperature-anomaly
  18. Step 5 — Smoke-test the endpoint AWS CLI JSON SageMaker

    Endpoint Instructor's computer input_fn() predict_fn() Prediction output_fn() Java Lambda + API Gateway Not involved in this test
  19. Step 5 — Smoke-test the endpoint echo '{"readings":[22,22.2,21.9,22.1,22,35]}' > input.json

    aws sagemaker-runtime invoke-endpoint \ --endpoint-name csc5100-temperature-anomaly \ --content-type application/json --accept application/json \ --body fileb://input.json output.json cat output.json # Repeat with a normal sequence; then invalid input. # Record actual response, latency and CloudWatch logs.
  20. Step 6 — Extend the existing Lambda Configuration ML_ENDPOINT=csc5100-temperature-anomaly; region

    from Lambda environment. Permission Add sagemaker:InvokeEndpoint on the one endpoint ARN to the Lambda execution role. Data Supply six compatible readings; do not silently mix sensor streams. Integration Preserve existing storage/events; include optional prediction and explicit unavailable status.
  21. Invoke SageMaker static final SageMakerRuntimeClient ML = SageMakerRuntimeClient.create(); String endpoint

    = System.getenv("ML_ENDPOINT"); String json = mapper.writeValueAsString(Map.of("readings", readings)); var result = ML.invokeEndpoint(r -> r .endpointName(endpoint) .contentType("application/json") .accept("application/json") .body(SdkBytes.fromUtf8String(json))); JsonNode prediction = mapper.readTree(result.body().asUtf8String());
  22. Example API call // Optional request extension { "readings":[22,22.2,21.9,22.1,22,35], "mlEnabled":true

    } // New response field, alongside existing data {"ml":{"status":"OK","model":"temperature-v1", "anomaly":true,"score":-0.12}} // If the prediction is unavailable {"ml":{"status":"UNAVAILABLE","model":"temperature-v1"}}
  23. Visual intelligence Computer vision Extract meaningful information from images using

    machine learning. Model Pretrained and managed by AWS. No training or deployment required (for our example). Input JPEG or PNG image, stored in S3 or provided as bytes. Operation Output DetectLabels with GENERAL_LABELS; cap results and specify minimum confidence. DetectText DetectFaces Label names, confidence (0–100), and bounding boxes for some instances.
  24. Configure and test aws s3 cp workspace.jpg s3://$BUCKET/images/l08/workspace.jpg aws rekognition

    detect-labels \ --image "S3Object={Bucket=$BUCKET,Name=images/l08/ workspace.jpg}" \ --features GENERAL_LABELS \ --max-labels 10 --min-confidence 70 # Inspect labels, confidence and available instance boxes. # Repeat with a different image and an invalid object key.
  25. DetectLabels static final RekognitionClient VISION = RekognitionClient.create(); var response =

    VISION.detectLabels(r -> r .image(i -> i.s3Object(o -> o.bucket(bucket).name(key))) .features(DetectLabelsFeatureName.GENERAL_LABELS) .maxLabels(10).minConfidence(70f)); for (var label : response.labels()) { System.out.println(label.name() + ": " + label.confidence()); // Inspect label.instances() for optional bounding boxes. } 27
  26. DetectLabels { "Name": "Cup", "Confidence": 96.2, "Instances": [ { "BoundingBox":

    { "Left": 0.60, "Top": 0.45, "Width": 0.15, "Height": 0.25 }, "Confidence": 95.8 } ] ... }
  27. Language intelligence Natural language processing Extract meaningful information from human

    language using machine learning. Model Pretrained and managed by AWS. No training or deployment required for our example. Input Short UTF-8 text with an explicit supported language code. Operation DetectSentiment (synchronous). Output POSITIVE, NEGATIVE, NEUTRAL or MIXED plus four scores.
  28. Configure and test aws comprehend detect-sentiment \ --language-code en \

    --text 'The robot completed the task successfully.' aws comprehend detect-sentiment \ --language-code en \ --text 'The interface is useful, but the robot is too slow.' # Compare label and scores; discuss ambiguous feedback.
  29. DetectSentiment static final ComprehendClient NLP = ComprehendClient.create(); var result =

    NLP.detectSentiment(r -> r .languageCode(LanguageCode.EN) .text(feedback)); var scores = result.sentimentScore(); String label = result.sentimentAsString(); float positive = scores.positive(); float negative = scores.negative(); float neutral = scores.neutral(); float mixed = scores.mixed();
  30. Interpreting visual output { "feedback": "The robot was easy to

    use.", "language": "en" } { "Sentiment": "POSITIVE", "SentimentScore": { "Positive": 0.94, "Negative": 0.01, "Neutral": 0.04, "Mixed": 0.01 } }
  31. CSC 5100 Modern Software Engineering Javier Gonzalez-Sanchez, Ph.D. [email protected] Fall

    2026 Copyright Notice. These slides are provided exclusively for educational use in CSC 5100 within the California State University system. Redistribution or use for any other purpose is prohibited without prior written permission.

More Decks by Javier Gonzalez-Sanchez

Other Decks in Programming