~EDA1~ import pandas as pd import numpy as np import seaborn as sns import matplotlib.pyplot as plt import warnings warnings.filterwarnings('ignore') df = pd.read_csv(r"C:\Users\johnz\OneDrive\Desktop\SEM VII\AIML Lab Codes\Toyota.csv") df df.head(5) df.tail(5) print(df.shape) df.select_dtypes(exclude=['object']).columns.tolist() mi = df.select_dtypes(exclude=['object']) mi.min() mi = df.select_dtypes(exclude=['object']) mi.max() mi = df.select_dtypes(exclude=['object']) mi.mode() df.isnull() boxplot = df.boxplot(figsize = (5,5), rot = 90, fontsize = '8', grid = False) mean = np.mean(df['KM']) std = np.std(df['KM']) print((df['KM']-mean)/std) df['KM-z_score'] = (df['KM'] - mean)/std print(df.head(5)) df.corr(numeric_only=True) sns.displot(df, x = 'HP', kde = True, fill= True) plt.show() df['Automatic'].value_counts().plot(kind='bar') plt.show() plt.figure(figsize=(10,5)) plt.subplot(1,2,1) sns.swarmplot(df['Price']) plt.subplot(1,2,2) sns.violinplot(df['Price']) plt.show() df.plot('Price','HP',kind='scatter') plt.show() plt.figure(figsize=(15,10)) sns.barplot(x = 'Price', y = 'HP', data = df[15:35], palette = 'plasma') plt.show() sns.countplot(df['Weight']) plt.show() sns.pairplot(df) plt.show() counts = df['Automatic'].value_counts() plt.bar(counts.index, counts.values) plt.xlabel('Automatic') plt.ylabel('Counts') plt.show() ________________________________________________________________ ~EDA2~ import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns import statistics as stats sns.set(color_codes = True) from sklearn.metrics import mean_squared_error, r2_score df = pd.read_csv(r"C:\Users\johnz\OneDrive\Desktop\SEM VII\AIML Lab Codes\Toyota.csv") df missing = df.isnull().sum() percentage = (df.isnull().sum()/len(df)) * 100 print(percentage) for col in df.columns: if df[col].isnull().sum() / len(df) * 100 < 10: if df[col].dtype != 'object': df[col].fillna(df[col].mean(), inplace=True) else: print("Percent") common = df.apply(lambda x: x.fillna(x.value_counts().index[0])) common df['FuelType'].unique() for col in percentage.index: if percentage[col] < 10 and pd.api.types.is_numeric_dtype(df[col]): df[col].fillna(df[col].interpolate(method='nearest'), inplace=True) for i in df: if df[i].isnull().sum()*100>10: df.drop([i],axis=1, inplace = True) print(i, "Dropped") print("Shape of dataset",df.shape) threshold = 4 outlier = [] temp = df['Doors'] mean = np.mean(temp) std = np.std(temp) ind = 0 for i in temp: z = (i-mean)/std if z > threshold: print(z, 'row dropped') temp.drop(index=[ind], axis=0, inplace=True) else: ind += 1 print(temp.head()) df.sort_values('KM', ascending = False).drop_duplicates('HP').sort_index() plt.title("URK22RA1003 - John Zac Mathew") min = df['Price'] xscal = (min-min.min())/(min.max()-min.min()) sns.scatterplot(x=min, y=xscal) onehot = df['FuelType'] dum=pd.get_dummies(onehot, columns = ['Payment']) dum ________________________________________________________________ ~LR~ 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 from sklearn.metrics import mean_squared_error, r2_score data = {"Experience": [1,2,3,4,5,6,7,8,9,10], "Salary": [45000,50000,60000,65000,70000,75000,80000,85000,90000,95000]} df = pd.DataFrame(data) X = df[['Experience']] y = df['Salary'] X_train, X_test, y_train, y_test=train_test_split(X,y,test_size=0.2,random_state=42) model = LinearRegression() model.fit(X_train,y_train) y_pred = model.predict(X_test) print("Mean Squared Error(MSE):",mean_squared_error(y_test,y_pred)) print("R2Score:",r2_score(y_test,y_pred)) plt.scatter(X,y,color='blue',label='Actual Data') plt.plot(X,model.predict(X),color='red',linewidth=2,label='Regression Line') plt.xlabel('Years of Experience') plt.ylabel('Salary') plt.title('Linear Regression Example') plt.legend() plt.show() ________________________________________________________________ ~SLP~ import numpy as np from sklearn import datasets from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler from sklearn.linear_model import Perceptron from sklearn.metrics import accuracy_score iris = datasets.load_iris() X = iris.data y = iris.target X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) sc = StandardScaler() X_train_std = sc.fit_transform(X_train) X_test_std = sc.transform(X_test) perceptron = Perceptron(max_iter=100, eta0=0.1, random_state=0) perceptron.fit(X_train_std, y_train) y_pred = perceptron.predict(X_test_std) accuracy = accuracy_score(y_test, y_pred) print(f'Accuracy: {accuracy:.2f}') ________________________________________________________________ ~MLP~ from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split from sklearn.neural_network import MLPClassifier from sklearn.metrics import accuracy_score iris = load_iris() X, y = iris.data, iris.target X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42) mlp = MLPClassifier(hidden_layer_sizes=(10), activation='relu', max_iter=1000, random_state=42) #relu - Rectified Linear Unit mlp.fit(X_train, y_train) y_pred = mlp.predict(X_test) accuracy = accuracy_score(y_test, y_pred) print(f'MLP Classifier Accuracy: {accuracy:.4f}') ________________________________________________________________ ~KNN~ import pandas as pd import numpy as np from sklearn import datasets from sklearn.model_selection import train_test_split from sklearn.neighbors import KNeighborsClassifier from sklearn.metrics import accuracy_score iris = datasets.load_iris() X = iris.data y = iris.target df = pd.DataFrame(X, columns=iris.feature_names) df['target'] = y print("Dataset summary (using pandas describe):") print(df.describe(include='all')) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=24) k = 3 knn_classifier = KNeighborsClassifier(n_neighbors=k) knn_classifier.fit(X_train, y_train) y_pred = knn_classifier.predict(X_test) accuracy = accuracy_score(y_test, y_pred) print(f"\nAccuracy: {accuracy * 100:.2f}%") ________________________________________________________________ ~SVR~ import numpy as np import pandas as pd import seaborn as sns from sklearn import datasets from sklearn.model_selection import train_test_split from sklearn.svm import SVR from sklearn.metrics import mean_squared_error, r2_score import matplotlib.pyplot as plt iris = datasets.load_iris() X = iris.data y = iris.target iris_df = pd.DataFrame(data=np.c_[iris['data'], iris['target']], columns=iris['feature_names'] + ['target']) print(iris_df.head(150)) print(iris_df.info()) print(iris_df.describe()) print(iris_df['target'].unique()) y_regression = X[:,1] sns.pairplot(iris_df, hue='target', palette='rainbow') plt.show() X_train, X_test, y_train, y_test = train_test_split(X,y_regression,test_size=0.2, random_state=42) svr = SVR(kernel='rbf') #rbf = radial basis function | can put either rbf, linear, polynomial svr.fit(X_train, y_train) y_pred = svr.predict(X_test) mse = mean_squared_error(y_test, y_pred) #mse = mean squared error r2 = r2_score(y_test, y_pred) print("mean squared error:", mse) print("R- squared:", r2) plt.scatter(y_test, y_pred) plt.xlabel("Actual sepal length") plt.ylabel("Predicted sepal length") plt.title("SVR: Actual vs Predicted Sepal Length") plt.show() ________________________________________________________________ ~Fuzzy~ #Union of two fuzzy sets A= {"a":0.2, "b":0.3, "c":0.6, "d":0.6} B= {"a":0.9, "b":0.6, "c":0.4, "d":0.5} Y={ } print('The first fuzzy set is:', A) print('The second fuzzy set is:', B) for key in A: A_value = A[key] B_value = B.get(key, 0) Y[key] = max(A_value, B_value) print('Fuzzy set union is: ', Y) #Intersection of two fuzzy sets A= {"a":0.2, "b":0.3, "c":0.6, "d":0.6} B= {"a":0.9, "b":0.6, "c":0.4, "d":0.5} Y={ } print('The first fuzzy set is:', A) print('The second fuzzy set is:', B) for key in A: A_value = A[key] B_value = B.get(key, 0) Y[key] = min(A_value, B_value) print('Fuzzy set intersection is: ', Y) #Compliment of fuzzy sets A= {"a":0.2, "b":0.3, "c":0.6, "d":0.6} Y={ } print('The fuzzy set is:', A) for key in A: Y[key] = 1 - A[key] print('Fuzzy set compliment is: ', Y) #Scalar multiplication of fuzzy sets A = {"a": 0.2, "b": 0.3, "c": 0.6, "d": 0.6} alpha = 0.5 Y = {} print('The fuzzy set is:', A) print(f'Scalar multiplication by {alpha}:') for key in A: Y[key] = min(1, alpha * A[key]) print('Result of scalar multiplication is:', Y) #Fuzzy addition of two fuzzy sets A= {"a":0.2, "b":0.3, "c":0.6, "d":0.6} B= {"a":0.9, "b":0.6, "c":0.4, "d":0.5} Y={ } print('The first fuzzy set is:', A) print('The second fuzzy set is:', B) for key in set(A) | set(B): A_value = A.get(key,0) B_value = B.get(key, 0) Y[key] = min(1, A_value + B_value) print('Fuzzy addition of A and B is: ', Y) #Fuzzy subtraction of two fuzzy sets B= {"a":0.2, "b":0.3, "c":0.6, "d":0.6} A= {"a":0.9, "b":0.6, "c":0.4, "d":0.5} Y={ } print('The first fuzzy set is:', A) print('The second fuzzy set is:', B) for key in set(A) | set(B): A_value = A.get(key,0) B_value = B.get(key, 0) Y[key] = max(1, A_value + B_value) print('Fuzzy subtraction of A and B is: ', Y) ________________________________________________________________ ~NBC~ import numpy as np from sklearn import datasets from sklearn.model_selection import train_test_split from sklearn.naive_bayes import GaussianNB from sklearn.metrics import accuracy_score, classification_report, confusion_matrix iris = datasets.load_iris() X = iris.data #features y = iris.target #target variable(labels) X_train, X_test, y_train, y_test = train_test_split(X,y, test_size=0.2, random_state=42) clf = GaussianNB() clf.fit(X_train, y_train) y_pred = clf.predict(X_test) accuracy = accuracy_score(y_test, y_pred) confusion = confusion_matrix(y_test, y_pred) classification_rep = classification_report(y_test, y_pred, target_names=iris.target_names) print("Accuracy:", accuracy) print("Confusion matrix:") print(confusion) print("Classification report:") print(classification_rep) ________________________________________________________________ ~KMEAN~ import numpy as np import pandas as pd from sklearn import datasets from sklearn.cluster import KMeans import matplotlib.pyplot as plt iris = datasets.load_iris() X = iris.data y = iris.target df = pd.DataFrame(X, columns=iris.feature_names) print("Dataset preview:") print(df.head()) k = 3 kmeans = KMeans(n_clusters=k, random_state=42) kmeans.fit(X) df['Cluster'] = kmeans.labels_ print("\nCluster centers:\n", kmeans.cluster_centers_) print("\nFirst 10 cluster labels:\n", df['Cluster'].head(10)) plt.scatter(X[:,0], X[:,1], c=kmeans.labels_, cmap='rainbow') plt.scatter(kmeans.cluster_centers_[:,0],kmeans.cluster_centers_[:,1],color='black', marker='X', s=200, label='Centroids') plt.title('K-Means Clustering (Iris Dataset)') plt.xlabel('Sepal Length (cm)') plt.ylabel('Sepal Width (cm)') plt.legend() plt.show() ________________________________________________________________ ~DFS~ def dfs(graph, start): visited = set() stack = [start] while stack : node = stack.pop() if node not in visited : visited.add(node) print(node) stack.extend([neighbor for neighbor in graph[node] if neighbor not in visited]) graph = {'A':['B','C'],'B':['D','E'],'C':['F'],'D':[],'E':['F'],'F':[]} print("Depth First Search:") dfs(graph,'A') ________________________________________________________________ ~BFS~ from collections import deque def bfs(graph, start): visited = set() queue = deque([start]) while queue : node= queue.popleft() if node not in visited: visited.add(node) print(node) queue.extend([neighbor for neighbor in graph[node] if neighbor not in visited]) graph = {'A':['B','C'],'B':['D','E'],'C':['F'],'D':[],'E':['F'],'F':[]} print("\nBreadth First Search:") bfs(graph,'A')