Artificial Intellegence Lab Practical
Artificial Intellegence Lab Practical
NAME :
REG. NO :
Elayampalayam, Tiruchengode.
2 K-Means Clustering
3 Decision Trees
4 K-Nearest Neighbour
6 Baseyian Network
AIM:
ALGORITHM:
1.Install Anaconda
1. Download Anaconda
o Go to the Anaconda website.
o Choose the appropriate installer for your operating system
(Windows, macOS, or Linux).
o Click the "Download" button.
jupyter notebook
o This command will open the Jupyter Notebook interface in your
default web browser.
2. Create a New Notebook
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
RESULT:
AIM:
ALGORITHM:
1. Import Required Libraries:
Use the fitted model to predict the cluster for the new data point.
Display the predicted cluster.
RESULT:
Thus the predict a classification using K-Means Clustering algorithm has been
successfully executed
Date : :
Exercise No :
3. Write a program to demonstrate the working of the decision tree
based ID3 algorithm. Use an appropriate data set for building the
decision tree and apply this knowledge to classify a new sample.
AIM:
To Write a program to demonstrate the working of the decision tree based
ID3 algorithm and apply this knowledge to classify a new sample.
ALGORITHM:
Use the Iris dataset, which is commonly used for classification tasks.
Calculate and display the accuracy of the model on the test set.
CODING:
import numpy as np
import pandas as pd
from sklearn.tree import DecisionTreeClassifier, export_text, plot_tree
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
# Create a DataFrame
df = pd.DataFrame(data.data, columns=feature_names)
df['species'] = pd.Categorical.from_codes(data.target, target_names)
plt.show()
# Classify a new sample
new_sample = np.array([[5.1, 3.5, 1.4, 0.2]]) # Example: A new iris sample
predicted_class = clf.predict(new_sample)
predicted_class_name = target_names[predicted_class[0]]
print(f"\nNew Sample Prediction: {predicted_class_name}")
# Test accuracy
accuracy = clf.score(X_test, y_test)
print(f"\nModel Accuracy: {accuracy:.2f}")
OUTPUT:
New Sample Prediction: setosa
Model Accuracy: 1.00
RESULT:
Thus the To Write a program to demonstrate the working of the decision tree
based ID3 algorithm and apply this knowledge to classify a new sample has been
executed successfully.
Date :
Exercise No :
AIM:
ALGORITHM:
o Split the dataset into training and testing sets using train_test_split.
4. Create the k-NN Classifier:
# Evaluate predictions
accuracy = accuracy_score(y_test, predictions)
correct = sum(predictions == y_test)
wrong = len(y_test) - correct
RESULT:
AIM:
ALGORITHM:
Print the clustering labels from both the GMM and K-Means models.
Compare the silhouette scores to determine which algorithm provides
better clustering results.
CODING:
import pandas as pd
import numpy as np
from sklearn.preprocessing import StandardScaler
from sklearn.mixture import GaussianMixture
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score
data = pd.read_csv('your_dataset.csv')
data.dropna(inplace=True)
#features
X = data.iloc[:, :-1].values
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
gmm.fit(X_scaled)
gmm_labels = gmm.predict(X_scaled)
kmeans.fit(X_scaled)
kmeans_labels = kmeans.labels_
RESULT:
Thus the program Apply EM algorithm and K-Means algorithm to cluster a set of
data stored in a .CSV file and compare results of two algorithms sucessfully
executed
Date :
Exercise No :
6. Write a program to construct a Bayesian network considering
medical data. Use this model to demonstrate the diagnosis of heart
patients using standard Heart Disease Data Set. You can use
Java/Python ML libraryclasses/APL.
AIM:
To Write a program to construct a Bayesian network considering medical data
to diagnose heart disease prediction
ALGORITHM:
1. Import Libraries:
Split the dataset into training (80%) and testing (20%) sets.
5. Train the Naive Bayes Model:
import pandas as pd
import numpy as np
import warnings
warnings.filterwarnings('ignore')
df['Sex'] = le.fit_transform(df['Sex'])
df['ChestPainType'] = le.fit_transform(df['ChestPainType'])
df['RestingECG'] = le.fit_transform(df['RestingECG'])
df['ExerciseAngina'] = le.fit_transform(df['ExerciseAngina'])
df['ST_Slope'] = le.fit_transform(df['ST_Slope'])
x=df.drop(columns=['HeartDisease']) #Input
y=df['HeartDisease'] #Output
y_pred=NB.predict(x_test)
testPrediction = NB.predict([[29,0,2,100,106,1,2,80,1,1,1]])
if testPrediction==1:
print("The Patient Have Heart Disease,please consult the Doctor")
else:
print("The Patient Normal")
OUTPUT:
ACCURACY is 0.8206521739130435
The Patient Have Heart Disease,please consult the Doctor
RESULT:
ALGORITHM:
1. Data Preparation:
2.Train-Test Split:
Split the dataset into training and testing sets using train_test_split.
import numpy as np
import pandas as pd
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import MultinomialNB
from sklearn.metrics import accuracy_score, precision_score, recall_score
data = {
'document': [
'The quick brown fox jumps over the lazy dog',
'Never jump over the lazy dog quickly',
'Brown foxes are quick and jumping over dogs',
'A quick brown dog outpaces a quick fox',
'The lazy dog does not jump over the quick fox',
'Quick brown fox jumps over a lazy dog',
'A lazy dog does not jump quickly'
],
'category': [
'positive', 'negative', 'positive', 'positive', 'negative', 'positive',
'negative'
]
}
df = pd.DataFrame(data)
vectorizer = CountVectorizer()
X = vectorizer.fit_transform(df['document'])
y = df['category']
nb = MultinomialNB()
nb.fit(X_train, y_train)
y_pred = nb.predict(X_test)
print(f'Accuracy: {accuracy:.2f}')
print(f'Precision: {precision:.2f}')
print(f'Recall: {recall:.2f}')
test_document = 'Quick brown fox'
test_vector = vectorizer.transform([test_document])
test_prediction = nb.predict(test_vector)
if test_prediction == 'positive':
print("The document is classified as positive.")
else:
print("The document is classified as negative.")
OUTPUT:
Accuracy: 1.00
Precision: 1.00
Recall: 1.00
The document is classified as positive.
RESULT:
AIM:
To write java program to create package in java.
ALGORITHM:
1. Data Preparation:
Separate the dataset into features (X) and target variable (y).
Split the dataset into training and testing sets using train_test_split.
4. Making Predictions:
5. Plotting:
6. Output:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
data = {
'X': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
'Y': [3, 4, 2, 5, 6, 7, 8, 9, 10, 12]
}
df = pd.DataFrame(data)
X = df[['X']].values
y = df['Y'].values
model = LinearRegression()
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
plt.scatter(X, y, color='blue', label='Data Points')
plt.xlabel('X')
plt.ylabel('Y')
plt.title('Simple Linear Regression')
plt.legend()
plt.show()
print(f"Coefficient: {model.coef_[0]}")
print(f"Intercept: {model.intercept_}")
for i in range(len(X_test)):
print(f"Predicted: {y_pred[i]}, Actual: {y_test[i]}")
OUTPUT:
Coefficient: 1.1272727272727274
Intercept: 1.490909090909091
Predicted: 5.0, Actual: 5
Predicted: 11.0, Actual: 12
RESULT:
Thus python program to program to implement a simple linear regression to plot
a graph has been successfully executed.
Date :
Exercise No :
9. Build an Artificial Neural Network by implementing the Back
propagation algorithm and test the same using appropriate data sets.
AIM:
To Build an Artificial Neural Network by implementing the Back propagation
algorithm and test the same using appropriate data sets.
ALGORITHM:
1. Data Preprocessing:
o Load and preprocess the Iris dataset. Standardize the features and
one-hot encode the labels.
2. Initialize Parameters:
o Define the architecture of the neural network: input layer, hidden
layer, and output layer.
o Initialize weights and biases randomly.
3. Training:
o Perform forward propagation to calculate outputs.
o Compute error and perform backpropagation to update weights
and biases.
o Print the loss every 100 epochs.
4. Testing:
o Use the trained network to make predictions on the test data and
calculate accuracy.
CODING:
import numpy as np
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.metrics import accuracy_score
def sigmoid_derivative(x):
return sigmoid(x) * (1 - sigmoid(x))
# Initialize parameters
input_size = X_train.shape[1]
hidden_size = 4
output_size = y_train.shape[1]
learning_rate = 0.01
epochs = 500
# Training
for epoch in range(epochs):
# Forward pass
hidden_layer = sigmoid(np.dot(X_train, weights_input_hidden) +
bias_hidden)
output_layer = sigmoid(np.dot(hidden_layer, weights_hidden_output) +
bias_output)
# Compute error
error = y_train - output_layer
d_output = error * sigmoid_derivative(output_layer)
d_hidden = d_output.dot(weights_hidden_output.T) *
sigmoid_derivative(hidden_layer)
RESULT:
ALGORITHM:
1. Download and Install Weka:
o You can download Weka from the official website: Weka Download
o Follow the installation instructions specific to your operating system.
2. Prepare Your Dataset:
o Click on the "Open file..." button and load your dataset file (e.g.,
iris.arff or iris.csv).
5. Choose the SVM Classifier:
o You can configure the SVM parameters by clicking on the text next to
the "Choose" button.
o This will open a dialog where you can set parameters such as the
kernel type, complexity parameter (C), etc.
o For example, you can set the kernel type to PolyKernel for a
polynomial kernel or leave it as RBFKernel for a radial basis function
kernel.
7. Run the Classification:
o In the "Test options" section, choose how you want to evaluate your
model. You can use cross-validation (default is 10-fold) or a separate
test set.
o Click on the "Start" button to train and evaluate the SVM model.
8.View the Results:
Click on the text next to "Choose" (it will look like SMO -C 1.0 -L 0.001 -P
1.0E-12 -N 0 -V -1 -W 1 -K
"weka.classifiers.functions.supportVector.PolyKernel -E 1.0").
Set any desired parameters. For a simple linear kernel, use PolyKernel
with an exponent of 1.
SMO
...
a b c <-- classified as
50 0 0 | a = Iris-setosa
0 46 4 | b = Iris-versicolor
0 1 49 | c = Iris-virginica
RESULT:
Thus Using Weka tool for SVM classification for chosen domain application has
been executed successfully.