210..127 Ai
210..127 Ai
SEMESTER – 7
Certificate
Date of Submission:
Professor Sign:
Introduction to Artificial Intelligence (3171105)
List of Experiments
EXPERIMENT: 1
AIM: Create a program using the Pandas, NumPy library that implements
grouping, filtering, sorting, and merging operations.
Code:
import pandas as pd
Players = {
'Name': ['Chirag', 'Sanket', 'Dharmit', 'Sumit'], # Updated some names to match
for merging
'Sports': ['Cricket', 'Football', 'Badminton', 'Volleyball'],
'Rating': [2, 8, 6, 4]
}
Placementdata = pd.DataFrame(Placement)
Playersdata = pd.DataFrame(Players)
# Display DataFrames
print("DataFrame 1:\n", Placementdata)
print("\nDataFrame 2:\n", Playersdata)
Output:
Introduction to Artificial Intelligence (3171105)
Conclusion:
Introduction to Artificial Intelligence (3171105)
EXPERIMENT: 2
Aim: Create a program using a sample dataset (heart disease data) to implement a
decision tree algorithm.
Code:
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeRegressor
from sklearn.metrics import mean_squared_error, r2_score
import matplotlib.pyplot as plt
from sklearn import tree
Output:
Conclusion:
Introduction to Artificial Intelligence (3171105)
EXPERIMENT: 3
Code:
import numpy as np
import pandas as pd
# Scale units
X = X / np.amax(X, axis=0) # Normalize features
y = y / np.max(y) # Normalize target price
class NeuralNetwork(object):
def __init__(self):
# Parameters
self.inputSize = 3 # Update to 3 for the selected features
self.outputSize = 1
self.hiddenSize = 4
# Weights
self.W1 = np.random.randn(self.inputSize, self.hiddenSize) # (3x4) weight
matrix from input to hidden layer
self.W2 = np.random.randn(self.hiddenSize, self.outputSize) # (4x1) weight
matrix from hidden to output layer
if deriv:
return s * (1 - s)
return 1 / (1 + np.exp(-s))
# Adjusting weights
self.W1 += X.T.dot(self.z2_delta) # Adjusting first set (input -> hidden)
weights
self.W2 += self.z2.T.dot(self.output_delta) # Adjusting second set (hidden ->
output) weights
Output:
Introduction to Artificial Intelligence (3171105)
Conclusion:
Introduction to Artificial Intelligence (3171105)
EXPERIMENT: 4
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler
from sklearn.linear_model import LinearRegression
import matplotlib.pyplot as plt
y = np.array(data['Prediction']) # Labels
y = y[:-1] # Shifted by one day
plt.figure(figsize=(10, 9))
plt.subplot(311)
plt.plot(data.index[-len(y_test):], y_test, label='True Price', color='green')
plt.subplot(312)
plt.plot(data.index[-len(y_test):], predictions, label='Predicted Price', color='red')
plt.subplot(313)
plt.plot(data.index[-len(y_test):], y_test, label='True Price', color='green')
plt.plot(data.index[-len(y_test):], predictions, label='Predicted Price', color='red')
plt.xlabel('Date')
Introduction to Artificial Intelligence (3171105)
plt.ylabel('Stock Price')
plt.title('Stock Price Prediction')
plt.legend()
plt.show()
Output:
Conclusion
Introduction to Artificial Intelligence (3171105)
EXPERIMENT: 5
Code:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
for _ in range(self.n_iter):
errors = 0
for x, target in zip(X, y):
update = self.learning_rate * (target - self.predict(x))
self.weights[1:] += update * x
self.weights[0] += update
errors += int(update != 0.0)
self.errors_.append(errors)
return self
# Use 'area' and 'parking' as features for simplicity (adjust according to your
preference)
X = data[['area', 'parking']].values
y = data['furnishingstatus'].values
# Data points
plt.subplot(1, 2, 1)
plt.scatter(X[y == 1][:, 0], X[y == 1][:, 1], color='green', marker='x',
label='Furnished')
plt.scatter(X[y == 0][:, 0], X[y == 0][:, 1], color='red', marker='o',
label='Unfurnished')
plt.xlabel('Area')
plt.ylabel('Parking')
plt.legend(loc='upper right')
plt.ylabel('Number of Updates')
plt.title('Perceptron Training Performance')
plt.tight_layout()
plt.show()
Output:
Conclusion:
Introduction to Artificial Intelligence (3171105)
EXPERIMENT: 6
Code:
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error, r2_score
# Assuming the dataset has columns like 'area', 'bedrooms', 'price', etc.
# Step 2: Data Cleaning and Preparation
# Drop rows with missing values
data = data.dropna()
Output:
Introduction to Artificial Intelligence (3171105)
Conclusion:
Introduction to Artificial Intelligence (3171105)
EXPERIMENT: 7
Code:
import numpy as np
import pandas as pd
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Input
import matplotlib.pyplot as plt
import sys
# Compile the model with mean squared error loss and Adam optimizer
model.compile(optimizer='adam', loss='mean_squared_error')
Output:
Conclusion:
Introduction to Artificial Intelligence (3171105)
EXPERIMENT: 8
Convolutional Layer
import tensorflow as tf
from tensorflow.keras import layers, models
import numpy as np
import matplotlib.pyplot as plt
# Reshape the data to include a channel dimension (since it's a grayscale image)
x_train = x_train.reshape(-1, 28, 28, 1)
x_test = x_test.reshape(-1, 28, 28, 1)
layers.MaxPooling2D((2, 2)),
layers.Flatten(),
layers.Dense(64, activation='relu'),
layers.Dense(10, activation='softmax') # 10 output classes for digits 0-9
])
plt.subplot(1, 2, 1)
plt.plot(history.history['accuracy'], label='Training Accuracy')
plt.plot(history.history['val_accuracy'], label='Validation Accuracy')
plt.title('Training and Validation Accuracy')
plt.legend()
Introduction to Artificial Intelligence (3171105)
plt.subplot(1, 2, 2)
plt.plot(history.history['loss'], label='Training Loss')
plt.plot(history.history['val_loss'], label='Validation Loss')
plt.title('Training and Validation Loss')
plt.legend()
plt.show()
Output:
Conclusion:
Introduction to Artificial Intelligence (3171105)
EXPERIMENT: 9
Code:
import cv2
import numpy as np
import tensorflow as tf
from tensorflow.keras.applications.mobilenet_v2
import preprocess_input, decode_predictions
import sys
import time
if not cap.isOpened():
print("Error: Could not open video stream.")
sys.exit()
return decoded_preds
# Release the video capture object and close the OpenCV window
cap.release()
cv2.destroyAllWindows()
Introduction to Artificial Intelligence (3171105)
Output:
Conclusion:
Introduction to Artificial Intelligence (3171105)
EXPERIMENT: 10
import numpy as np
import pandas as pd
import tensorflow as tf
import matplotlib.pyplot as plt
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import OneHotEncoder
tf.compat.v1.disable_eager_execution()
data = pd.read_csv('movie_reviews_dataset.csv')
print("Data Shape:", data.shape)
print(data.head())
x = tfidf.fit_transform(x_orig).toarray()
# Model parameters
alpha, epochs = 0.0035, 500
m, n = X_train.shape
print('m =', m)
print('n =', n)
print('Learning Rate =', alpha)
print('Number of Epochs =', epochs)
# Optimizer
# Use tf.compat.v1.train.GradientDescentOptimizer for compatibility with TensorFlow 2.x
optimizer =
tf.compat.v1.train.GradientDescentOptimizer(learning_rate=alpha).minimize(cost)
cost_history.append(sum(sum(c)))
accuracy_history.append(accuracy.eval({X: X_train, Y: y_train}) * 100)
if epoch % 100 == 0 and epoch != 0:
print("Epoch " + str(epoch) + " Cost: " + str(cost_history[-1]))
Weight = sess.run(W)
Introduction to Artificial Intelligence (3171105)
Bias = sess.run(b)
Output:
Introduction to Artificial Intelligence (3171105)
Conclusion: