Tuesday, March 31, 2026

Messages in LangChain

In this tutorial we’ll see what are messages in LangChain and what are the different message types available in LangChain.

What are Messages in LangChain?

When you interact with LLMs programmatically using LangChain every input and output has an associated message type, structure and metadata. Knowing these message types will help you in structuring your prompt, setting context for each message in a better way which in turn will get you a better response from LLM.

Attributes of a Message in LangChain

Each message is an object which has following attributes-

  • Role- Which identifies the type of the message (System, Human etc.)
  • Content- Actual content of the message (prompt by user, response from model).
  • Metadata- Optional data like token usage, message ID etc.

Types of Messages in LangChain

List of the different message classes in LangChain.

  1. SystemMessage- Used to set how model should behave and for setting the context for interaction.
  2. HumanMessage- Represents the user input.
  3. AIMessage- Represents the response generated by the model.
  4. ToolsMessage- Represents the output of the tool calls.
  5. ChatMessage- Messages that can be assigned an arbitrary role other than the predefined ones.
  6. FunctionMessage- Message for passing the result of executing a tool back to a model. This is a legacy class succeeded by ToolsMessage.

SystemMessage Class

SystemMessage class is used to provide high-level instructions that guide model's behavior, tone, or style.

from langchain_core.messages import SystemMessage
SystemMessage(content="You are an experience Python programmer")
  

HumanMessage Class

A HumanMessage represents user input and interactions. They can contain text, images, audio, files, and any other amount of multimodal content.

from langchain_core.messages import HumanMessage
HumanMessage (content="Write binary search program in Python")
  

AIMessage Class

This is the response from the model. They can include multimodal data, tool calls, and provider-specific metadata that you can later access.

Here is an example how a message list may look like with system, human and ai messages.

from langchain.messages import AIMessage, SystemMessage, HumanMessage

# Add to conversation history
messages = [
SystemMessage("You are a helpful assistant"),
HumanMessage("Can you help me?"),
# Create an AI message manually (for conversation history purpose)
AIMessage("I'd be happy to help you with that question!"), # Insert as if it came from the model
HumanMessage("Great! What's agentic AI?")
]
  

ToolMessage Class

When models make tool calls, they’re included as ToolMessage in the returned AIMessage.

Suppose there is a tool call to extract some information from the message and this tool is bound to the model.

@tool
def extract_info(message:str) -> str:
	…
	…

Then the model knows it has to call this function for extracting information and that is also conveyed in the AIMessage which includes a ToolsMessage.

AIMessage(content='', additional_kwargs={}, response_metadata={'model': 'llama3.1', 'created_at': '2026-03-30T06:33:19.9566618Z', 
'done': True, 'done_reason': 'stop', 'total_duration': 75089402400, 'load_duration': 184685700, 'prompt_eval_count': 755, 
'prompt_eval_duration': 68079985500, 'eval_count': 42, 'eval_duration': 6618086400, 'logprobs': None, 'model_name': 'llama3.1', 
'model_provider': 'ollama'}, id='lc_run--019d3d71-3dfe-7b11-b5c8-8bedf1f1870e-0', 
tool_calls=[{'name': 'extract_info', 'args': {'message': 'Extract relevant information from this message, Name: Test, skills: Java, Python, Spring Boot'}, 'id': 'ccd14d41-41ca-47fc-b89e-68dfcdb0fae2', 'type': 'tool_call'}], invalid_tool_calls=[], usage_metadata={'input_tokens': 755, 'output_tokens': 42, 'total_tokens': 797}), ToolMessage(content='Extracted information successfully. Let me check if I have all the details.', name='extract_info', id='93988e12-e267-409e-8efe-7494193d6451', tool_call_id='ccd14d41-41ca-47fc-b89e-68dfcdb0fae2')

ChatMessage Class

The ChatMessage class in LangChain is a flexible message type that allows you to specify an arbitrary role for the speaker.

messages = [
    SystemMessage(content="You are a helpful assistant."),
    HumanMessage(content="What is agentic AI?"),
    AIMessage(content=" Agentic AI is artificial intelligence that can autonomously perceive, reason, and act toward achieving goals without constant human intervention."),
    ChatMessage(role="developer", content="Ensure your next response is very technical."),
    HumanMessage(content="Explain the role of agentic AI."),
]
  

That's all for this topic Messages in LangChain. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. What is LangChain - An Introduction
  2. First LangChain Program: Ask Me Anything
  3. Prompt Templates in LangChain With Examples
  4. LangChain PromptTemplate + Streamlit - Code Generator Example
  5. Object Creation Using new Operator in Java

You may also like-

  1. String in Java Tutorial
  2. Array in Java
  3. Count Number of Words in a String Java Program
  4. Ternary Operator in Java With Examples
  5. Java Multithreading Interview Questions And Answers
  6. Java Exception Handling Tutorial
  7. ConcurrentHashMap in Java With Examples
  8. TreeMap in Java With Examples

Monday, March 30, 2026

raise Statement in Python Exception Handling

In Python Exception Handling - try,except,finally we saw some examples of exception handling in Python but exceptions, in all the examples there, were raised automatically. You can trigger an exception manually too using raise statement in Python.

Python raise statement usage

For throwing an exception using raise there are the following options-

1. Re‑raising the current exception

You can simply use raise without any other expression inside an except block. If no expressions are present, raise re-raises the last exception that was active in the current scope. This is useful when you want to handle an error partially but still propagate it upward. If no exception is active in the current scope, a RuntimeError exception is raised indicating that this is an error.

def divide_num(num1, num2):
  try:
    print('Result-',num1/num2)
  except ZeroDivisionError as error:
    print('Zero is not a valid argument here')
    #raise with no expression
    raise

divide_num(10, 0)

Output

Zero is not a valid argument here
Traceback (most recent call last):
  File "F:/NETJS/NetJS_2017/Python/Programs/Test.py", line 10, in <module>
    divide_num(10, 0)
  File "F:/NETJS/NetJS_2017/Python/Programs/Test.py", line 3, in divide_num
    print('Result-',num1/num2)
ZeroDivisionError: division by zero

As you can see raise statement re-raises the last exception again.

2. Raising a specific exception

If raise is used with an expression then raise evaluates the first expression as the exception object. It must be either a subclass or an instance of BaseException.

  • If you provide a class (e.g., raise ValueError), Python instantiates it automatically with no arguments.
  • If you provide an instance (e.g., raise ValueError("Invalid input")), that exact exception object is raised.
def divide_num(num1, num2):
  try:
    print('Result-',num1/num2)
  except ZeroDivisionError as error:
    print('Zero is not a valid argument here')
    raise RuntimeError("An error occurred")

divide_num(10, 0)

Output

Zero is not a valid argument here
Traceback (most recent call last):
  File "F:/NETJS/NetJS_2017/Python/Programs/Test.py", line 3, in divide_num
    print('Result-',num1/num2)
ZeroDivisionError: division by zero

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "F:/NETJS/NetJS_2017/Python/Programs/Test.py", line 9, in <module>
    divide_num(10, 0)
  File "F:/NETJS/NetJS_2017/Python/Programs/Test.py", line 6, in divide_num
    raise RuntimeError("An error occurred")
RuntimeError: An error occurred

As you can see in this case previous exception is attached as the new exception’s __context__ attribute.

3. raise with from clause

raise can also be used with from clause for exception chaining. With the from clause another exception class or instance is given, which will then be attached to the raised exception as the __cause__ attribute.

In the example there are two functions, from function func() there is a call to function divide_num with arguments that cause ZeroDivisionError.

def divide_num(num1, num2):
  try:
    print('Result-',num1/num2)
  except ZeroDivisionError as error:
    print('Zero is not a valid argument here')
    raise RuntimeError("An error occurred") from error

def func():
  try:
    divide_num(10, 0)
  except RuntimeError as obj:
    print(obj)
    print(obj.__cause__)

func()

Output

Zero is not a valid argument here
An error occurred
division by zero

As you can see using __cause__ attribute you can get the attached exception.

That's all for this topic raise Statement in Python Exception Handling. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. User-defined Exceptions in Python
  2. Passing Object of The Class as Parameter in Python
  3. Encapsulation in Python
  4. Interface in Python
  5. Python break Statement With Examples

You may also like-

  1. Magic Methods in Python With Examples
  2. Check if String Present in Another String in Python
  3. Default Arguments in Python
  4. Python Program to Display Armstrong Numbers
  5. HashMap in Java With Examples
  6. this Keyword in Java With Examples
  7. Introduction to Hadoop Framework
  8. Spring Web Reactive Framework - Spring WebFlux Tutorial

LangChain PromptTemplate + Streamlit - Code Generator Example

In this article we’ll see how to create an AI code generator using LangChain’s ChatPromptTemplate class and Streamlit for UI. What we are going to built is a UI with a dropdown to select the programming language and an area to state the coding problem. On the click of the "generate code" button, programming language and the problem are inserted as actual values in the prepared prompt template and sent to the model to get an appropriate response.

How the UI looks like

What we are going to built in the UI

  • A dropdown to select the programming language
  • An area to state the coding problem
  • A display area where the generated code is displayed
StreamLit UI for code generator

Prompt templates used in the code are kept in the separate file prompt.py

code_system_prompt_template = """
    You are an expert {language} programmer. Write code as per the given instructions. The code should be efficient, well-structured, and properly commented. Use appropriate variable names and follow best practices for coding in the specified programming language.
    """

code_human_prompt_template = """
***Instructions***: Write code to solve the following programming problem: {problem}.
Make sure to include any necessary imports and handle edge cases appropriately.
"""

codegenerator.py

In the code there is a function generate_code() that has two arguments-

  • problem (str): The programming problem to solve.
  • language (str): The programming language to use for the code generation.

