import numpy as np import pandas as pd from sklearn import datasets from sklearn.model_selection import train_test_split from sklearn.neighbors import KNeighborsClassifier, KNeighborsRegressor from sklearn.metrics import accuracy_score, confusion_matrix, classification_report, mean_squared_error, r2_score iris = datasets.load_iris() X = iris.data y = iris.target X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42) model = KNeighborsClassifier() model.fit(X_train, y_train) predictions = model.predict(X_test) accuracy = accuracy_score(y_test, predictions) confusion = confusion_matrix(y_test, predictions) report = classification_report(y_test, predictions) print("KNN Classification Performance Metrics:") print("Accuracy:", accuracy) print("Confusion Matrix:\n", confusion) print("Classification Report:\n", report) housing = datasets.fetch_california_housing() X = housing.data y = housing.target X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42) model = KNeighborsRegressor() model.fit(X_train, y_train) predictions = model.predict(X_test) mse = mean_squared_error(y_test, predictions) r2 = r2_score(y_test, predictions) print("\nKNN Regression Performance Metrics:") print("Mean Squared Error:", mse) print("R^2 Score:", r2)
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