A Python-based contextual chatbot that uses Natural Language Processing (NLP) and a neural network to understand and respond to user queries. The chatbot is trained on custom intents and can provide contextual responses based on user input.
- Natural Language Understanding using NLTK
- Neural Network-based response generation
- Customizable intents and responses
- Context-aware conversation handling
- Probability-based response selection
- GPU support for faster training (if available)
- Python 3.x
- PyTorch
- NLTK
- NumPy
-
Clone the repository:
git clone https://github.com/remicku/contextual-chatbot.git cd contextual-chatbot -
(Optional) Create the conda environment if it doesn't exist:
conda create -n pytorch python=3.9
-
Activate the environment:
conda activate pytorch
-
Install the required packages:
pip install torch nltk numpy
-
Download required NLTK data:
import nltk nltk.download('punkt')
chat.py- Main chatbot interface (interactive CLI)train.py- Script for training the neural network modelmodel.py- Neural network model architecturenltk_utils.py- NLP utility functions (tokenization, BoW)intents.json- Training data containing patterns and responsesdata.pth- Saved model state and metadata
-
Train the model (creates
data.pth):python train.py
-
Start chatting:
python chat.py
-
Deactivate the environment when you're done:
conda deactivate
Type 'quit' to exit the chat.
You can customize the chatbot's responses by modifying the intents.json file. The file structure should be:
{
"intents": [
{
"tag": "greeting",
"patterns": ["Hi", "Hello", "Hey"],
"responses": ["Hello!", "Hi there!", "Hey!"]
}
// Add more intents as needed
]
}Changes to this file require retraining the model (python train.py).
- Input Preprocessing: User input is tokenized and stemmed using NLTK
- Vectorization: The text is converted to a bag-of-words vector
- Prediction: A neural network processes the input and predicts the most likely intent (responses are selected based on the predicted intent and confidence threshold)
- Confidence Check: If the model's confidence > 75%, a matching response is chosen
- Fallback: Otherwise, a default fallback message is returned
The neural network consists of:
- Input layer: Size = vocabulary length
- Two hidden layers: 8 neurons each, ReLU activation
- Output layer: Size = number of unique intents
- Loss function: CrossEntropyLoss
- Optimizer: Adam
Contributions are welcome! Feel free to submit issues or open pull requests to improve this chatbot.