This function is invoked from the streamlit code after selecting the programming language from the given option, stating the coding problem and clicking the button "Generate Code"

from langchain_core.prompts import ChatPromptTemplate, SystemMessagePromptTemplate, HumanMessagePromptTemplate
from langchain_ollama import ChatOllama
from prompt import code_system_prompt_template, code_human_prompt_template
import streamlit as st

# Define system and human message templates
system_message = SystemMessagePromptTemplate.from_template(code_system_prompt_template)
human_message = HumanMessagePromptTemplate.from_template(code_human_prompt_template)    

def generate_code(problem: str, language: str) -> str:

    # Create a ChatPromptTemplate object
    prompt = ChatPromptTemplate.from_messages([system_message, human_message]) 
    # Initialize the model
    model = ChatOllama(model="llama3.1",    
                        temperature=0.7)            
    # Format the prompt with the problem and language
    formatted_prompt = prompt.format(problem=problem, language=language)
    print(f"Formatted prompt: {formatted_prompt}")
    # Generate the code using the model
    response = model.invoke(formatted_prompt)
    # Return the generated code
    return response.content

# Streamlit app to demonstrate code generation
st.set_page_config(page_title="AI Code Generator", layout="centered")
st.title("🤖 Code Generator ")
st.markdown("Select **programming language** and state your coding problem to generate code!")
# Create a dropdown with a default value
option = st.selectbox(
    'Choose your favorite programming language:',
    ('Python', 'JavaScript', 'Java', 'C++'),
    index=0  # sets the default value to the first option
)

#print(f"Selected programming language: {option}")
problem = st.text_area("Enter the programming problem you want to solve:")

# Generate code when the button is clicked
if st.button("Generate Code"):
    if problem.strip() == "":
        st.warning("Please enter a programming problem to generate code.")
    else:
        with st.spinner("Generating code..."):
            generated_code = generate_code(problem, option)
            st.code(generated_code, language=option.lower())

You can run the code using the following command.

streamlit run codegenerator.py

If there is no error then you should see a message telling how to access your streamlit web app.

  You can now view your Streamlit app in your browser.
  Local URL: http://localhost:8501

The prompt after the insertion of actual values looks like as given below-

Formatted prompt: System:
    You are an expert Java programmer. Write code as per the given instructions. The code should be
    efficient, well-structured, and properly commented. Use appropriate variable names and follow
    best practices for coding in the specified programming language.

Human:
***Instructions***: Write code to solve the following programming problem: For given input array find contiguous array of size k whose sum is equal to given s
Input - [2,2,1,2,3]
s = 5
k = 3
Output- [2,2,1] [2,1,2]
s=4
k=2
Output - [2,2]
If no contiguous array found return "Not Present".
Make sure to include any necessary imports and handle edge cases appropriately.

That's all for this topic LangChain PromptTemplate + Streamlit - Code Generator Example. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. What is LangChain - An Introduction
  2. First LangChain Program: Ask Me Anything
  3. Access Modifiers in Java - Public, Private, Protected and Default
  4. What Are JVM, JRE And JDK in Java
  5. Object Creation Using new Operator in Java

You may also like-

  1. String in Java Tutorial
  2. Array in Java
  3. Count Number of Words in a String Java Program
  4. Ternary Operator in Java With Examples
  5. Java Multithreading Interview Questions And Answers
  6. Java Exception Handling Tutorial
  7. ConcurrentHashMap in Java With Examples
  8. TreeMap in Java With Examples

Prompt Templates in LangChain With Examples

This article shows how to use prompt template in LangChain to create reusable prompts for models. In the post First LangChain Program: Ask Me Anything we saw how to connect to different models using LangChain standard interfaces and pass user’s prompt. But what limits the prompt there is that it is hardcoded. What if you want to give user a chance to create dynamic prompts where certain values can be passed at runtime? For example-

"Write a 2-page blog post on the topic {topic}"

Here topic is a placeholder which can be replaced by the actual value later.

Or

"Write a {programming_language} program for {topic}"

Where user can supply the choice of language and the topic later to be replaced in the prompt before sending it to the model.

Creating prompt templates in LangChain

LangChain gives two options for creating such dynamic prompt templates.

  1. PromptTemplate- This class is best used for single-message, text-completion-style prompts. A prompt template consists of a string template with placeholders and formats it with input values.
  2. ChatPromptTemplate- ChatPromptTemplate is best for multi-role conversations. It uses a list of messages, each with a defined role (system, human, ai, etc).

PromptTemplate in LangChain

PromptTemplate is a utility for creating structured prompts for LLMs. It lets you define a template string with placeholders which can be replaced by actual values later.

LangChain PromptTemplate example

Let’s say you want to create an AI blog post generator which can write a blog post for the given topic. For this example, I have used a locally deployed "llama3.1" model using Ollama.

