The title should say AI101 gets real, real fast.
Edit- This is AI101 through unit 3. This is what we are learning to do and understand. Turning words into math to train a learning AI system. This post is more or less giving people a view into what we are doing in later courses before you get there. Its not all fun and games like it was the first 2/3 of the AI software engineering program. If you don't get anything from this post maybe think of this as sending someone out ahead to scout the route. This is what everyone is in store for. By the End of AI101 unit 3, you will need to understand and explain all of this. This is terminal output of the result of running all files you will all have to write. Honestly, what almost scares me is this is just introduction to AI concepts and math foundations.
PRO TIP:
Here is a code sample, notice the format. The code becomes your notes.
"""
Classify support tickets using a smoothed Naive Bayes approach.
This module uses labeled training tickets to calculate the probability
that a new support ticket belongs to each known category.
For each category, the classifier combines:
- The prior probability of the category.
- The smoothed likelihood of each known word in the ticket.
Each distinct word contributes once to the category score, regardless
of how many times it appears in the original ticket.
Add-one smoothing prevents an observed word count of zero from
reducing an entire category score to zero.
The resulting category scores are normalized so they sum to 1.0.
The category with the highest normalized score becomes the prediction.
The held-out test dataset is used only to evaluate classification
performance. It is never used to calculate training statistics.
"""
# ============================================================
# 1. IMPORT DEPENDENCIES
# ============================================================
from tickets import load_tickets
from vectors import tokenize
# ============================================================
# 2. PREPARE TRAINING EXAMPLES
# ============================================================
def prepare_examples(examples):
"""
Prepare labeled training examples for probability calculations.
Each training ticket is tokenized and converted into a set of
distinct words. This ensures that repeated words within one
ticket contribute only one occurrence to word-category counts.
The function also calculates:
- The available category labels.
- The number of training tickets in each category.
- The vocabulary of known training words.
- The number of category tickets containing each word.
Args:
examples (list): Labeled training ticket dictionaries.
Each dictionary must contain:
- text: Original ticket text.
- category: Known category label.
Returns:
tuple: Contains:
- categories (list): Sorted category labels.
- category_counts (dict): Number of tickets per category.
- vocabulary (set): Unique words from training tickets.
- word_counts (dict): Word counts organized by category.
Raises:
ValueError: If the training examples are empty.
TypeError: If a ticket's text or category has an invalid type.
KeyError: If a training ticket is missing a required field.
"""
# 2.1 Verify that training examples are available.
if not examples:
raise ValueError("Training examples cannot be empty.")
# 2.2 Tokenize each training ticket and retain distinct words.
tokenized_examples = []
for example in examples:
if not isinstance(example["text"], str):
raise TypeError("Training ticket text must be a string.")
if not isinstance(example["category"], str):
raise TypeError("Training ticket category must be a string.")
tokenized_examples.append({
"category": example["category"],
"words": set(tokenize(example["text"])),
})
# 2.3 Identify every category represented in the training data.
categories = sorted({
example["category"]
for example in tokenized_examples
})
# 2.4 Build the vocabulary from training words only.
vocabulary = {
word
for example in tokenized_examples
for word in example["words"]
}
# 2.5 Count the number of training tickets per category.
category_counts = {
category: 0
for category in categories
}
for example in tokenized_examples:
category = example["category"]
category_counts[category] += 1
# 2.6 Count how many category tickets contain each word.
word_counts = {
category: {
word: 0
for word in vocabulary
}
for category in categories
}
for example in tokenized_examples:
category = example["category"]
for word in example["words"]:
word_counts[category][word] += 1
return categories, category_counts, vocabulary, word_counts
*****************************************************
This is my ticket_pipline.py and and its output:
****************************************************
"""
Coordinate the AI101 ticket-triage project by executing its individual
modules in a consistent sequence.
This module serves as the central entry point for the ticket-triage
project. It launches each selected component using its existing
standalone execution behavior, keeping the responsibilities of the
individual modules separate from project-level orchestration.
Each module remains independently executable and maintains ownership
of its own calculations, demonstrations, and evaluation output.
"""
# ============================================================
# 1. IMPORT DEPENDENCIES
# ============================================================
import runpy
# ============================================================
# 2. DEFINE THE EXECUTION SEQUENCE
# ============================================================
PIPELINE_MODULES = (
"stats",
"vectors",
"probability",
"router",
"classifier",
"bayes_router",
)
# ============================================================
# 3. EXECUTE PROJECT MODULES
# ============================================================
def run_pipeline():
"""
Execute the selected AI101 ticket-triage modules in sequence.
Each module is executed with its __main__ execution context,
allowing existing standalone demonstrations and evaluations
to run without duplicating their logic.
Returns:
None
Side Effects:
Prints output produced by each executed module.
Raises:
ImportError: If a requested module cannot be located.
Exception: If execution of a module raises an exception.
"""
print("=" * 60)
print("AI101 TICKET-TRIAGE PIPELINE")
print("=" * 60)
for module_name in PIPELINE_MODULES:
print("\n")
print("=" * 60)
print(f"RUNNING: {module_name.upper()}")
print("=" * 60)
runpy.run_module(module_name, run_name="__main__")
print("\n")
print("=" * 60)
print("TICKET-TRIAGE PIPELINE COMPLETE")
print("=" * 60)
# ============================================================
# 4. APPLICATION ENTRY POINT
# ============================================================
if __name__ == "__main__":
run_pipeline()
============================================================
AI101 TICKET-TRIAGE PIPELINE
============================================================
============================================================
RUNNING: STATS
============================================================
Range: 4
Manual calculation:
Data: [2, 4, 6]
Variance: 2.6666666666666665
Standard deviation: 1.632993161855452
NumPy calculation:
Variance: 2.6666666666666665
Standard deviation: 1.632993161855452
Number of tickets: 240
Minimum word count: 2
Maximum word count: 20
First 10 word counts: [12, 7, 11, 7, 7, 6, 6, 20, 14, 3]
Ticket Word Count Histogram:
0-4: **************************************
5-9: **************************************************************************
10-14: ************************************************************************************************
15-19: ******************************
20-24: **
============================================================
RUNNING: VECTORS
============================================================
Number of training tickets: 240
Vocabulary size: 709
First 20 vocabulary words: ['"error', '"unable', '$', '$$', '$1', '$10','$8', '1', '10%', '10th', '2', '25%', '2fa', '30', '30-day', '3rd', '40%', '5', '500', '5000']
First ticket: How do I see which devices are signed in to my account?
Vector length: 709
First ticket vector: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
Query ticket: How do I see which devices are signed in to my account?
Top 3 by distance:
(3.3166247903554, 26, 'how do i stop paying')
(3.3166247903554, 154, 'How do I add a recovery phone number to my account?')
(3.4641016151377544, 10, 'how do i archive a notebook')
Top 3 by cosine:
(0.5222329678670935, 154, 'How do I add a recovery phone number to my account?')
(0.4635863249727653, 239, 'How do I download a copy of all my data before I close my account?')
(0.45643546458763845, 197, 'How do I change the email address on my account?')
Manual vector calculations:
Dot product: 14
Norm: 4.123105625617661
Distance: 1.4142135623730951
NumPy verification:
NumPy dot product: 14
NumPy norm: 4.123105625617661
NumPy distance: 1.4142135623730951
Distance vs cosine for [1,2] and [2,4]:
Distance: 2.23606797749979
Cosine: 0.9999999999999998
Cosine similarity verification:
Manual cosine: 0.9999999999999998
NumPy cosine: 0.9999999999999998
Distance vs cosine for [1,2] and [3,6]:
Distance: 4.47213595499958
Cosine: 0.9999999999999999
Distance vs cosine for [1,2] and [2,1]:
Distance: 1.4142135623730951
Cosine: 0.7999999999999998
============================================================
RUNNING: PROBABILITY
============================================================
=================================================================
SUPPORT TICKET PROBABILITY ANALYSIS
=================================================================
Training tickets: 240
Vocabulary size: 709
Categories: account, billing, other, technical
CATEGORY PRIORS
-----------------------------------------------------------------
account Count: 60 Prior: 0.2500
billing Count: 68 Prior: 0.2833
other Count: 32 Prior: 0.1333
technical Count: 80 Prior: 0.3333
WORD PROBABILITY ANALYSIS
-----------------------------------------------------------------
Word: refund
Word given category:
P(refund | account) = 0.0000 (0/60)
P(refund | billing) = 0.0735 (5/68)
P(refund | other) = 0.0000 (0/32)
P(refund | technical) = 0.0000 (0/80)
Category given word:
P(account | refund) = 0.0000 (0/5)
P(billing | refund) = 1.0000 (5/5)
P(other | refund) = 0.0000 (0/5)
P(technical | refund) = 0.0000 (0/5)
PYTHON AND NUMPY VERIFICATION
-----------------------------------------------------------------
All category counts match.
All category priors match.
All word-category counts match.
All word-given-category probabilities match.
All category-given-word probabilities match.
Verification successful.
REUSABLE FUNCTION EXAMPLES
-----------------------------------------------------------------
Prior for billing: 0.2833
P(refund | billing): 0.0735
P(billing | refund): 1.0000
=================================================================
PROBABILITY ANALYSIS COMPLETE
=================================================================
============================================================
RUNNING: ROUTER
============================================================
Router - Training:
{'correct': 98, 'total': 240, 'accuracy': 0.4083333333333333}
Router - Training Errors:
Total misses: 142
First Eight Training Errors:
{'id': 'T005', 'channel': 'web', 'text': 'The student discount code STUDY20 says it is invalid at checkout.', 'true': 'billing', 'pred': 'other'}
{'id': 'T006', 'channel': 'mobile', 'text': 'why did u take $10 not $8','true': 'billing', 'pred': 'other'}
{'id': 'T007', 'channel': 'mobile', 'text': 'pymt failed but $ left my acct', 'true': 'billing', 'pred': 'other'}
{'id': 'T009', 'channel': 'mobile', 'text': 'code from ur email didnt work', 'true': 'billing', 'pred': 'account'}
{'id': 'T011', 'channel': 'web', 'text': 'I want to downgrade from Team to Pro. Will I get a prorated credit for the rest of the month?', 'true':'billing', 'pred': 'other'}
{'id': 'T012', 'channel': 'web', 'text': 'When I export a note to PDF, the images are missing from the file.', 'true': 'technical', 'pred': 'other'}
{'id': 'T017', 'channel': 'mobile', 'text': 'checkboxes keep unchecking', 'true': 'technical', 'pred': 'other'}
{'id': 'T018', 'channel': 'mobile', 'text': 'still pending', 'true': 'account', 'pred': 'other'}
Majority Baseline - Training:
{'correct': 80, 'total': 240, 'accuracy': 0.3333333333333333}
Most common category: technical
Router - Test:
{'correct': 23, 'total': 60, 'accuracy': 0.38333333333333336}
Router - Test Errors:
Total misses: 37
First Eight Test Errors:
{'id': 'T003', 'channel': 'web', 'text': "The app uses 100% of my CPU when it's open in the background.", 'true': 'technical', 'pred': 'other'}
{'id': 'T010', 'channel': 'mobile', 'text': 'attachments wont download','true': 'technical', 'pred': 'other'}
{'id': 'T021', 'channel': 'web', 'text': "Drag and drop to move notes between notebooks doesn't work anymore.", 'true': 'technical', 'pred': 'other'}
{'id': 'T025', 'channel': 'mobile', 'text': 'keeps closing on iphone', 'true': 'technical', 'pred': 'other'}
{'id': 'T034', 'channel': 'web', 'text': 'I need to reset two-factor authentication for a user on our team.', 'true': 'account', 'pred': 'other'}
{'id': 'T040', 'channel': 'mobile', 'text': 'switched plans and got hit twice', 'true': 'billing', 'pred': 'other'}
{'id': 'T046', 'channel': 'web', 'text': "I keep getting logged out every few minutes while I'm editing.", 'true': 'technical', 'pred': 'other'}
{'id': 'T051', 'channel': 'web', 'text': 'The app crashes every time I open a notebook with more than 200 notes.', 'true': 'technical', 'pred': 'other'}
Majority Baseline - Test:
{'correct': 20, 'total': 60, 'accuracy': 0.3333333333333333}
Rule-Based Routing Demonstration:
Ticket: I was charged twice on my card and need a refund.
Trace: {'category': 'billing', 'fired_rules': ['billing_issue', 'route_billing']}
Non-Billing Account Demonstration:
Ticket: someone else got in??
Trace: {'category': 'other', 'fired_rules': []}
============================================================
RUNNING: CLASSIFIER
============================================================
TRAINING DATA
Training tickets: 240
Vocabulary size: 709
HELD-OUT TEST DATA
Test tickets: 60
K=1 RESULTS
Correct: 45/60
Accuracy: 75.00%
K=5 RESULTS
Correct: 45/60
Accuracy: 75.00%
K-NEAREST-NEIGHBOR COMPARISON
k=1 accuracy: 75.00%
k=5 accuracy: 75.00%
============================================================
CLASSIFICATION TRACE (k=1)
============================================================
New ticket: Can I pay for the Team plan by bank transfer instead of a credit card?
Nearest training neighbors:
Neighbor 1
ID: T175
Category: account
Similarity: 0.4671
Text: Can I use a passkey instead of a password?
Vote counts:
account: 1
Predicted category: account
Confidence: 100.00%
============================================================
============================================================
CLASSIFICATION TRACE (k=5)
============================================================
New ticket: Can I pay for the Team plan by bank transfer instead of a credit card?
Nearest training neighbors:
Neighbor 1
ID: T175
Category: account
Similarity: 0.4671
Text: Can I use a passkey instead of a password?
Neighbor 2
ID: T011
Category: billing
Similarity: 0.4557
Text: I want to downgrade from Team to Pro. Will I get a prorated credit for the rest of the month?
Neighbor 3
ID: T121
Category: billing
Similarity: 0.4216
Text: can i pause for a bit
Neighbor 4
ID: T110
Category: billing
Similarity: 0.4140
Text: I'd like a refund for the annual plan. I bought it yesterday by mistake.
Neighbor 5
ID: T164
Category: billing
Similarity: 0.4140
Text: Can I get a refund for the unused months after cancelling my annual plan?
Vote counts:
account: 1
billing: 4
Predicted category: billing
Confidence: 80.00%
============================================================
============================================================
NEW DEMONSTRATION TICKET 1
============================================================
Input: App is logging me out every time I switch accounts.
k=1 prediction:
Category: technical
k=5 prediction:
Category: technical
Confidence: 40.00%
k=5 classification trace:
Neighbor 1
ID: T211
Category: technical
Similarity: 0.3536
Text: logs me out randomly
Neighbor 2
ID: T260
Category: billing
Similarity: 0.3354
Text: Please stop charging me. I deleted the app months ago.
Neighbor 3
ID: T106
Category: account
Similarity: 0.2887
Text: new email, how do i switch
Neighbor 4
ID: T203
Category: billing
Similarity: 0.2652
Text: I paid for Pro through the App Store. How do I get a receipt?
Neighbor 5
ID: T239
Category: technical
Similarity: 0.2500
Text: The dark mode setting resets to light mode every time I refresh the page.
============================================================
NEW DEMONSTRATION TICKET 2
============================================================
Input: Can I get an invoice for last month's charges?
k=1 prediction:
Category: billing
k=5 prediction:
Category: billing
Confidence: 100.00%
k=5 classification trace:
Neighbor 1
ID: T213
Category: billing
Similarity: 0.5145
Text: Please send me an invoice for last month's payment. My company needs it for reimbursement.
Neighbor 2
ID: T121
Category: billing
Similarity: 0.4330
Text: can i pause for a bit
Neighbor 3
ID: T293
Category: billing
Similarity: 0.4009
Text: how do i get invoice on phone
Neighbor 4
ID: T164
Category: billing
Similarity: 0.3780
Text: Can I get a refund for the unused months after cancelling my annual plan?
Neighbor 5
ID: T154
Category: billing
Similarity: 0.3608
Text: How do I get a refund for a gift subscription I bought forsomeone who already had Pro?
============================================================
NEW DEMONSTRATION TICKET 3
============================================================
Input: How do I reset my two-factor authentication?
k=1 prediction:
Category: account
k=5 prediction:
Category: account
Confidence: 80.00%
k=5 classification trace:
Neighbor 1
ID: T142
Category: account
Similarity: 0.5241
Text: How do I change my password? I can't find the setting.
Neighbor 2
ID: T300
Category: account
Similarity: 0.5203
Text: How do I download a copy of all my data before I close my account?
Neighbor 3
ID: T035
Category: billing
Similarity: 0.5071
Text: how do i stop paying
Neighbor 4
ID: T249
Category: account
Similarity: 0.4781
Text: How do I change the email address on my account?
Neighbor 5
ID: T186
Category: account
Similarity: 0.4729
Text: My employer set up my account. Now that I've left, how do I keep my personal notes?
============================================================
CLASSIFICATION DEMONSTRATIONS COMPLETE
============================================================
============================================================
RUNNING: BAYES_ROUTER
============================================================
=================================================================
NAIVE BAYES SUPPORT TICKET ROUTER
=================================================================
Training tickets: 240
Test tickets: 60
CATEGORY PRIORS
-----------------------------------------------------------------
account Count: 60 Prior: 0.2500
billing Count: 68 Prior: 0.2833
other Count: 32 Prior: 0.1333
technical Count: 80 Prior: 0.3333
Training vocabulary size: 709
=================================================================
BAYES CLASSIFICATION TRACE
=================================================================
Ticket: Can I pay for the Team plan by bank transfer instead of a creditcard?
Normalized category scores:
-----------------------------------------------------------------
billing 0.999562 (99.96%)
other 0.000380 (0.04%)
account 0.000058 (0.01%)
technical 0.000000 (0.00%)
Predicted category: billing
=================================================================
Actual category: billing
NEW TICKET DEMONSTRATIONS
=================================================================
=================================================================
BAYES CLASSIFICATION TRACE
=================================================================
Ticket: App is logging me out every time I switch accounts.
Normalized category scores:
-----------------------------------------------------------------
technical 0.483719 (48.37%)
other 0.383800 (38.38%)
billing 0.083996 (8.40%)
account 0.048484 (4.85%)
Predicted category: technical
=================================================================
=================================================================
BAYES CLASSIFICATION TRACE
=================================================================
Ticket: Can I get an invoice for last month's charges?
Normalized category scores:
-----------------------------------------------------------------
billing 0.974545 (97.45%)
other 0.013746 (1.37%)
account 0.011345 (1.13%)
technical 0.000364 (0.04%)
Predicted category: billing
=================================================================
=================================================================
BAYES CLASSIFICATION TRACE
=================================================================
Ticket: How do I reset my two-factor authentication?
Normalized category scores:
-----------------------------------------------------------------
account 0.957134 (95.71%)
other 0.033725 (3.37%)
billing 0.009118 (0.91%)
technical 0.000023 (0.00%)
Predicted category: account
=================================================================
HELD-OUT TEST EVALUATION
=================================================================
Correct predictions: 45
Total test tickets: 60
Accuracy: 0.7500
Accuracy percentage: 75.00%
=================================================================
BAYES ROUTER COMPLETE
=================================================================
============================================================
TICKET-TRIAGE PIPELINE COMPLETE
============================================================