Iris Flower Classification with ML
Iris Flower Classification with ML
AIM:
To Write a Program Classification of Iris Flowers using Pandas & Decision
Tree.
ALGORITHM:
Step 1: Load dataset from [Link].
Step 2: Convert to DataFrame for easy inspection and add a human-readable
label column.
Step 3: Define features X and target y.
Step 4: (Optional) Sanity checks: check for missing values, class balance, basic
stats / histograms.
Step 5: Split data into X_train, X_test, y_train, y_test.
Step 6: Create a DecisionTreeClassifier with chosen hyperparameters (e.g.,
random_state, max_depth).
Step 7: Train (fit) the model on training data.
Step 8: Predict labels for the test set.
Step 9: Evaluate using accuracy_score (and optionally confusion matrix,
classification report).
Step 10: Visualize the trained tree with plot_tree() (or export as graph).
Step 11: (Optional) Save the model to disk.
Step 12: Tune hyperparameters via cross-validation
GridSearchCV if performance is unsatisfactory.
CODE:
#Install the required libraries
Make sure these libraries are installed in your system :
pip install pandas scikit-learn matplotlib
#Import the libraries
import pandas as pd
from [Link] import load_iris
from sklearn.model_selection import train_test_split
from [Link] import DecisionTreeClassifier, plot_tree
from [Link] import accuracy_score
import [Link] as plt
OUTPUT:
RESULT:
AIM:
To Write a Classification using Logistic Regression.
ALGORITHM:
Step 1: Import libraries — load the functions you need (dataset, split, model,
metrics).
Step 2: Load dataset — read Iris features X and labels y.
Step 3: Split — divide into training (X_train, y_train) and testing (X_test,
y_test) sets.
Step 4: Create model — instantiate LogisticRegression(max_iter=200) (sets
solver + convergence limit).
Step 5: Train model — [Link](X_train, y_train) learns model parameters
from training data.
Step 6: Predict & evaluate — [Link](X_test) and compute accuracy,
confusion_matrix, classification_report.
CODE:
X = [Link]
y = [Link]
Step 2: Split data into training and testing sets (80% train, 20% test)
model = LogisticRegression(max_iter=200)
[Link](X_train, y_train)
y_pred = [Link](X_test)
OUTPUT:
RESULT:
AIM:
ALGORITHM:
Step 1 : Load Iris dataset (load_iris) → provides features (X) and labels (y).
CODE:
iris = load_iris()
X = [Link] # Features
y = [Link] # Labels
Step 2: Split the data into training and testing sets (80% train, 20% test)
pipeline = Pipeline([
('scaler', StandardScaler()),
('lda', LinearDiscriminantAnalysis(n_components=2)),
('classifier', LogisticRegression(max_iter=200))
])
[Link](X_train, y_train)
y_pred = [Link](X_test)
OUTPUT:
RESULT:
AIM:
To Write a Program to PCA + Clustering using KMeans.
ALGORITHM:
Step 1: Start the process.
Step 2: Open your Python IDE or code editor (e.g., VS Code, PyCharm, Jupyter
Notebook).
Step 3: Create a new Python file (e.g., pca_kmeans.py).
Step 4: Import the required libraries:
[Link] → for plotting clusters.
load_iris → to load the Iris dataset.
StandardScaler → to scale features.
PCA → to reduce dimensions.
KMeans → for clustering.
silhouette_score and confusion_matrix → to evaluate clustering performance.
Step 5: Load the dataset:
Load Iris dataset into iris.
Assign X = [Link] (features) and y = [Link] (true labels, optional).
CODE:
Import required libraries
import [Link] as plt
from [Link] import load_iris
from [Link] import StandardScaler
from [Link] import PCA
from [Link] import KMeans
from [Link] import silhouette_score, confusion_matrix
RESULT:
AIM:
To Write a Program to Linear Regression Pipeline using Spark MLlib on
House Price Data.
ALGORITHM:
Step 1: Start the process.
Step 2: Initialize a SparkSession using [Link]().
Step 3: Load the house price dataset using [Link]() with header=True
and inferSchema=True.
Step 4: Display the schema using printSchema() to understand data types.
Step 5: Define the target variable (price) and use all other columns as features.
Step 6: Create a VectorAssembler to combine multiple feature columns into
one vector column (features).
Step 7: Initialize a LinearRegression model specifying featuresCol and
labelCol.
Step 8: Build a Pipeline with two stages:
Stage 1: VectorAssembler (feature transformation)
Stage 2: LinearRegression (model training)
Step 9: Split the dataset into 80% training and 20% testing sets.
Step 10: Train the model using [Link](train_data).
Step 11: Generate predictions on the test dataset using
[Link](test_data).
Step 12: Evaluate the model using RegressionEvaluator with metrics such as
RMSE and R².
Step 13: Display predicted vs actual prices.
Step 14: Stop the Spark session to free resources.
Step 15: End the process.
CODE:
#Import required libraries
from [Link] import SparkSession
from [Link] import VectorAssembler
from [Link] import LinearRegression
from [Link] import Pipeline
from [Link] import RegressionEvaluator
Step 1: Initialize Spark Session
spark = [Link] \
.appName("LinearRegressionPipeline_HousePrice") \
.getOrCreate()
Step 2: Load the House Price dataset (replace with your file path)
Example CSV columns: "area", "bedrooms", "bathrooms", "price"
data = [Link]("house_price.csv", header=True, inferSchema=True)
Step 3: Display dataset schema
[Link]()
[Link](5)
Step 4: Define feature columns and label column
feature_columns = [col for col in [Link] if col != 'price']
Step 5: Assemble features into a single vector
assembler = VectorAssembler(
inputCols=feature_columns,
outputCol="features"
)
Step 6: Define Linear Regression model
lr = LinearRegression(
featuresCol="features",
labelCol="price"
)
Step 7: Create a Pipeline (Assembler → Linear Regression)
pipeline = Pipeline(stages=[assembler, lr])
Step 8: Split data into training and testing sets
train_data, test_data = [Link]([0.8, 0.2], seed=42)
Step 9: Train the model using the pipeline
model = [Link](train_data)
Step 10: Make predictions on test data
predictions = [Link](test_data)
Step 11: Evaluate the model performance
evaluator = RegressionEvaluator(
labelCol="price",
predictionCol="prediction",
metricName="rmse"
)
rmse = [Link](predictions)
r2 = [Link](predictions, {[Link]: "r2"})
print(f"Root Mean Squared Error (RMSE): {rmse}")
print(f"R² Score: {r2}")
Step 12: Display sample predictions
[Link]("features", "price", "prediction").show(10)
Step 13: Stop the Spark Session
[Link]()
[Link] Logistic Regression Pipeline on Titanic Dataset
DATE:
using Spark Mllib
AIM:
To Write a Program Logistic Regression Pipeline on Titanic Dataset using
Spark Mllib.
ALGORITHM:
Step 1: Start the process.
Step 2: Initialize a Spark Session using [Link]().
Step 3: Load the Titanic dataset (CSV format) using [Link]() with
header=True and inferSchema=True.
Step 4: Display the dataset schema and first few rows to confirm loading.
Step 5: Drop any rows with missing values in key columns like Age, Fare, Sex,
and Embarked.
Step 6: Convert categorical columns (Sex, Embarked) into numerical indices
using StringIndexer.
Step 7: Assemble all numeric and indexed categorical features into a single
vector using VectorAssembler.
Step 8: Initialize a LogisticRegression model with featuresCol="features" and
labelCol="Survived".
Step 9: Create a Pipeline containing:
StringIndexer for categorical variables.
VectorAssembler for feature vector creation.
LogisticRegression for classification.
Step 10: Split the data into training and testing subsets (80% training, 20%
testing).
Step 11: Train the pipeline model using [Link](train_data).
Step 12: Make predictions using [Link](test_data).
Step 13: Evaluate the model using BinaryClassificationEvaluator (AUC) and
MulticlassClassificationEvaluator (Accuracy).
Step 14: Display model predictions along with survival probabilities.
Step 15: Stop the Spark session to free resources.
Step 16: End the process.
CODE:
# Import required libraries
from [Link] import SparkSession
from [Link] import StringIndexer, VectorAssembler
from [Link] import LogisticRegression
from [Link] import Pipeline
from [Link] import MulticlassClassificationEvaluator,
BinaryClassificationEvaluator
Step 9: Split data into training (80%) and testing (20%) sets
train_data, test_data = [Link]([0.8, 0.2], seed=42)
accuracy_evaluator = MulticlassClassificationEvaluator(
labelCol="Survived", predictionCol="prediction", metricName="accuracy"
)
accuracy = accuracy_evaluator.evaluate(predictions)
auc = [Link](predictions)
print(f"Accuracy: {accuracy:.4f}")
print(f"Area Under ROC (AUC): {auc:.4f}")
OUTPUT:
[Link] Implement the following Data structures in Java
DATE: Linked Lists, Stacks, Queues, Set, Map
AIM:
To Write a Program to Implement the following Data structures in Java Linked
Lists, Stacks, Queues, Set, Map.
Code:
!sudo apt-get install openjdk-17-jdk -y
!java -version
OUTPUT:
ALGORITHM FOR STACKS:
Step 1: Start the program.
Step 2: Import the required packages:
[Link].* and [Link].* to use Java’s built-in classes.
Step 3: Define the class StackDemo.
Step 4: Inside the main() method, create two Stack objects:
- stack1 (non-generic stack).
- stack2 (generic stack that stores String type).
Step 5: Push elements into stack1 using the push() method:
- Push "Nakka".
- Push "Sri Manohar".
- Push "Reddy".
Step 6: Display the elements of the stack using [Link](stack1).
Step 7: The stack elements are printed in the order they were pushed (LIFO structure).
Step 8: End the program.
Code :
%%writefile [Link]
import [Link].*;
import [Link].*;
class StackDemo {
public static void main(String[] args) {
// Create stacks
Stack stack1 = new Stack();
Stack<String> stack2 = new Stack<String>();
OUTPUT:
Algorithm for Queues:
%%writefile [Link]
import [Link];
import [Link];
class Main {
[Link](1);
[Link](2);
[Link](3);
[Link]();
!java Main
OUTPUT:
import [Link];
import [Link];
// Create a HashSet
// Add elements
[Link](10);
[Link](20);
[Link](30);
// Check if 20 exists
[Link](30);
OUTPUT:
Algorithm For Map:
Step 1: Start the process.
Step 4: Inside the main() method, create a Map object named countryCodes using the
TreeMap class.
Step 5: Add key-value pairs into the map using the put() method:
• Add key "USA" with value "+1".
• Add key "India" with value "+91".
• Add key "UAE" with value "+97".
Step 6: Check if the map contains the key "India" using the containsKey() method.
• Print the result (true or false).
Step 7: Remove the key "USA" from the map using the remove() method.
import [Link];
import [Link];
// Create a TreeMap
[Link]("USA", "+1");
[Link]("India", "+91");
[Link]("UAE", "+97");
!java MapInterfaceExample
OUTPUT:
RESULT:
Thus code has been executed and verified successfully.
5. Configure Hadoop:
o Edit the Hadoop configuration files (e.g., [Link], [Link], etc.) to
specify the paths and settings.
6. Run Hadoop Jobs:
o You can now run Hadoop jobs in Standalone Mode.
2. Pseudo-distributed Mode:
In Pseudo-Distributed Mode, Hadoop emulates a distributed environment on a single
machine, running each
daemon as a separate Java process. Hadoop software is installed on a Single Node,
where various daemons of
Hadoop run on the same machine as separate Java processes. These daemons include
NameNode, DataNode,
SecondaryNameNode, JobTracker, and TaskTracker, all operating within the confines
of a single server.
1. Repeat Steps 1-4 from Standalone Mode.
2. Configure Hadoop:
o Edit the Hadoop configuration files to set the appropriate values for the
pseudo-distributed environment.
o Specify localhost or [Link] as the hostname for all daemons.
# For [Link]
<property>
<name>[Link]</name>
<value>hdfs://localhost:9000</value>
</property>
# For [Link]
<property>
<name>[Link]</name>
<value>yarn</value>
</property>
# For [Link]
<property>
<name>[Link]-services</name>
<value>mapreduce_shuffle</value>
</property><property>
<name>[Link]</name>
<value>[Link]</value>
</property>
Configuring Hadoop:
Fig. Core [Link]
Fig. [Link]
Fig. [Link]
Fig. [Link]
[Link] (ii)Use web based tools to monitor your Hadoop setup.
DATE:
• Nodemanager
After Successfully running all these demons we can access these in localhost ports.
This completes the installation part of Hadoop. [Link]
(ii)Use web-based tools to monitor your Hadoop setup.
Fig. Applications
Fig. DataNode
RESULT:
Thus code has been executed and verified successfully.
[Link] Install and Run Pig then write Pig Latin
DATE:
scripts to sort, group, join, project, and filter
your data.
AIM:
To Write a program install and run Apache Pig and write Pig Latin scripts to perform
sorting, grouping, joining, projecting, and filtering operations on a dataset.
ALGORITHM:
Step 1: Install Apache Pig and set up environment variables.
Step 2: Run Pig in local mode using the command:
pig -x local
Step 3: Create a sample input data file (e.g., [Link]) containing student details.
Step 4: Load the dataset into Pig using LOAD and PigStorage().
Step 5: Use FILTER to select records based on a condition.
Step 6: Use FOREACH ... GENERATE to project specific columns.
Step 7: Use GROUP to group records based on a specific field.
Step 8: Use ORDER to sort the data in ascending or descending order.
Step 9: Use JOIN to combine data from two relations.
CODE:
[Link] Sample Data
Create a text file named [Link]:
1,John,CS,85
2,Mary,IT,92
3,Sam,CS,70
4,Anna,IT,88
5,Paul,CS,95
-- Display outputs
DUMP high_scorers;
DUMP name_marks;
DUMP grouped_by_dept;
DUMP sorted_students;
DUMP joined_data;
[Link] Output
Filtered (marks > 80):
(2,Mary,IT,92)
(4,Anna,IT,88)
(5,Paul,CS,95)
(John,85)
(Mary,92)
(Sam,70)
(Anna,88)
(Paul,95)
Grouped by dept:
(CS,{(1,John,CS,85),(3,Sam,CS,70),(5,Paul,CS,95)})
(IT,{(2,Mary,IT,92),(4,Anna,IT,88)})
RESULT:
Thus code has been executed and verified successfully.
[Link] Install and Run Hive then use Hive to create,
DATE: alter, and drop databases, tables, views, functions,
and indexes.
AIM:
To install and run Apache Hive and use HiveQL to create, alter, and drop
databases, tables, views, functions, and indexes.
ALGORITHM:
Step 1: Install Apache Hive and configure it with Hadoop.
Step 2: Start the Hadoop and Hive services.
Step 3: Open the Hive command-line interface (CLI) using the command hive.
Step 4: Create a new Hive database using the CREATE DATABASE command.
Step 5: Create a table within the database using CREATE TABLE.
Step 6: Load data into the table using the LOAD DATA command.
Step 7: Perform queries to verify the data.
Step 8: Alter the table structure using the ALTER TABLE command.
Step 9: Create a VIEW from an existing table using CREATE VIEW.
Step 10: Create a FUNCTION for user-defined operations.
Step 11: Create an INDEX on a column for faster retrieval.
Step 12: Drop the created objects (database, table, view, index, etc.) using DROP
statements.
CODE:
[Link] and Run Hive
[Link] a Database
CREATE DATABASE college;
SHOW DATABASES;
USE college;
[Link] a Table
CREATE TABLE students (
id INT,
name STRING,
dept STRING,
marks INT
)
ROW FORMAT DELIMITED
FIELDS TERMINATED BY ','
STORED AS TEXTFILE;
[Link] a Function
Hive includes built-in functions, but you can also create temporary ones.
[Link] an Index
CREATE INDEX idx_dept
ON TABLE student_info (dept)
AS 'COMPACT'
WITH DEFERRED REBUILD;
SHOW INDEXES ON student_info;
[Link] Operations
DROP INDEX idx_dept ON student_info;
DROP VIEW high_scorers;
DROP TABLE student_info;
DROP DATABASE college;
OUTPUT:
Sample Table Data:
1 John CS 85
2 Mary IT 92
3 Sam CS 70
4 Anna IT 88
5 Paul CS 95
Mary IT 92
Anna IT 88
Paul CS 95