from langchain_core.prompts import PromptTemplate
from langchain_ollama import ChatOllama 
# Define a prompt template for generating a blog post
template = """
    You are an expert technical content writer. Write a detailed blog post as per the given instructions. The blog post should be engaging, informative, and well-structured. Include an introduction, main body, and conclusion. Use subheadings where appropriate and provide examples to illustrate key points.
    ***Instructions***: Write a {no_of_paras} paragraphs blog post about the following topic: {topic}.
"""
# Create a PromptTemplate object
prompt = PromptTemplate.from_template(template)
# Initialize the Ollama model
model = ChatOllama(model="llama3.1", 
                    temperature=0.7)
# Define the topic and number of paragraphs for the blog post   
topic = "Dictionary in Python"
no_of_paras = 6
# Format the prompt with the topic and number of paragraphs
formatted_prompt = prompt.format(topic=topic, no_of_paras=no_of_paras)   
# Print the formatted prompt to verify its correctness
print("Formatted Prompt:\n", formatted_prompt)  
# Generate the blog post using the model
response = model.invoke(formatted_prompt)
# Print the generated blog post 
print("\nGenerated Blog Post:\n", response.content)

Formatter prompt output is as given below-

“You are an expert technical content writer. Write a detailed blog post as per the given instructions. The blog post should be engaging, informative, and well-structured. Include an introduction, main body, and conclusion. Use subheadings where appropriate and provide examples to illustrate key points.
***Instructions***: Write a 6 paragraphs blog post about the following topic: Dictionary in Python.

ChatPromptTemplate in LangChain

ChatPromptTemplate in LangChain is a class for building structured prompts for chat models. You define messages with roles like system, human, and ai.

For example-

template = ChatPromptTemplate(
    [
        ("system", "You are a helpful AI bot. Your name is {name}."),
        ("human", "Hello, how are you doing?"),
        ("ai", "I'm doing well, thanks!"),
        ("human", "{user_input}"),
    ]
)

There are specific prompt template utility classes also to be used for creating different kind of messages.

  • AIMessagePromptTemplate- The AIMessagePromptTemplate class in LangChain is used to create a template for messages that are assumed to be from an AI within a chat conversation.
  • HumanMessagePromptTemplate- The HumanMessagePromptTemplate class in LangChain is used to create a template for messages that are from user.
  • SystemMessagePromptTemplate- The SystemMessagePromptTemplate in LangChain is a class used to define a system-level instruction (set context) for a language model within a chat application.

Refer this post- Messages in LangChain to know about the different Message classes available in LangChain.

LangChain ChatPromptTemplate example

We’ll take the previous example of the blog generation itself with one change. In the previous example context for the system is always set as "technical content writer". In this example, we’ll set this expertise later; in the beginning it is also a placeholder now. Let’s see how to do it.

For creating templates separate file prompt.py is used.

prompt.py

system_prompt_template = """
    You are an expert {expertise} content writer. Write a detailed blog post as per the given 
    instructions. The blog post should be engaging, informative, and well-structured. Include an introduction, main body, and conclusion. Use subheadings where appropriate and provide examples to illustrate key points.
"""

human_prompt_template = """    
    ***Instructions***: Write a {no_of_paras} paragraphs blog post about the following topic: {topic}.
"""

As you can see, we have two separate templates for system and human respectively with total three placeholders {expertise}, {no_of_paras}, {topic}

chattemplatedemo.py

This is the class where both of the templates are imported from prompt.py file and used to create messages for System and Human roles. I have used a locally deployed “llama3.1” model using Ollama.

from langchain_core.prompts import ChatPromptTemplate, SystemMessagePromptTemplate, HumanMessagePromptTemplate
from langchain_ollama import ChatOllama 
from prompt import system_prompt_template, human_prompt_template
system_message = SystemMessagePromptTemplate.from_template(system_prompt_template)
human_message = HumanMessagePromptTemplate.from_template(human_prompt_template)

# Create a ChatPromptTemplate object
prompt = ChatPromptTemplate.from_messages([system_message, human_message])

# Initialize the Ollama model
model = ChatOllama(model="llama3.1", 
                    temperature=0.7)

# Define the topic and number of paragraphs for the blog post   
topic = "What is an ideal duration to keep any stock in your portfolio?"
no_of_paras = 3
expertise = "financial"

# Format the prompt with the topic and number of paragraphs
formatted_prompt = prompt.format(topic=topic, no_of_paras=no_of_paras, expertise=expertise)
# Print the formatted prompt to verify its correctness
print("Formatted Prompt:\n", formatted_prompt)  

# Generate the blog post using the model
response = model.invoke(formatted_prompt)
# Print the generated blog post 
print("\nGenerated Blog Post:\n", response.content)

That’s how the formatted prompt with inserted values looks like.

Formatted Prompt:
 System:
  You are an expert financial content writer. Write a detailed blog post as per the given
  instructions. The blog post should be engaging, informative, and well-structured. Include an introduction, main body, and conclusion. Use subheadings where appropriate and provide examples to illustrate key points.

  Human: ***Instructions***: Write a 3 paragraphs blog post about the following topic: What is an ideal duration to keep any stock in your portfolio?.

