Posts

Showing posts with the label Python

What is Set in Python?

 A set is a data structure used to store multiple unique values in a single variable . No Duplicate Values. Example numbers = {10, 20, 30, 40} names = {"Kavi","Arjun","Ashok"} Sets do not store values by index . The items are not ordered , so you cannot access values using position. names = {"kavi","arjun","akash"} print([0]) It does not work because Sets dont have Index numbers. Sets do not allow duplicate values . even if you input duplicate values, output will always have unique values. numbers = {10, 20, 20, 30, 30, 40} print(numbers) Output will contain only unique values . Sets are changeable (mutable) . You can add or remove values . numbers = {10, 20, 30} numbers.add(40) numbers.remove(10) print(numbers)

What is Dictionary in Python?

 A dictionary is a data structure used to store data as key–value pairs . One is Keyword and another is Value for that keyword. Example: person = {"name": "Manoj", "age": 15, "city": "Chennai"} Values in a dictionary are accessed using keys instead of index numbers . person = {"name": "Mohan", "age": 25, "city": "Chennai"} print(person["name"]) It will print the value for the key "name" . Dictionaries are changeable (mutable) . You can update old values with new values using the key. person = {"name": "Raj", "age": 25} person["age"] = 30 print(person) A dictionary can also store different data types in the same structure . person = {"name": "Kavi", "age": 25, "height": 175.5, "is_employee": True}

What is Tuple in python?

 A tuple is a data structure used to store multiple values in a single variable , similar to a list. Example:  numbers = (10, 20, 30, 40) names = ("Kavi","Arjun","Ashok") Values are arranged by index number starting from 0 . You can print a value based on its position / index . names = ("kavi","arjun","akash") print(names[0]) It will print the 0 index value of the names tuple . Tuples are not changeable (immutable) . Once a tuple is created, the values cannot be modified . person_details = ("John", 25, "Europe") You cannot update a value like we do in a list. A tuple can also store different data types like List. person_details = ("John", 25, 76.5, True)

