Page 233 - AI_Ver_3.0_class_11
P. 233

# Calculate accuracy
                     accuracy = metrics.accuracy_score(y_test, y_pred)

                     # Calculate precision
                     precision = metrics.precision_score(y_test, y_pred, average='weighted')
                     print("Accuracy:", accuracy)
                     print("Precision:", precision)
                 Output:

                     Accuracy: 1.0
                     Precision: 1.0
                 Now, if you want to validate the predictive accuracy of the model based on the sample data. For example:

                    [[3, 5, 4, 2], [2, 2, 5, 4]]
                  Program 64: To evaluate the metrics of the IRIS dataset based on the sample data for testing

                     from sklearn.model_selection import train_test_split

                     from sklearn.datasets import load_iris
                     from sklearn.neighbors import KNeighborsClassifier
                     from sklearn import metrics
                     # load dataset
                     iris = load_iris()

                     # separate the data into features and target
                     X = iris.data
                     y = iris.target
                     # Split the data: 80% for training, 20% for testing

                     X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=1)
                     # Splitting the data into training and testing sets (80% training, 20% testing)
                     X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_
                     state=1)
                     # Create a KNN classifier with 3 neighbors
                     knn = KNeighborsClassifier(n_neighbors=3)

                     # Train the KNN classifier on the training data
                     knn.fit(X_train, y_train)
                     # Use the trained classifier to make predictions on the test data
                     y_pred = knn.predict(X_test)

                     # Calculate accuracy
                     accuracy = metrics.accuracy_score(y_test, y_pred)
                     # Make a prediction based on the new sample data
                     sample = [[3, 5, 4, 2], [2, 2, 5, 4]]
                     prediction = knn.predict(sample)

                     prediction_species = [iris.target_names[p] for p in prediction]
                     print("Accuracy:", accuracy)
                     print("Predictions:", prediction_species)
                                                                                         Python Programming     231
   228   229   230   231   232   233   234   235   236   237   238