import pandas as pd from sklearn.model_selection import train_test_split from sklearn.neighbors import KNeighborsClassifier from sklearn.metrics import accuracy_score, confusion_matrix, classification_report # Sample data data = { 'Feature1': [2, 4, 4, 4, 6, 6, 6, 8, 8, 8], 'Feature2': [4, 2, 4, 6, 2, 4, 6, 2, 4, 6], 'Target': [0, 0, 0, 0, 1, 1, 1, 1, 1, 1] } df = pd.DataFrame(data) # Split data into features and target X = df[['Feature1', 'Feature2']] y = df['Target'] # Split dataset X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42) # Initialize and fit model knn = KNeighborsClassifier(n_neighbors=3) knn.fit(X_train, y_train) # Make predictions y_pred = knn.predict(X_test) # Evaluate model accuracy = accuracy_score(y_test, y_pred) conf_matrix = confusion_matrix(y_test, y_pred) class_report = classification_report(y_test, y_pred)
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter