data science
classification
March 24, 2022
[1]: import numpy as np from sklearn.naive_bayes import GaussianNB
[2]: X = np.genfromtxt('iris.csv', delimiter=',', skip_header=0)
[3]: X.shape
[3]: (150, 5)
[4]: # Shuffle X so that the classes are more uniformly distributed. np.random.seed(12) # having the same seed allows to always generate the same␣ ↪→pseudorandom numbers.
np.random.shuffle(X)
[5]: # Divide X into a training set (100 rows) and a test set (50 rows). X_train = X[:100, :4] # training set, features y_train = X[:100, 4] # training set, targets X_test = X[100:, :4] # test set, features y_test = X[100:, 4] # test set, targets
[6]: # The training set is used to train a model that will classify new examples. # The function fit takes two parameters: the features ( or attributes) and the␣ ↪→target.
model = GaussianNB().fit(X_train, y_train)
[7]: # Apply new test cases to the model, and store the predictions in a variable␣ ↪→y_pred.
y_pred = model.predict(X_test)
[8]: # Find the accuracy of the model # the accuracy of the model is found by counting the number of correct␣ ↪→predictions.
[9]: np.sum(y_pred == y_test)
[9]: 47
1
[10]: # accuracy in percentage np.sum(y_pred == y_test) / len(y_test) * 100
[10]: 94.0
[ ]:
2