That's all for this topic Prompt Templates in LangChain With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. What is LangChain - An Introduction
  2. LangChain PromptTemplate + Streamlit - Code Generator Example
  3. Access Modifiers in Java - Public, Private, Protected and Default
  4. What Are JVM, JRE And JDK in Java
  5. Object Creation Using new Operator in Java

You may also like-

  1. String in Java Tutorial
  2. Array in Java
  3. Count Number of Words in a String Java Program
  4. Ternary Operator in Java With Examples
  5. Java Multithreading Interview Questions And Answers
  6. Java Exception Handling Tutorial
  7. ConcurrentHashMap in Java With Examples
  8. TreeMap in Java With Examples

Sunday, March 29, 2026

How to Create User-defined Exceptions in Python

In this Python Exception Handling Tutorial series we'll see how to create user defined exceptions in Python which allow developers to create custom error types tailored to specific scenarios.

While Python provides a wide range of built‑in exceptions (like ValueError, TypeError, and IndexError), sometimes you as a user would want to create your own exception for a specific scenario in order to make error messages more relevant to the context. Such exceptions are called user-defined exceptions or custom exceptions. Defining your own exception makes error handling more meaningful and easier to debug.

User-defined exception in Python

To create a custom exception in Python, you simply define a new class that inherits from the built‑in Exception class (directly or indirectly).

Since your exception class is a class it can theoretically be defined to do anything any other class can do, but usually user-defined exception classes are kept simple, providing just enough information for handlers to understand the error.

As a convention, custom exception names should end with "Error", following the style of Python’s standard exceptions. This makes your code more readable and consistent with community practices.

User-defined exception Python example

Suppose you have a Python function that take age as a parameter and tells whether a person is eligible to vote or not. Voting age is 18 or more.

If person is not eligible to vote you want to raise an exception using raise statement, for this scenario you want to write a custom exception named “InvalidAgeError”.

# Custom exception
class InvalidAgeError(Exception):
  """Raised when the age provided is invalid."""
  def __init__(self, arg):
    self.msg = arg

def vote_eligibility(age):
  if age < 18:
    raise InvalidAgeError("Person not eligible to vote, age is " + str(age))
  else:
    print('Person can vote, age is', age)

# calling function
try:
  vote_eligibility(22)
  vote_eligibility(14)
except InvalidAgeError as error:
  print(error)

Output

Person can vote, age is 22
Person not eligible to vote, age is 14

Hierarchical custom exceptions

When creating a module that can raise several distinct errors, a common practice is to create a base class for exceptions defined by that module, and subclass that to create specific exception classes for different error conditions:

class Error(Exception):
  """Base class for exceptions in this module."""
  pass

class InputError(Error):
  """Exception raised for errors in the input.

  Attributes:
    expression -- input expression in which the error occurred
    message -- explanation of the error
  """

  def __init__(self, expression, message):
    self.expression = expression
    self.message = message

That's all for this topic How to Create User-defined Exceptions in Python. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. Python Exception Handling - try,except,finally
  2. Python assert Statement
  3. Passing Object of The Class as Parameter in Python
  4. Name Mangling in Python
  5. Strings in Python With Method Examples

You may also like-

  1. Magic Methods in Python With Examples
  2. Getting Substring in Python String
  3. Variable Length Arguments (*args), Keyword Varargs (**kwargs) in Python
  4. Python Program to Display Prime Numbers
  5. HashSet in Java With Examples
  6. Java Multithreading Interview Questions And Answers
  7. Switch-Case Statement in Java
  8. Spring Email Scheduling Example Using Quartz Scheduler

Array Rotation Java Program

Write a Java program to rotate an array to the left or right by n steps is a frequently asked Java interview question because it tests both problem-solving skills and understanding of array manipulation.

For example, if your array is– {1,2,3,4,5,6,7,8}

  • Rotating the array 2 steps to the right results in {7,8,1,2,3,4,5,6}.
  • Rotating the array 2 steps to the left gives {3,4,5,6,7,8,1,2}.

Array rotation program- Solution

This tutorial provides two efficient solutions for the Array Rotation Java Program.

  1. Using a temporary array and System.arraycopy() for faster copying. See example.
  2. Rotating elements one by one using loops, which is simple but less efficient for large arrays. See example.

Array rotation program- Using temp array

Solution using temporary array works as follows-

  1. Create a temporary array having the same length as the original array.
  2. If you have to rotate by 2 steps i.e. n=2 then copy n elements to a temporary array.
  3. Shift rest of the elements to the left or right based on rotation requirement.
  4. Copy elements from the temp array to the original array in the space created by shifting the elements.

In the program we actually copy all the elements to the temp array and then copy back to original array.

public class ArrayRotation {
  public static void main(String[] args) {
    int[] numArr={1,2,3,4,5,6,7,8};
    //rotateLeft(numArr, 4);
    rotateRight(numArr, 3);
  }
    
