File size: 4,818 Bytes
827cd15
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
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)

</html>