"""
Created on 2024.2.21
@author: 2024.2.21
"""
import numpy as np
from sklearn import datasets
from sklearn. model_selection import train_test_split
from sklearn. metrics import classification_report, confusion_matrix
import operator
import random
def knn ( x_test, x_data, y_data, k) :
x_data_size = x_data. shape[ 0 ]
np. tile( x_test, ( x_data_size, 1 ) )
diffMat = np. tile( x_test, ( x_data_size, 1 ) ) - x_data
sqDiffMat = diffMat** 2
sqDistances = sqDiffMat. sum ( axis= 1 )
distances = sqDistances** 0.5
sortedDistances = distances. argsort( )
classCount = { }
for i in range ( k) :
votelabel = y_data[ sortedDistances[ i] ]
classCount[ votelabel] = classCount. get( votelabel, 0 ) + 1
sortedClassCount = sorted ( classCount. items( ) , key= operator. itemgetter( 1 ) , reverse= True )
return sortedClassCount[ 0 ] [ 0 ]
iris = datasets. load_iris( )
data_size = iris. data. shape[ 0 ]
index = [ i for i in range ( data_size) ]
random. shuffle( index)
iris. data = iris. data[ index]
iris. target = iris. target[ index]
test_size = 40
x_train = iris. data[ test_size: ]
x_test = iris. data[ : test_size]
y_train = iris. target[ test_size: ]
y_test = iris. target[ : test_size]
predictions = [ ]
for i in range ( x_test. shape[ 0 ] ) :
predictions. append( knn( x_test[ i] , x_train, y_train, 5 ) )
print ( classification_report( y_test, predictions) )
print ( confusion_matrix( y_test, predictions) )
"""
Created on 2024.2.21
@author: 2024.2.21
"""
from sklearn import neighbors
from sklearn import datasets
from sklearn. model_selection import train_test_split
from sklearn. metrics import classification_report
import random
from sklearn import model_selection
iris = datasets. load_iris( )
print ( iris)
data_size = iris. data. shape[ 0 ]
index = [ i for i in range ( data_size) ]
random. shuffle( index)
iris. data = iris. data[ index]
iris. target = iris. target[ index]
test_size = 40
x_train = iris. data[ test_size: ]
x_test = iris. data[ : test_size]
y_train = iris. target[ test_size: ]
y_test = iris. target[ : test_size]
model = neighbors. KNeighborsClassifier( n_neighbors= 3 )
model. fit( x_train, y_train)
prediction = model. predict( x_test)
print ( classification_report( y_test, prediction) )
scores = model_selection. cross_val_score( model, iris. data[ : , 1 : 3 ] , iris. target, cv= 3 , scoring= 'accuracy' )
print ( "Accuracy: %0.5f" % ( scores. mean( ) ) )