ML Lab PT
ML Lab PT
AIM:
To execute a python program for solving regression and classification using decision tree.
PROGRAM CODE:
# Classification
print("Classification Example:")
# Split the dataset for classification with 70% training and 30% testing
X_train_clf, X_test_clf, y_train_clf, y_test_clf = train_test_split(X, y_classification, test_size=0.14,
random_state=2)
# Regression
print("\nRegression Example:")
# Split the dataset for regression with 70% training and 30% testing
X_train_reg, X_test_reg, y_train_reg, y_test_reg = train_test_split(X, y_regression, test_size=0.31,
random_state=42)
RESULT:
Thus, the program was executed and the result was obtained successfully.
EXP NO: 2 Root Node Attribute Selection for Decision Trees
DATE: using Information Gain
AIM:
To implement a python program for root note attribute selection for decision trees using
information gain.
PROGRAM CODE:
# Calculate the unique values and their counts for the selected attribute
attribute_values, counts = np.unique(data[:, attribute_index], return_counts=True)
# Example dataset
data = np.array([
[1, 'Sunny', 'Hot', 'High', 'Weak'],
[2, 'Sunny', 'Hot', 'High', 'Strong'],
[3, 'Overcast', 'Hot', 'High', 'Weak'],
[4, 'Rain', 'Mild', 'High', 'Weak'],
[5, 'Rain', 'Cool', 'Normal', 'Weak'],
[6, 'Rain', 'Cool', 'Normal', 'Strong'],
[7, 'Overcast', 'Cool', 'Normal', 'Strong'],
[8, 'Sunny', 'Mild', 'High', 'Weak'],
[9, 'Sunny', 'Cool', 'Normal', 'Weak'],
[10, 'Rain', 'Mild', 'Normal', 'Weak'],
[11, 'Sunny', 'Mild', 'Normal', 'Strong'],
[12, 'Overcast', 'Mild', 'High', 'Strong'],
[13, 'Overcast', 'Hot', 'Normal', 'Weak'],
[14, 'Rain', 'Mild', 'High', 'Strong']
])
target = np.array(['No', 'No', 'Yes', 'Yes', 'Yes', 'No', 'Yes', 'No', 'Yes', 'Yes', 'Yes', 'Yes', 'Yes', 'No'])
RESULT:
Thus, the program was executed and the result was obtained successfully
EXP NO : 3 Pattern Recognition Application using
DATE: Bayesian Inference
AIM:
To implement a python program for pattern recognition application using Bayesian Interface.
PROGRAM CODE:
import numpy as np
class BayesianClassifier:
def __init__(self):
self.class_priors = {}
self.class_means = {}
self.class_variances = {}
# Make predictions
predictions = classifier.predict(X_test)
for i, pred in enumerate(predictions):
print(f"Sample {i+1}: Predicted class - {pred}")
OUTPUT:
RESULT:
Thus, the program was executed and the result was obtained successfully
EXP NO :4 Naïve Bayes Classification
DATE:
AIM:
PROGRAM CODE:
import numpy as np
class NaiveBayesClassifier:
def __init__(self):
self.class_priors = {}
self.feature_likelihoods = {}
# Example dataset
X_train = np.array([
['<30', 'High', 'Yes'],
['<30', 'High', 'No'],
['30-40', 'High', 'Yes'],
['>40', 'Medium', 'Yes'],
['>40', 'Low', 'No'],
['>40', 'Low', 'Yes'],
['30-40', 'Low', 'Yes'],
['<30', 'Medium', 'No'],
['<30', 'Low', 'Yes'],
['>40', 'Medium', 'Yes']
])
y_train = np.array(['Yes', 'No', 'Yes', 'Yes', 'No', 'Yes', 'No', 'Yes', 'Yes', 'Yes'])
X_test = np.array([
['<30', 'Low', 'No'],
['>40', 'Medium', 'No']
])
# Make predictions
predictions = classifier.predict(X_test)
for i, pred in enumerate(predictions):
print(f"Sample {i+1}: Predicted class - {pred}")
OUTPUT:
EXP NO: 5 Bagging in Classification
DATE:
AIM:
PROGRAM CODE:
# Make predictions
y_pred = bagging_classifier.predict(X_test)
# Calculate accuracy
accuracy = accuracy_score(y_test, y_pred)
print("Accuracy:", accuracy)
OUTPUT:
RESULT:
Thus, the program was executed and the result was obtained successfully
EXP NO: 6 Bagging Boosting Applications using
DATE: Regression Trees
AIM:
To implement a python program for bagging boosting applications using regression trees.
PROGRAM CODE:
import numpy as np
from sklearn.datasets import make_regression
from sklearn.model_selection import train_test_split
from sklearn.ensemble import BaggingRegressor, GradientBoostingRegressor
from sklearn.tree import DecisionTreeRegressor
from sklearn.metrics import mean_squared_error
RESULT:
Thus, the program was executed and the result was obtained successfully
EXP NO: 7 Data and Text classification using Neural Network
DATE:
AIM:
To implement a python program that classifies data and text using neural network.
PROGRAM CODE:
# Import necessary libraries
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.neural_network import MLPClassifier
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score
iris = load_iris()
X = iris.data
y = iris.target
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
RESULT:
Thus, the program was executed and the result was obtained successfully.
EXP NO: 8 Data & Text Clustering using
DATE: K-means algorithm
AIM:
PROGRAM CODE:
import os
# Set OMP_NUM_THREADS environment variable to 2
os.environ['OMP_NUM_THREADS'] = '2'
from sklearn.datasets import make_blobs
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
plt.xlabel('Feature 1')
plt.ylabel('Feature 2')
plt.title('K-means Clustering')
plt.show()
OUTPUT:
RESULT:
Thus, the program was executed and the result was obtained successfully.
EXP NO: 9 Application of CRFs in Natural
DATE: Language Processing
AIM:
PROGRAM CODE:
import pandas as pd
# Example sentences and corresponding POS tags
sentences = [
"I love to play soccer",
"She sings beautifully",
"They are going to the park",
"I like to watch sunset"
]
pos_tags = [
["PRON", "VERB", "PART", "VERB", "NOUN"],
["PRON", "VERB", "ADV"],
["PRON", "AUX", "VERB", "ADP", "DET", "NOUN"],
["PRON", "VERB", "NOUN"]
]# Create a DataFrame to store the sentences and POS tags
data = pd.DataFrame({'sentence': sentences, 'pos_tags': pos_tags})
# Save the DataFrame as a CSV file
data.to_csv('pos_tagging_dataset.csv', index=False)
from google.colab import files
files.download('pos_tagging_dataset.csv')
import nltk
nltk.download('punkt')
nltk.download('averaged_perceptron_tagger')
# Load your own dataset (replace 'path_to_dataset' with the actual path)
with open('/content/pos_tagging_dataset.csv', 'r') as file:
data = file.read()
# Tokenize the text into sentences
sentences = nltk.sent_tokenize(data)
# Tokenize each sentence into words and apply POS tagging
pos_tags = []
for sentence in sentences:
words = nltk.word_tokenize(sentence)
pos_tags.append(nltk.pos_tag(words))
# Display the sentences
for i, sentence in enumerate(sentences):
print(f"--- Sentence {i+1} ---")
print(sentence)
print()
import nltk
nltk.download('punkt')
nltk.download('averaged_perceptron_tagger')
# Function to perform POS tagging on a sentence
def pos_tagging(sentence):
# Tokenize the sentence into words
words = nltk.word_tokenize(sentence)
# Apply POS tagging
pos_tags = nltk.pos_tag(words)
return pos_tags
# Get input sentence from user
sentence = input("Enter a sentence:")
# Perform POS tagging on the sentence
tagged_words = pos_tagging(sentence)
# Display the POS tags for each word
for word, pos_tag in tagged_words:
print(f"{word} -> {pos_tag}")
OUTPUT:
RESULT:
Thus, the program was executed and the result was obtained successfully.