Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #program 5
- import pandas as pd
- from sklearn.model_selection import train_test_split
- from sklearn.neighbors import KNeighborsClassifier
- from sklearn import metrics
- # Load the dataset without specifying column names
- dataset = pd.read_csv("P5Data.csv")
- # Print the first few rows to check the data
- print(dataset.head())
- # Ensure that we only use the numeric columns for X (features)
- X = dataset.iloc[:, :-1].values # Features (all rows, all columns
- except the last)
- y = dataset.iloc[:, -1].values # Target (the last column)
- # Split the dataset into train and test sets
- Xtrain, Xtest, ytrain, ytest = train_test_split(X, y, test_size=0.10)
- # Initialize and train the classifier
- classifier = KNeighborsClassifier(n_neighbors=5).fit(Xtrain, ytrain)
- # Predict the labels for the test set
- ypred = classifier.predict(Xtest)
- # Print the results
- print("\nOriginal vs Predicted Labels:")
- for true, pred in zip(ytest, ypred):
- print(f"{true: <25} {pred: <25} {'Correct' if true == pred else
- 'Wrong'}")
- # Confusion matrix and classification report
- print("\nConfusion Matrix:")
- print(metrics.confusion_matrix(ytest, ypred))
- print("\nClassification Report:")
- print(metrics.classification_report(ytest, ypred))
- # Accuracy score
- print(f"Accuracy: {metrics.accuracy_score(ytest, ypred):.2f}")
Advertisement
Add Comment
Please, Sign In to add comment