python from flask import Flask, request, jsonify from flask_cors import CORS import numpy as np from transformers import pipeline app = Flask(__name__) CORS(app) # Load AI models qa_pipeline = pipeline( "question-answering", model="distilbert-base-cased-distilled-squad", tokenizer="distilbert-base-cased" ) text_gen_pipeline = pipeline( "text-generation", model="gpt2", tokenizer="gpt2" ) @app.route('/api/chat', methods=['POST']) def chat(): data = request.json user_message = data.get('message', '').lower() # AI/ML specific responses ml_keywords = { 'backpropagation': explain_backpropagation, 'python': python_ml_example, 'gan': explain_gan, 'neural network': explain_neural_network, 'regression': explain_regression, 'classification': explain_classification } # Check for specific ML topics response = None for keyword, handler in ml_keywords.items(): if keyword in user_message: response = handler() break if not response: # Use QA model for general questions context = """ Machine learning is a field of artificial intelligence that uses statistical techniques to give computer systems the ability to "learn" from data. There are three main types: supervised learning (labeled data), unsupervised learning (unlabeled data), and reinforcement learning (reward-based). Popular algorithms include linear regression, decision trees, neural networks, and support vector machines. """ qa_result = qa_pipeline(question=user_message, context=context) if qa_result['score'] > 0.3: response = qa_result['answer'] else: # Fallback to text generation prompt = f"Q: {user_message}\nA:" gen_result = text_gen_pipeline( prompt, max_length=100, num_return_sequences=1, temperature=0.7 ) response = gen_result[0]['generated_text'].replace(prompt, '').strip() return jsonify({'response': response}) def explain_backpropagation(): return """Backpropagation is the algorithm used to train neural networks. It involves: 1. Forward pass: Compute predictions 2. Calculate loss between predictions and true values 3. Backward pass: Compute gradients of loss w.r.t. all parameters 4. Update weights using gradient descent The "back" in backpropagation refers to how gradients flow backward through the network from output to input layers.""" def python_ml_example(): return """Here's a simple machine learning example using scikit-learn: python from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split from sklearn.ensemble import RandomForestClassifier # Load dataset iris = load_iris() X, y = iris.data, iris.target # Split data X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2) # Create and train model model = RandomForestClassifier(n_estimators=100) model.fit(X_train, y_train) # Evaluate accuracy = model.score(X_test, y_test) print(f"Model accuracy: {accuracy:.2f}") """ def explain_gan(): return """GAN stands for Generative Adversarial Network. It consists of two neural networks: 1. Generator: Creates fake data samples 2. Discriminator: Tries to distinguish real from fake samples They compete in a game where the generator improves its outputs to fool the discriminator, while the discriminator gets better at detection. This adversarial process leads to highly realistic generated data.""" def explain_neural_network(): return """A neural network is a series of algorithms that attempts to recognize underlying relationships in data through a process that mimics how the human brain operates. Key components: - Input layer: Receives the data - Hidden layers: Perform computations (with weights and biases) - Output layer: Produces the final prediction - Activation functions: Introduce non-linearity (ReLU, sigmoid, tanh)""" def explain_regression(): return """Regression is a supervised learning technique for predicting continuous values. Common types: 1. Linear Regression: Models linear relationships 2. Polynomial Regression: Fits polynomial functions 3. Ridge/Lasso Regression: Regularized linear models 4. Logistic Regression: Despite the name, used for classification""" def explain_classification(): return """Classification is a supervised learning technique for predicting discrete class labels. Popular algorithms: 1. Decision Trees 2. Random Forest 3. Support Vector Machines (SVM) 4. Neural Networks 5. k-Nearest Neighbors (k-NN)""" if __name__ == '__main__': app.run(host='0.0.0.0', port=5000)