ml-batch(1)
ml-batch(1)
import numpy as nm
import matplotlib.pyplot as mtp
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import confusion_matrix
from matplotlib.colors import ListedColormap
from sklearn.preprocessing import LabelEncoder
from sklearn.metrics import confusion_matrix, accuracy_score
from sklearn.neighbors import KNeighborsClassifier
# input
x = dataset.iloc[:, [2,3]].values
x
Out[]:
array([[ 35, 20000],
[ 40, 43500],
[ 49, 74000],
...,
[ 28, 138500],
[ 48, 134000],
[ 44, 73500]])
# output
y = dataset.iloc[:, 4].values
y
Out[17]:
array([0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1,
…….. 0, 0, 0, 0, 1, 0, 0, 1, 1, 0])
sc = StandardScaler()
xtrain = sc.fit_transform(xtrain)
xtest = sc.transform(xtest)
knn = KNeighborsClassifier(n_neighbors=7)
knn.fit(xtrain, ytrain)
Out[]: KNeighborsClassifier(n_neighbors=7)
ypred = knn.predict(xtest)
print(ypred)
[1 0 1 0 0 0 1 1 1 0 0 0 0 0 1 1 0 0 1 0 0 0 0 1 1 0 0 0 1 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 1 0 0 1 1 1 1 1 0 0 0 1 0 1 1 0 0 0 1 1 1]
knn.score(xtest, ytest)
Out[]: 0.924
Accuracy : 92.4
cm = confusion_matrix(ytest, ypred)
print ("Confusion Matrix : \n", cm)
Confusion Matrix :
[[142 10]
[ 9 89]]
import numpy as nm
import matplotlib.pyplot as mtp
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import confusion_matrix
from matplotlib.colors import ListedColormap
from sklearn.preprocessing import LabelEncoder
from sklearn.metrics import confusion_matrix, accuracy_score
from sklearn.svm import SVC
Out[]:
<bound method NDFrame.head of User ID Gender Age AnnualSalary Purchased
0 385 Male 35 20000 0
1 681 Male 40 43500 0
2 353 Male 49 74000 0
3 895 Male 40 107500 1
4 661 Male 25 79000 0
.. ... ... ... ... ...
995 863 Male 38 59000 0
996 800 Female 47 23500 0
997 407 Female 28 138500 1
998 299 Female 48 134000 1
999 687 Female 44 73500 0
# input
x = dataset.iloc[:, [2,3]].values
x
Out[]:
array([[ 35, 20000],
[ 40, 43500],
[ 49, 74000],
...,
[ 28, 138500],
[ 48, 134000],
[ 44, 73500]])
# output
y = dataset.iloc[:, 4].values
y
Out[17]:
array([0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1,
…….. 0, 0, 0, 0, 1, 0, 0, 1, 1, 0])
sc = StandardScaler()
xtrain = sc.fit_transform(xtrain)
xtest = sc.transform(xtest)
ypred = classifier.predict(xtest)
print(ypred)
[1 0 0 0 0 0 0 1 1 0 1 0 0 0 0 0 0 1 1 0 0 0 0 1 1 0 0 0 1 0 0 0 0 0 0 0 0
0 0 0 0 1 0 1 0 0 0 1 1 1 1 1 0 0 0 1 0 1 1 0 0 0 1 1 0]
classifier.score(xtest, ytest)
Out[]: 0.84
Accuracy : 84.0
cm = confusion_matrix(ytest, ypred)
print ("Confusion Matrix : \n", cm)
Confusion Matrix :
[[138 14]
[ 26 72]]
X_set=x
y_set=y
for i, j in enumerate(nm.unique(y_set)):
plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1],
c = ListedColormap(('red','green','blue'))(i), label = j)
plt.xlim(0, 80)
plt.ylim(0, 180000)
plt.title('Classifier (Test set)')
plt.xlabel('Age')
plt.ylabel('Annual Salary')
plt.legend()
plt.show()
# Visualizing Test Results
X_set, y_set = xtest, ytest
X1, X2 = nm.meshgrid(nm.arange(start = X_set[:, 0].min() - 1, stop = X_set[:, 0].max() + 1,
step = 0.01),
nm.arange(start = X_set[:, 1].min() - 1, stop = X_set[:, 1].max() + 1, step =
0.01))
plt.contourf(X1, X2, classifier.predict(nm.array([X1.ravel(),
X2.ravel()]).T).reshape(X1.shape),
alpha = 0.75, cmap = ListedColormap(('red', 'green')))
plt.xlim(X1.min(), X1.max())
plt.ylim(X2.min(), X2.max())
for i, j in enumerate(nm.unique(y_set)):
plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1],
c = ListedColormap(('white', 'black'))(i), label = j)
plt.title('SVM (Test set)')
plt.xlabel('Age')
plt.ylabel('Estimated Salary')
plt.legend()
plt.show()
# USING RBF KERNAL FOR SVM
classifier = SVC(kernel = 'rbf', random_state = 0)
classifier.fit(xtrain, ytrain)
Out[]: SVC(random_state=0)
ypred = classifier.predict(xtest)
print(ypred)
[1 0 1 0 0 0 1 1 1 0 1 0 0 0 1 1 0 1 1 0 0 0 0 1 1 0 0 0 1 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 1 0 0 1 1 1 1 1 0 1 0 1 0 1 1 0 0 0 1 1 0]
classifier.score(xtest, ytest)
Out[]: 0.9
Accuracy : 90.0
cm = confusion_matrix(ytest, ypred)
print ("Confusion Matrix : \n", cm)
Confusion Matrix :
[[138 14]
[ 11 87]]
X_set=x
y_set=y
for i, j in enumerate(nm.unique(y_set)):
plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1],
c = ListedColormap(('red','green','blue'))(i), label = j)
plt.xlim(0, 80)
plt.ylim(0, 180000)
plt.title('Classifier (Test set)')
plt.xlabel('Age')
plt.ylabel('Annual Salary')
plt.legend()
plt.show()
# Visualizing Test Results
X_set, y_set = xtest, ytest
X1, X2 = nm.meshgrid(nm.arange(start = X_set[:, 0].min() - 1, stop = X_set[:, 0].max() + 1,
step = 0.01),
nm.arange(start = X_set[:, 1].min() - 1, stop = X_set[:, 1].max() + 1, step =
0.01))
plt.contourf(X1, X2, classifier.predict(nm.array([X1.ravel(),
X2.ravel()]).T).reshape(X1.shape),
alpha = 0.75, cmap = ListedColormap(('red', 'green')))
plt.xlim(X1.min(), X1.max())
plt.ylim(X2.min(), X2.max())
for i, j in enumerate(nm.unique(y_set)):
plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1],
c = ListedColormap(('white', 'black'))(i), label = j)
plt.title('SVM (Test set)')
plt.xlabel('Age')
plt.ylabel('Estimated Salary')
plt.legend()
plt.show()
Naïve bayes
import numpy as nm
import matplotlib.pyplot as mtp
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import confusion_matrix
from matplotlib.colors import ListedColormap
from sklearn.naive_bayes import GaussianNB
from sklearn.metrics import confusion_matrix, accuracy_score
dataset
Out[103]:
User ID Gender Age AnnualSalary Purchased
0 385 Male 35 20000 0
1 681 Male 40 43500 0
2 353 Male 49 74000 0
3 895 Male 40 107500 1
4 661 Male 25 79000 0
.. ... ... ... ... ...
995 863 Male 38 59000 0
996 800 Female 47 23500 0
997 407 Female 28 138500 1
998 299 Female 48 134000 1
999 687 Female 44 73500 0
# input
x = dataset.iloc[:, [2, 3]].values
x
Out[]:
array([[ 35, 20000],
[ 40, 43500],
[ 49, 74000],
...,
[ 28, 138500],
[ 48, 134000],
[ 44, 73500]])
# Target
y = dataset.iloc[:, 4].values
y
Out[]:
array([0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1,
….. 0, 0, 0, 0, 1, 0, 0, 1, 1, 0])
x2 = dataset.iloc[:, [2]].values
plt.scatter(x2,y)
plt.xlabel("Age")
plt.ylabel("Purchased")
plt.show()
x3 = dataset.iloc[:, [3]].values
plt.scatter(x3,y)
plt.xlabel("Salary")
plt.ylabel("Purchased")
plt.show()
# Splitting the dataset into the Training set and Test set
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size = 0.25, random_state = 0)
# Feature Scaling
sc = StandardScaler()
x_train = sc.fit_transform(x_train)
x_test = sc.transform(x_test)
print("Predicted values:")
print(y_pred)
Predicted values:
[1 0 1 0 0 0 0 1 1 0 1 0 0 0 0 1 0 1 1 0 0 0 0 1 1 0 0 0 1 0 0 0 0 0 0 0 0
0 0 0 0 0 0 1 1 0 0 1 1 1 1 1 0 0 0 1 0 1 1 0 0 0 1 1 0]
acc= accuracy_score(y_test,y_pred)*100
print ("\n\nAccuracy of Naïve Bayes Classifier: ", acc)
import warnings
warnings.filterwarnings('ignore')
Out[]:
<bound method NDFrame.head of Sepal Length Sepal Width Petal Length Peatal Width
Species
0 5.1 3.5 1.4 0.2 Iris-setosa
1 4.9 3.0 1.4 0.2 Iris-setosa
2 4.7 3.2 1.3 0.2 Iris-setosa
3 4.6 3.1 1.5 0.2 Iris-setosa
4 5.0 3.6 1.4 0.2 Iris-setosa
.. ... ... ... .. ...
145 6.7 3.0 5.2 2.3 Iris-virginica
146 6.3 2.5 5.0 1.9 Iris-virginica
147 6.5 3.0 5.2 2.0 Iris-virginica
148 6.2 3.4 5.4 2.3 Iris-virginica
149 5.9 3.0 5.1 1.8 Iris-virginica
# input
x = dataset.iloc[:, [0,1,2,3]].values
x
Out[]:
array([[5.1, 3.5, 1.4, 0.2],
[4.9, 3. , 1.4, 0.2],
[4.7, 3.2, 1.3, 0.2],
[4.6, 3.1, 1.5, 0.2],
[5. , 3.6, 1.4, 0.2],
………
sns.pairplot(dataset)
#Finding the optimum number of clusters for k-means classification
Elbow = []
for i in range(1, 11):
kmeans = KMeans(n_clusters = i, init = 'k-means++', max_iter = 300, n_init = 10, random_state = 0)
kmeans.fit(x)
Elbow.append(kmeans.inertia_)
#Plotting the results onto a Line graph, allowing us to observe ‘The Elbow’
plt.plot(range(1, 11), Elbow, marker='o')
plt.title('The Elbow method')
plt.xlabel('Number of clusters')
plt.ylabel('Elbow')
#within cluster sum of squares
plt.show()
distance_matrix = linkage(x, method = 'ward', metric = 'euclidean')
# Create a dendrogram
dn = dendrogram(distance_matrix)
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import confusion_matrix, accuracy_score
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn import metrics
import seaborn as sns
import warnings
warnings.filterwarnings('ignore')
# input
x = dataset.iloc[:, [0,1,2,3]].values
x
Out[]:
array([[5.1, 3.5, 1.4, 0.2],
[4.9, 3. , 1.4, 0.2],
[4.7, 3.2, 1.3, 0.2],
[4.6, 3.1, 1.5, 0.2],
[5. , 3.6, 1.4, 0.2],
………
# target
y = dataset.iloc[:, 4].values
y
Out[]:
array(['Iris-setosa', 'Iris-setosa', 'Iris-setosa', 'Iris-setosa',
….
'Iris-versicolor', 'Iris-versicolor', 'Iris-versicolor',
……
'Iris-virginica', 'Iris-virginica', 'Iris-virginica',
…..], dtype=object)
sc = StandardScaler()
xtrain = sc.fit_transform(xtrain)
xtest = sc.transform(xtest)
dtree= DecisionTreeClassifier()
dtree.fit(xtrain, ytrain)
Out[]: DecisionTreeClassifier()
y_pred1 = dtree.predict(xtest)
print("Predicted values:")
y_pred1
Predicted values:
Out[]:
array(['Iris-virginica', 'Iris-versicolor', 'Iris-setosa',
'Iris-virginica'], dtype=object)
acc_dtree= accuracy_score(ytest,y_pred1)*100
print ("\n\nAccuracy using Single Decision Tree: ", acc_dtree)
cm = confusion_matrix(ytest, y_pred1)
print ("\n\n Confusion Matrix for Single Decision Tree: \n", cm)
y_pred2 = RF.predict(xtest)
print("Predicted values:")
y_pred2
Predicted values:
Out[]:
array(['Iris-virginica', 'Iris-versicolor', 'Iris-setosa',
…… 'Iris-virginica'], dtype=object)
acc_rf= accuracy_score(ytest,y_pred2)*100
print ("\n\nAccuracy using Random Forest: ", acc_rf)
cm = confusion_matrix(ytest, y_pred2)
print ("\n\n Confusion Matrix for Random Forest Classifier: \n", cm)
Bagging
import numpy as nm
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import confusion_matrix
from matplotlib.colors import ListedColormap
from sklearn.metrics import confusion_matrix, accuracy_score
from sklearn import model_selection
from sklearn.ensemble import BaggingClassifier
from sklearn.naive_bayes import GaussianNB
import warnings
warnings.filterwarnings('ignore')
# input
x = dataset.iloc[:, [0,1,2,3]].values
x
Out[]:
array([[5.1, 3.5, 1.4, 0.2],
[4.9, 3. , 1.4, 0.2],
[4.7, 3.2, 1.3, 0.2],
[4.6, 3.1, 1.5, 0.2],
[5. , 3.6, 1.4, 0.2],
………
# target
y = dataset.iloc[:, 4].values
y
Out[]:
array(['Iris-setosa', 'Iris-setosa', 'Iris-setosa', 'Iris-setosa',
….
'Iris-versicolor', 'Iris-versicolor', 'Iris-versicolor',
……
'Iris-virginica', 'Iris-virginica', 'Iris-virginica',
…..], dtype=object)
# Splitting the dataset into the Training set and Test set
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size = 0.25, random_state = 0)
Single = GaussianNB()
Single.fit(xtrain, ytrain)
Out[]: GaussianNB()
y_pred = Single.predict(xtest)
print("Predicted values for single Naïve Bayes Classifier:")
y_pred
Predicted values for single Naïve Bayes Classifier:
Out[]:
array(['Iris-virginica', 'Iris-versicolor', 'Iris-setosa',
….
'Iris-versicolor'], dtype='<U15')
Acc_Single= accuracy_score(ytest,y_pred)*100
print ("\n\nAccuracy using single Naïve Bayes Classifier: ",Acc_Single)
cm = confusion_matrix(ytest, y_pred)
print ("\n\n Confusion Matrix -using single Naïve Bayes Classifier: \n", cm)
# bagging classifier
Bag = BaggingClassifier(base_estimator = base_cls, n_estimators = num_class, random_state
= 0)
Bag.fit(xtrain, ytrain)
Out[]: BaggingClassifier(base_estimator=GaussianNB(), n_estimators=100, random_state=0)
Boosting
import numpy as nm
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import confusion_matrix
from matplotlib.colors import ListedColormap
from sklearn.metrics import confusion_matrix, accuracy_score
from sklearn import model_selection
from sklearn.ensemble import AdaBoostClassifier
import warnings
warnings.filterwarnings('ignore')
# input
x = dataset.iloc[:, [0,1,2,3]].values
x
Out[]:
array([[5.1, 3.5, 1.4, 0.2],
[4.9, 3. , 1.4, 0.2],
[4.7, 3.2, 1.3, 0.2],
[4.6, 3.1, 1.5, 0.2],
[5. , 3.6, 1.4, 0.2],
………
# target
y = dataset.iloc[:, 4].values
y
Out[]:
array(['Iris-setosa', 'Iris-setosa', 'Iris-setosa', 'Iris-setosa',
….
'Iris-versicolor', 'Iris-versicolor', 'Iris-versicolor',
……
'Iris-virginica', 'Iris-virginica', 'Iris-virginica',
…..], dtype=object)
sc = StandardScaler()
xtrain = sc.fit_transform(xtrain)
xtest = sc.transform(xtest)
adaboost.score(xtest, ytest)
Out[]: 0.8947368421052632
y_pred = adaboost.predict(xtest)
print("Predicted values for AdaBoost Classifier:")
y_pred
Out[]:
array(['Iris-virginica', 'Iris-versicolor', 'Iris-setosa',
…..
'Iris-virginica'], dtype=object)
Acc_adaboost= accuracy_score(ytest,y_pred)*100
print ("\n\nTest Accuracy using AdaBoost Classifier: ", Acc_adaboost)
cm = confusion_matrix(ytest, y_pred)
print ("\n\n Confusion Matrix for AdaBoost Classifier: \n", cm)