Here’s a simple trainable AI program using Python that utilizes a basic machine learning model. This example demonstrates a text classifier using the sklearn library, where the AI can be trained to classify text into different categories.
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn.pipeline import make_pipeline
import joblib
def train_model():
# Sample training data (text and labels)
texts = ["hello", "hi", "greetings", "bye", "farewell", "see you"]
labels = ["greeting", "greeting", "greeting", "farewell", "farewell", "farewell"]
# Create a text classification pipeline
model = make_pipeline(CountVectorizer(), MultinomialNB())
# Train the model
model.fit(texts, labels)
# Save the trained model
joblib.dump(model, "text_classifier.pkl")
print("Model trained and saved as text_classifier.pkl")
def predict(text):
# Load the trained model
model = joblib.load("text_classifier.pkl")
# Make a prediction
label = model.predict([text])[0]
print(f"Predicted category: {label}")
return label
if __name__ == "__main__":
train_model()
# Test the model
user_input = input("Enter a text to classify: ")
predict(user_input)
This program:
- Trains a simple text classifier using the Naïve Bayes algorithm.
- Saves the trained model for future use.
- Loads the model to classify user input.
Try running the script and entering words like “hello” or “bye” to see how it predicts the category.