  private static void rotateLeft(int[] numArr, int steps){
    // create temp array
    int[] temp = new int[numArr.length];
    // copy elements to the temp array
    for(int i = 0; i < steps; i++){
      temp[(numArr.length-steps)+ i] = numArr[i];
    }
    // copy rest of the elements from the original array
    int i = 0;
    for(int j = steps; j < numArr.length; j++, i++){
      temp[i] = numArr[j];
    }
    //copy from temp to original 
    System.arraycopy(temp, 0, numArr, 0, numArr.length);    
    System.out.println("Array after left rotation- " + Arrays.toString(numArr));
  }
    
  private static void rotateRight(int[] numArr, int steps){
    // create temp array
    int[] temp = new int[numArr.length];
    // copy elements to the temp array
    for(int i = 0; i < steps; i++){
      temp[i] = numArr[(numArr.length-steps)+ i];
    }
    // copy rest of the elements from the original array
    int i = steps;
    for(int j = 0; j < numArr.length - steps; j++, i++){
      temp[i] = numArr[j];
    }
    System.out.println("Array after right rotation- " + Arrays.toString(temp));
  }
}

Output

Array after right rotation- [6, 7, 8, 1, 2, 3, 4, 5]

Time and space complexity

With this approach you need a temporary array of size n (same size as original array) so the space complexity is O(n).

Time Complexity is sum of the following actions

  • Creating the temporary array: O(n), where n is the size of the original array.
  • Copying elements into the temporary array: O(n).
  • Copying back into the original array using System.arraycopy(): O(n).

Thus the overall time complexity is O(n).

Array rotation program- using loops

This Java program for array rotation uses inner and outer for loops for shifting and copying elements.

Solution using loops works as follows-
  1. In an outer loop, copy the first element (in case of left rotation) or last element (in case of right rotation) in a temporary variable.
  2. Shift elements to the left or right as per rotation requirement in an inner loop one step at a time.
  3. Once out of inner loop copy the element stored in temp variable to its final position.
  4. Repeat the process for the total rotation steps.
public class ArrayRotation {
  public static void main(String[] args) {
    int[] numArr={1,2,3,4,5,6,7,8};
    rotateLeft(numArr, 2);
    //rotateRight(numArr, 3);
  }
    
  private static void rotateLeft(int[] numArr, int steps){
    for(int i = 0; i < steps; i++){
      // store the first element
      int temp = numArr[0];
      for(int j = 0; j < numArr.length - 1; j++){
        // shift element to the left by 1 position
        numArr[j] = numArr[j + 1];
      }
      // copy stored element to the last
      numArr[numArr.length - 1] = temp;
    }
    System.out.println("Array after left rotation- " + Arrays.toString(numArr));
  }
    
  private static void rotateRight(int[] numArr, int steps){
    for(int i = 0; i < steps; i++){
      int temp = numArr[numArr.length-1];
      for(int j = numArr.length-1; j > 0; j--){
        numArr[j] = numArr[j -1];
      }
      // copy stored element to the beginning
      numArr[0] = temp;
    }
    System.out.println("Array after right rotation- " + Arrays.toString(numArr));
  }
}

Output

Array after left rotation- [3, 4, 5, 6, 7, 8, 1, 2]

Time and space complexity

With this approach, if you need to rotate by n steps, and the array length is m, each step requires O(m) operations. So, the total number of operations = n * m. Thus the time complexity is O(n*m).

There is no extra space requirement so the space Complexity is O(1).

That's all for this topic Array Rotation Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. How to Find Common Elements Between Two Arrays Java Program
  2. Matrix Subtraction Java Program
  3. Java Lambda Expression Callable Example
  4. Producer-Consumer Java Program Using volatile
  5. Fibonacci Series Program in Java

You may also like-

  1. Difference Between Two Dates in Java
  2. How to Compile Java Program at Runtime
  3. Quick Sort Program in Java
  4. Write to a File in Java
  5. Map.Entry Interface in Java
  6. Synchronization in Java - Synchronized Method And Block
  7. Marker Interface in Java
  8. Spring Bean Life Cycle

Saturday, March 28, 2026

Support Vector Regression With Example

In this post we'll see how to use Support Vector Regression (SVR) which extends Support Vector Machine (SVM) to regression tasks. Since SVR is a regression model that means it is used for predicting continuous values where as SVM is a classification model which predicts a category or class label.

SVR is particularly useful when relationship between features and target may be non-linear or complex, when traditional linear regression struggles.

How does SVR work

Support vector regression works on the concept of hyperplane and support vectors. It also has a margin of error, called epsilon (ε). Let's try to understand these concepts.

1. Hyperplane- SVR model works by finding a function (hyperplane) that fits most data points within a defined margin of error (ε-tube).

In the case of linear relationship (Linear SVR) this hyperplane can be thought of as a straight line in 2D space.

In case of non-linear relationship this hyperplane can be thought of as existing in a higher dimensional space but in 2D space it manifests as a best fitting curved function.

