Get in touch
or send us a question?
CONTACT

Using GaussianNB from scikit-learn to train a model

  1. Install scikit-learn if you haven’t already:
   pip install scikit-learn
  1. Import the necessary libraries:
   from sklearn.naive_bayes import GaussianNB
   from sklearn.model_selection import train_test_split
   from sklearn.datasets import load_iris
  1. Load a dataset: For this example, let’s use the Iris dataset.
   # Load the Iris dataset
   data = load_iris()
   X = data.data
   y = data.target
  1. Split the dataset into training and testing sets:
   X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
  1. Create and train the Gaussian Naive Bayes model:
   # Initialize the model
   model = GaussianNB()

   # Train the model
   model.fit(X_train, y_train)
  1. Make predictions and evaluate the model:
   # Make predictions on the test set
   y_pred = model.predict(X_test)

   # Evaluate the model
   from sklearn.metrics import accuracy_score
   accuracy = accuracy_score(y_test, y_pred)
   print(f"Accuracy: {accuracy}")

That’s it! This code will train a Gaussian Naive Bayes model on the Iris dataset and evaluate its accuracy. You can, of course, replace the Iris dataset with your own data.

Source: ChatGPT