In [107]:
# Importing libraries
from pandas import read_csv
from matplotlib import pyplot
from sklearn.model_selection import train_test_split
from pandas.tools.plotting import scatter_matrix
from sklearn.model_selection import KFold
from sklearn.model_selection import cross_val_score
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from sklearn.naive_bayes import GaussianNB
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score
from sklearn.metrics import confusion_matrix
In [36]:
from sklearn.datasets import load_iris
data = load_iris()
In [38]:
# Load dataset
filename = 'D:\Machine Learning Mastery -Python\code\chapter_19\iris.data.csv'
names = ['sepal-length', 'sepal-width', 'petal-length', 'petal-width', 'class']
dataset = read_csv(filename, names=names)
In [42]:
# Summarise
# Descriptive Statistics
print(dataset.shape)
print(dataset.head(5))
print(dataset.describe())
print(dataset.groupby('class').size())
In [43]:
# Data Visualization
In [57]:
# Box and Whisker Plots
dataset.plot(kind='box', subplots=True,layout =(2,2),sharex=False )
pyplot.show()
In [69]:
# Histograms
dataset.hist()
pyplot.show()
In [66]:
scatter_matrix(dataset)
pyplot.show()
In [70]:
In [91]:
# Prepare Data
array = dataset.values
X = array[:,0:4]
Y = array[:,4]
validation_size=0.20
seed =7
X_train,X_Validation, Y_train,Y_Validation = train_test_split(X,Y,test_size=validation_size,random_state = seed)
In [94]:
# Spot -Check Algorithms
models = []
models.append(('LR',LogisticRegression()))
models.append(('LDA', LinearDiscriminantAnalysis()))
models.append(('KNN', KNeighborsClassifier()))
models.append(('CART',DecisionTreeClassifier()))
models.append(('NB',GaussianNB()))
models.append(('SVM',SVC()))
# Evaluate each model in turn
results = []
names = []
for name, model in models:
kfold = KFold(n_splits=10,random_state=seed)
cv_results = cross_val_score(model,X_train, Y_train,cv=kfold,scoring ='accuracy')
results.append(cv_results)
names.append(name)
msg = "%s: %f (%f)" %(name,cv_results.mean(),cv_results.std())
print(msg)
In [95]:
# Compare Algorithms
fig = pyplot.figure()
fig.suptitle('Algorithm Comparison')
ax = fig.add_subplot(111)
pyplot.boxplot(results)
ax.set_xticklabels(names)
pyplot.show()
In [110]:
from sklearn.metrics import classification_report
# Make Predictions
knn = KNeighborsClassifier()
knn.fit(X_train,Y_train)
predictions = knn.predict(X_Validation)
print(accuracy_score(Y_Validation,predictions))
print(confusion_matrix(Y_Validation,predictions))
print(classification_report(Y_Validation,predictions))
In [ ]: