Offline Notepad View raw

Shared snapshot

20RO2004

__ 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.readcsv(r"C:\Users\Desktop\Toyota.csv") df df.head(5) df.tail(5) print(df.shape) df.selectdtypes(exclude=['object']).columns.tolist() mi = df.selectdtypes(exclude=['object']) mi.min() mi = df.selectdtypes(exclude=['object']) mi.max() mi = df.selectdtypes(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-zscore'] = (df['KM'] - mean)/std print(df.head(5)) df.corr(numericonly=True) sns.displot(df, x = 'HP', kde = True, fill= True) plt.show() df['Automatic'].valuecounts().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(colorcodes = True) from sklearn.metrics import meansquarederror, r2score df = pd.readcsv(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.valuecounts().index[0])) common df['FuelType'].unique() for col in percentage.index: if percentage[col] < 10 and pd.api.types.isnumericdtype(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.sortvalues('KM', ascending = False).dropduplicates('HP').sortindex() min = df['Price'] xscal = (min-min.min())/(min.max()-min.min()) sns.scatterplot(x=min, y=xscal) onehot = df['FuelType'] dum=pd.getdummies(onehot, columns = ['Payment']) dum _

LR import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.modelselection import traintestsplit from sklearn.linearmodel import LinearRegression from sklearn.metrics import meansquarederror, r2score 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'] Xtrain, Xtest, ytrain, ytest=traintestsplit(X,y,testsize=0.2,randomstate=42) model = LinearRegression() model.fit(Xtrain,ytrain) ypred = model.predict(Xtest) print("Mean Squared Error(MSE):",meansquarederror(ytest,ypred)) print("R2Score:",r2score(ytest,ypred)) 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.modelselection import traintestsplit from sklearn.preprocessing import StandardScaler from sklearn.linearmodel import Perceptron from sklearn.metrics import accuracyscore iris = datasets.loadiris() X = iris.data y = iris.target Xtrain, Xtest, ytrain, ytest = traintestsplit(X, y, testsize=0.2, randomstate=42) sc = StandardScaler() Xtrainstd = sc.fittransform(Xtrain) Xteststd = sc.transform(Xtest) perceptron = Perceptron(maxiter=100, eta0=0.1, randomstate=0) perceptron.fit(Xtrainstd, ytrain) ypred = perceptron.predict(Xteststd) accuracy = accuracyscore(ytest, ypred) print(f'Accuracy: {accuracy:.2f}') _

MLP from sklearn.datasets import loadiris from sklearn.modelselection import traintestsplit from sklearn.neuralnetwork import MLPClassifier from sklearn.metrics import accuracyscore iris = loadiris() X, y = iris.data, iris.target Xtrain, Xtest, ytrain, ytest = traintestsplit(X, y, testsize=0.3, randomstate=42) mlp = MLPClassifier(hiddenlayersizes=(10), activation='relu', maxiter=1000, randomstate=42) #relu - Rectified Linear Unit mlp.fit(Xtrain, ytrain) ypred = mlp.predict(Xtest) accuracy = accuracyscore(ytest, ypred) print(f'MLP Classifier Accuracy: {accuracy:.4f}') _

KNN import pandas as pd import numpy as np from sklearn import datasets from sklearn.modelselection import traintestsplit from sklearn.neighbors import KNeighborsClassifier from sklearn.metrics import accuracyscore iris = datasets.loadiris() X = iris.data y = iris.target df = pd.DataFrame(X, columns=iris.featurenames) df['target'] = y print("Dataset summary (using pandas describe):") print(df.describe(include='all')) Xtrain, Xtest, ytrain, ytest = traintestsplit(X, y, testsize=0.3, randomstate=24) k = 3 knnclassifier = KNeighborsClassifier(nneighbors=k) knnclassifier.fit(Xtrain, ytrain) ypred = knnclassifier.predict(Xtest) accuracy = accuracyscore(ytest, 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.modelselection import traintestsplit from sklearn.svm import SVR from sklearn.metrics import meansquarederror, r2score import matplotlib.pyplot as plt iris = datasets.loadiris() X = iris.data y = iris.target irisdf = pd.DataFrame(data=np.c[iris['data'], iris['target']], columns=iris['featurenames'] + ['target']) print(irisdf.head(150)) print(irisdf.info()) print(irisdf.describe()) print(irisdf['target'].unique()) yregression = X[:,1] sns.pairplot(irisdf, hue='target', palette='rainbow') plt.show() Xtrain, Xtest, ytrain, ytest = traintestsplit(X,yregression,testsize=0.2, randomstate=42) svr = SVR(kernel='rbf') #rbf = radial basis function | can put either rbf, linear, polynomial svr.fit(Xtrain, ytrain) ypred = svr.predict(Xtest) mse = meansquarederror(ytest, ypred) #mse = mean squared error r2 = r2score(ytest, ypred) print("mean squared error:", mse) print("R- squared:", r2) plt.scatter(ytest, ypred) 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: Avalue = A[key] Bvalue = B.get(key, 0) Y[key] = max(Avalue, Bvalue) 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: Avalue = A[key] Bvalue = B.get(key, 0) Y[key] = min(Avalue, Bvalue) 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): Avalue = A.get(key,0) Bvalue = B.get(key, 0) Y[key] = min(1, Avalue + Bvalue) 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): Avalue = A.get(key,0) Bvalue = B.get(key, 0) Y[key] = max(1, Avalue + Bvalue) print('Fuzzy subtraction of A and B is: ', Y) _

NBC import numpy as np from sklearn import datasets from sklearn.modelselection import traintestsplit from sklearn.naivebayes import GaussianNB from sklearn.metrics import accuracyscore, classificationreport, confusionmatrix iris = datasets.loadiris() X = iris.data #features y = iris.target #target variable(labels) Xtrain, Xtest, ytrain, ytest = traintestsplit(X,y, testsize=0.2, randomstate=42) clf = GaussianNB() clf.fit(Xtrain, ytrain) ypred = clf.predict(Xtest) accuracy = accuracyscore(ytest, ypred) confusion = confusionmatrix(ytest, ypred) classificationrep = classificationreport(ytest, ypred, targetnames=iris.targetnames) 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.loadiris() X = iris.data y = iris.target df = pd.DataFrame(X, columns=iris.featurenames) print("Dataset preview:") print(df.head()) k = 3 kmeans = KMeans(nclusters=k, randomstate=42) kmeans.fit(X) df['Cluster'] = kmeans.labels_ print("\nCluster centers:\n", kmeans.clustercenters) print("\nFirst 10 cluster labels:\n", df['Cluster'].head(10)) plt.scatter(X[:,0], X[:,1], c=kmeans.labels, cmap='rainbow') plt.scatter(kmeans.clustercenters[:,0],kmeans.clustercenters_[:,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')