Vikhyath_11

a5

Dec 12th, 2024
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.27 KB | None | 0 0
  1. #program 5
  2. import pandas as pd
  3. from sklearn.model_selection import train_test_split
  4. from sklearn.neighbors import KNeighborsClassifier
  5. from sklearn import metrics
  6. # Load the dataset without specifying column names
  7. dataset = pd.read_csv("P5Data.csv")
  8. # Print the first few rows to check the data
  9. print(dataset.head())
  10. # Ensure that we only use the numeric columns for X (features)
  11. X = dataset.iloc[:, :-1].values # Features (all rows, all columns
  12. except the last)
  13. y = dataset.iloc[:, -1].values # Target (the last column)
  14. # Split the dataset into train and test sets
  15. Xtrain, Xtest, ytrain, ytest = train_test_split(X, y, test_size=0.10)
  16. # Initialize and train the classifier
  17. classifier = KNeighborsClassifier(n_neighbors=5).fit(Xtrain, ytrain)
  18. # Predict the labels for the test set
  19. ypred = classifier.predict(Xtest)
  20. # Print the results
  21. print("\nOriginal vs Predicted Labels:")
  22. for true, pred in zip(ytest, ypred):
  23. print(f"{true: <25} {pred: <25} {'Correct' if true == pred else
  24. 'Wrong'}")
  25. # Confusion matrix and classification report
  26. print("\nConfusion Matrix:")
  27. print(metrics.confusion_matrix(ytest, ypred))
  28. print("\nClassification Report:")
  29. print(metrics.classification_report(ytest, ypred))
  30. # Accuracy score
  31. print(f"Accuracy: {metrics.accuracy_score(ytest, ypred):.2f}")
Advertisement
Add Comment
Please, Sign In to add comment