What is List in Python?

 A list is a data structure used to store multiple values in a single variable . Example: numbers = [10, 20, 30, 40] names = ["Kavi","Arjun","Ashok" Values are arranged by index number starting from 0. You can print a value based on its position / index. names = ["kavi","arjun","akash"] print(names[0]) It will print the 0 index value of names list.  Lists are changeable (mutable). You can update the old value with new value in List using index number. person_details = ["John", 25, "Europe"] person_details[1]= 26 print(person_details) Can store different data types in the same list person_details = ["John", 25, 76.5, True]

Gen AI Chat Bot Python Project using Sentence transformer model all-MiniLM-L6-v2

Step 1 – Import libraries needed for text encoding, similarity calculation, and chatbot interface. SentenceTransformer – Converts sentences into numerical vectors so machines can understand the meaning of text. scikit-learn (cosine_similarity) – Calculates similarity between two text vectors to find how closely related they are. NumPy – Used for numerical computing, arrays, matrices, and fast mathematical operations. Pandas – U sed for handling datasets in table format such as reading data, filtering, cleaning, and manipulating rows and columns. ipywidgets – Creates interactive UI elements like text boxes, buttons, sliders, and dropdowns in notebook environments. IPython.display – Displays widgets, HTML, images, and formatted output inside notebooks. Step 2 – Loading the model – SentenceTransformer loads the model "all-MiniLM-L6-v2" which converts sentences into numerical embeddings. Step 3 – Creating product data – A dictionary is created with product names and product de...

Loop based Math Chat Agent in Python

print ( "🤖 Simple AI Chat Agent" ) print ( "Type 'exit' anytime to stop\n" ) #creating empty list to store the chats later chat_history = [] #creating function for mathematical calculations since its a math chat agent def calculations ( expression ):     try :         result = eval (expression)         return f "The answer is {result} "     except :         return "I couldn’t understand that.please use numbers instead of letters" #creating function for storing message, how and what to respond def chatrespond ( usermessage ):     usrmsg = usermessage.lower()     chat_history.append(usermessage)     # Greetings - when user says hello     if "hello" in usrmsg or "hi" in usrmsg:         return "Hello! How can I help you?"     # when user asks How are you     if "how are you" in usrmsg:         retu...

Polynomial Regression Python Code - Loan Default Prediction

Image
Import necessary libraries import pandas import numpy import matplotlib.pyplot from sklearn.linear_model import LinearRegression from sklearn.preprocessing import PolynomialFeatures Importing data into project data = pandas.read_csv('loan_default_rate_dataset.csv') print(data) Assign Input Columns to X variable and Output column to Y Variable x = data[['Credit_Score','Annual_Income','Loan_Amount']] y = data['Loan_Default_Probability'] Importing Polynomial Features to do cross connections, squares in x data. So data will expand and model can learn unpredictable patterns poly = PolynomialFeatures(degree=2) training the X variable using the polynomial feature. So it will do cross connections, squares in x data and learn the complex patterns. x_poly = poly.fit_transform(x) Now, since we learned the complex patterns and expanded the x values into x_poly variable, we can do linear regression from the Polynomial X data and Y data. model = LinearRegres...

What is Polynomial Regression? Linear Regression vs Polynomial Regression

Image
 Polynomial Regression is an Advance method of Linear Regression. Linear Regression draws a line between X and Y data values, we can check how well the relationship between X and Y. Polynomial Regression draws a Curved Line which bends when relationship is unpredictable and non Linear. In a non-linear relationship , the connection between X and Y is not consistent.  Sometimes when X increases , Y increases , Other times when X increases , Y decreases , and it can change direction multiple times . Linear Regression → works best when the relationship between X and Y is proportional and predictable . The line just shows how much Y increases when X increases. Polynomial Regression → works best when the relationship is non-linear or unpredictable . The curve bends up and down showing that sometimes X increases Y, sometimes decreases Y, depending on the data pattern.

Showing Relationship between X and Y Values using Linear Regression Line in Python - Machine Learning

Image
Importing Libraries for this project import numpy as np  import pandas as pd from sklearn.linear_ model import LinearRegression  import matplotlib.pyplot as plt  Importing Data file into python code  filepath = 'PythonRegressionPracticeWorkbook.csv'  data = pd.read_csv(filepath)  print(data)  Assigning Input / Independent Column to X and assigning dependent / Output Column to Y variables  x = data[['Square Feet']]  y = data['Price']  Training the X and Y variables using Linear Regression Model to find how X affects Y model = LinearRegression()  model.fit(x,y)  Checking Slope, Intercept values from the learned Model slope = model.coef_[0]  intercept = model.intercept_  print("Slope:", slope)  print("Intercept:",intercept)  Predicting the output value / Y value for each X value / input value  y_pred = model.predict(x)  Plotting Scatter plot with Regression Line to show both Original X and Y values, P...

Linear Regression Prediction of future values in Python using Scatter Plot - Machine Learning

Image
We are Importing Necessary Libraries for this project  import pandas as pandas  import numpy as numpy  import matplotlib.pyplot as pyplot  from sklearn.linear_model import LinearRegression Importing Data using Pandas library and creating table dataframe data = pandas.read_csv('python_linear_regression_prediction_python_data.csv')  print(data) Assigning Input / Independent columns to X variable and Assigning Output / Dependent Column to Y Variable x = data[['Experience_Years','Calls_Made','Meetings_Conducted']]  y = data['Sales_Amount'] Asking Linear Regression Model to learn data from X and Y variables model = LinearRegression() model.fit(x,y) Printing Coefficient and Intercept to check their values print("Coefficient:",model.coef_)  print("Intercept",model.intercept_) Adding New Inputs / Independent Values to predict Output / Dependent values new_data = pandas.DataFrame({ 'Experience_Years': [8, 12, 15], '...

What is For Loop in Python?

For loop is used to repeat a code multiple times . It goes through each Value in a Range , one by one, executes the code for each item. How it works: You will write a code inside For Loop. It applies that code to each values in the Range, one by one. You will save time doing this instead of applying the code separately for each values. It only stops the process when it reaches last value in a range.

Matplotlib Library for Python Visualization

Image
Matplotlib is a Python library for creating visualizations like graphs, charts, and plots. It helps us see data visually , which makes it easier to understand patterns, trends, and relationships. Why Matplotlib is used in Python for Data Science: Easily create line charts, scatter plots, bar charts, histograms, and more. Change colors, labels, titles, legends, figure size, and styles. Works well with Pandas and NumPy data structures.

Scikit-learn Library for Data Science and Machine Learning

Image
Scikit-learn is a Python library for Machine Learning . It has  tools to create models, train data and test models for predicting or classifying data. Why Scikit-learn is used in Python for Data Science: It has Simple functions to train models and make predictions. It Supports many algorithms: Linear Regression, Decision Trees, Random Forest, K-Nearest Neighbors, Clustering, etc. Test Model and Provides metrics like accuracy, r-squared, mean squared error. Prepare data with  Scaling, encoding, splitting data into train / test datasets. Works with NumPy , Pandas , and Matplotlib easily.

Pandas Library in Data Science

Image
Pandas is a Python library for data manipulation and analyzing dataset with rows and Columns. Suitable for working with Large Datasets. Why Pandas is used in Python for Data Science: Stores data in a structured way using Data Frames . Easily handle missing data, duplicates, or incorrect values. Perform calculations, filtering, sorting, grouping, and aggregation. Read and write CSV, Excel, SQL, JSON, and more. Integration with Other Libraries: Works well with NumPy , Matplotlib , Seaborn , and Scikit-learn .

Why Vector, Matrix and Tensor are called 1D, 2D and 3D

1. Vector (1D): A list of numbers in a single line. [1,2,3,4,5] Think of it as a single column or Single Row in Excel. It either goes Horizontal or Vertical or any direction, but Single Line. That is why it is called Only one dimension . Example: [5, 10, 15] → 3 numbers in one row or 3 numbers in one column. Python Code: import numpy as np vector = np.array([1,2,3,4,5]) print(vector) 2. Matrix (2D): A table of numbers with both  rows and columns . Think of it as one Excel sheet where Column A has 1,2,3,4,5 and Column B has 6,7,8,9,10 Now it has Two dimensions: rows × columns. Python Code: import numpy as np matrix = np.array([[1,2,3],[4,5,6],[7,8,9]]) print(matrix) 3. Tensor (3D or more): A collection of matrices stacked together like a . Think of it as multiple Excel sheets stacked in a workbook . One above another. Tensor Can have 3, 4, or more dimensions. Row is one dimension, Column is second dimension, second table or second sheet is third dimension, third table is fourth d...

NumPy Library in Data Science

Image
We use the NumPy library in data science with Python because it makes working with numbers and large datasets much faster and easier. Why NumPy is important in data science: NumPy stores data as arrays that uses less memory Applies Math Operations directly on all values in the array at once. We can work with 1D (vectors), 2D (matrices), and even higher-dimensional data. Libraries like Pandas , Scikit-learn , TensorFlow , and Matplotlib depend on NumPy for handling numeric data. NumPy has built-in functions for matrix multiplication, eigenvalues, random number generation, and statistical calculations.

Linear Regression in Python to find Relationship between two columns - Code Explanation

import numpy as np Importing Numpy Library and giving it a short name as np import pandas as pd Importing pandas librabry and giving it a short name as pd from sklearn.linear_model import LinearRegression Importing Linear Regression Model from Sckit Learn Library. import matplotlib.pyplot as plt Importing Matplotlib library for making graphs and giving a short name as plt filepath = r'C:\Users\kkumaran\Downloads\Python - Regression Practice Workbook.xlsx' This is the Location of the Excel File in my Computer. I am importing Excel file into variable called "filepath" data = pd.read_excel(filepath,sheet_name='Linear Regression Practice 1') This code reads the excel file using pandas library and load the sheet Linear Regression Practice 1 into a dataframe called "data". Now your excel data is inside python. print(data) This show the dataset for you to verify. x = data[['Square Feet']] I am creating a variable called x and putting Square feet Col...