2. Kernel trick- This ability of SVR to work in higher dimensional spaces is achieved by "kernel trick". A non-linear relationship is very difficult (actually impossible) to represent with a straight line. By mapping the data into a higher-dimensional feature space, the relationship may become linear in that space. That transformation is not done explicitly as it can be very expensive.

Using kernel trick this computation becomes easier, this lets SVR work in high-dimensional spaces implicitly, without ever explicitly constructing the transformed features.

Common kernel functions used in SVR are linear, polynomial, radial basis function (RBF), and sigmoid.

3. Margin of error- SVR has some tolerance for error. It gives a margin of error (ε) and data points that reside with in that margin are considered to have no error. You can think of this margin as a tube that goes on both sides of the fitted line (or curve). That tube is known as ε-insensitive tube because it makes the model insensitive to minor fluctuations.

SVR tries to fit a function such that most points lie within an ε-tube around the regression line.

4. Support vectors- These are the points that fall outside the ε-tube or lie on the edge of it. These support vectors determine the position of the hyperplane. These are the only points that influence the regression function because points falling with in the ε-tube are considered to have no error.

5. Slack Variables- Numerical values assigned to the variables representing the distance of the points outside the tube from the ε-tube. These slack variables are represented using the symbol \(\xi\).

Following images try to clarify all the above nomenclatures.

Support Vector Regression

SVR equation

In SVR there is an objective function and the goal is to minimize that function-

$$\frac{1}{2}\| w\| ^2+C\sum _{i=1}^n(\xi _i+\xi _i^*) $$

1. Here w is the weight vector which is computed from the support vectors:

$$w=\sum _{i=1}^n(\alpha _i -\alpha _i^*)x_i$$

where

  • xi are the support vectors (training points that lie outside the ε-tube)
  • \(\alpha _i, \alpha _i^*\) are Lagrange multipliers from the optimization problem

Note that Lagrange multipliers are used here in finding the maximum or minimum of a function when certain conditions (constraints) must be satisfied.

Constraints here are; for each data point (xi,yi):

$$y_i-(w\cdot x_i+b)\leq \varepsilon +\xi _i$$ $$(w\cdot x_i+b)-y_i\leq \varepsilon +\xi _i^*$$ $$\xi _i,\xi _i^*\geq 0$$

Note that in linear SVR, w is the weight vector defining the regression hyperplane.
In non-linear SVR, the kernel trick replaces direct inner products (xi, xj) with a kernel function K(xi, xj) and w is not computed explicitly.

minimizing \(\frac{1}{2}\| w\| ^2\) (norm of the weight vector) ensures the function is as flat as possible. Benefit of doing that is improved generalization of the model to new data and increased robustness against outliers.

2. \((\xi _i, \xi _i^*)\) are slack variables that measure deviations outside the ε-insensitive tube.

3. C is the regularization parameter controlling trade-off between flatness and total deviations outside the ε-insensitive tube. A large C value fits data closely which may risk overfitting, a smaller C value means simpler model which may mean risk of underfitting.

SVR tries to minimize the objective function during training. It finds the best \(w, b, \alpha _i, \alpha _i^*\) that minimize this objective function.

Once the optimized values are calculated, the regression function is defined as:

$$f(x)=\sum _{i=1}^n(\alpha _i-\alpha _i^*)K(x_i,x)+b$$

This is the actual function you use to make predictions.

Where:

  • xi = training data points
  • K(xi, x) = kernel function (linear, polynomial, RBF, etc.)
  • \(\alpha _i,\alpha _i^*\) = Lagrange multipliers from optimization
  • b = bias term

If you use a linear kernel, the equation simplifies to:

$$f(x)=w\cdot x+b$$

In case kernel is RBF (Radial Basis Function), the SVR prediction equation takes the form:

$$f(x)=\sum _{i=1}^n(\alpha _i-\alpha _i^*)\, \exp \left( -\gamma \| x-x_i\| ^2\right) +b$$

When SVR with Polynomial Kernel is used then the regression function becomes:

$$f(x)=\sum _{i=1}^n(\alpha _i-\alpha _i^*)\, (\gamma \cdot (x_i\cdot x)+r)^d+b$$

Support Vector Regression using scikit-learn Python library

Dataset used here can be downloaded from- https://www.kaggle.com/datasets/mariospirito/position-salariescsv

Goal is to predict the salary based on the position level.

In the implementation code is broken into several smaller units with some explanation in between for data pre-processing steps.

1. Importing libraries and reading CSV file

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
df = pd.read_csv('./Position_Salaries.csv')

Position_Salaries.csv file is in the current directory.

2. Getting info about the data.

print(df.info())

Output


RangeIndex: 10 entries, 0 to 9
Data columns (total 3 columns):
 #   Column    Non-Null Count  	  Dtype 
---  ------    -------------- 	 ----- 
 0   Position 	10 non-null     object
 1   Level      10 non-null     int64 
 2   Salary     10 non-null     int64 

As you can see count of records is 10 only. Since dataset is already small so splitting is not done. Also, it is evident from one look at the small number of records that there are no duplicates and null values.

3. Feature and label selection

X = df.iloc[:, 1:-1]
y = df.iloc[:, -1]

Explanation- X = df.iloc[:, 1:-1]

  • : means "select all rows."
  • 1:-1 means "from column index 1 up to (but not including) the last column"

y = df.iloc[:, -1]

  • : means select all rows.
  • -1 means select the last column, uses negative indexing

"Position" column has been dropped as "level" column is also signifying the same thing in numerical values.

4.
print(X)
print(y)

On printing these two variables you can see that X is a 2D array where as y is a 1D array. Printing here just to make you understand that y may need conversion to 2D array as some of the functions need 2D array as parameter.

5. Scaling data

SVR relies on kernel functions (like RBF, polynomial) that compute distances between points. If features are on different scales, one feature can dominate the distance metric, skewing the model. So, standardizing the features is required.

With SVR target scaling is also required because the ε-insensitive tube and penalty parameter C are defined relative to the scale of y. Scaling y ensures that ε and C operate in a normalized space

from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVR
from sklearn.metrics import r2_score, mean_squared_error
scaler_X = StandardScaler()
scaler_y = StandardScaler()
X_scaled = scaler_X.fit_transform(X)
y_scaled = scaler_y.fit_transform(y.reshape(-1, 1)).ravel()

Dependent variable y needs to be changed to a 2D array for that reshape is used. Note that with reshape() one of the dimensions can be -1. In that case, the value is inferred from the length of the array. Here row is passed as -1 so NumPy will infer how many rows are needed based on array size.

ravel() is used to flatten the 2D array again. Otherwise, fit() method will give problem as that expects dependent variable to be a 1D array.

6. Fitting the model

reg = SVR(kernel='rbf')
reg.fit(X_scaled, y_scaled)

An object of class SVR is created, kernel is passed as 'rbf' which is also a default. For C and epsilon default values are used which are 1 and 0.1 respectively. Note that y_scaled was already changed to a 1D array using ravel(), if not done you'll get the following error.

A column-vector y was passed when a 1d array was expected. Please change the shape of y to (n_samples, ), for example using ravel().

7. Predicting values

First a single value is predicted.

#prediciting salary by passing level
y_pred_scaled = reg.predict(scaler_X.transform([[6]]))
# prediction will also be scaled, so need to do inverse transformation
y_pred = scaler_y.inverse_transform(y_pred_scaled.reshape(-1,1))
print("Prediction in original scale:", y_pred.ravel()) #145503.10688572

Note that X value has to be scaled as model is trained with scaled values. Also, predicted value has be inversely transformed to bring it back to original scale.

Predicting for the whole data. Since splitting is not done and there is no train and test data so X_scaled is used to predict values.

y_pred = scaler_y.inverse_transform(reg.predict(X_scaled).reshape(-1,1)).ravel()

8. Comparing test and predicted values

A dataframe is created and printed to display original and predicted values side-by-side.

df_results = pd.DataFrame({'Target':y, 'Predictions':y_pred})
print(df_results)

Output

	 Target	Predictions
0	45000	73416.856829
1	50000	78362.982831
2	60000	88372.122821
3	80000	108481.435811
4	110000	138403.075511
5	150000	178332.360333
6	200000	225797.711581
7	300000	271569.924155
8	500000	471665.638386
9	1000000	495411.293695

As you can see, model has lots of room for improvement, lack of proper data is one of the main reason here. For 1 million, prediction is way off the mark.

9. Seeing the model metrics such as R squared, mean squared error and root mean squared error.

#Metrics - R-Squared, MSE, RMSE
print("R2 score", r2_score(y, y_pred)) 
mse = mean_squared_error(y, y_pred)
print("Mean Squared Error", mse)
print("Root Mean Squared Error", np.sqrt(mse))

Output

R2 score 0.7516001070620797
Mean Squared Error 20036494264.13176
Root Mean Squared Error 141550.3241399742

10. Visualize the result

plt.scatter(X, y, color='red')
plt.plot(X, scaler_y.inverse_transform(reg.predict(X_scaled).reshape(-1,1)), color='blue')
plt.xlabel('Level')
plt.ylabel('Salary')
plt.title("SVR")
Support Vector Regression plot

That's all for this topic Support Vector Regression With Example. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. Simple Linear Regression With Example
  2. Multiple Linear Regression With Example
  3. Polynomial Regression With Example
  4. R-squared - Coefficient of Determination
  5. Mean Squared Error (MSE) With Python Examples

You may also like-

  1. What is LangChain - An Introduction
  2. Local, Nonlocal And Global Variables in Python
  3. Python count() method - Counting Substrings
  4. Python Functions : Returning Multiple Values
  5. Marker Interface in Java
  6. Functional Interfaces in Java
  7. Difference Between Checked And Unchecked Exceptions in Java
  8. Race Condition in Java Multi-Threading