Skip to content

Commit

Permalink
Added KNeighbors model to predict iris values
Browse files Browse the repository at this point in the history
  • Loading branch information
Seniru committed Jan 20, 2020
1 parent 0b62783 commit c4059a0
Showing 1 changed file with 42 additions and 0 deletions.
42 changes: 42 additions & 0 deletions Iris/iris_kneighbours.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
#Loading the necessary modules
import numpy as np
import pandas as pd

from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsRegressor
from sklearn.metrics import mean_absolute_error

#Loading the iris dataset
iris = datasets.load_iris()
iris_df = pd.DataFrame(
data= np.c_[iris['data'],
iris['target']],
columns= iris['feature_names'] + ['target']

)

neighbors = 4 #Best number of neigbors

#Setting our feature matrix
X = iris_df[["sepal length (cm)", "sepal width (cm)", "petal length (cm)", "petal width (cm)"]]
y = iris_df["target"]

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)

def score(X_train, X_test, y_train, y_test, neighbors):
sample_model = KNeighborsRegressor(n_neighbors=neighbors)
sample_model.fit(X_train, y_train)
return mean_absolute_error(sample_model.predict(X_test), y_test)

def getOptimumNeighbors(X_train, X_test, y_train, y_test):
for neighbors in range(3, 15):
print("Nodes: {} -> {}".format(neighbors, score(X_train, X_test, y_train, y_test, neighbors)))

#Uncomment this to check which number of neighbors perform best
#getOptimumNeighbors(X_train, X_test, y_train, y_test)

model = KNeighborsRegressor(n_neighbors=3)
model.fit(X_train, y_train)

print(mean_absolute_error(model.predict(X_test), y_test))

0 comments on commit c4059a0

Please sign in to comment.