Glossary
Every idea the lessons teach, in a sentence, with the lessons that teach it.
- accuracy
- The share of predictions that are right, such as 0.9 for 9 out of 10.
- Taught in Classification, Project: from data to a model, pk-ml-classify
- accuracy_score and .score
accuracy_score(y_true, y_pred)is the share of labels guessed right. A model's.score(X, y)gives accuracy for classifiers and R² for regressors.- Taught in pk-skl-models, Score a model
- agent loop
- Calling a model again and again, running the tools it asks for and feeding back the results, until it gives a final answer or reaches a step limit.
- Taught in The agent loop, pk-bai-retrieval
- aggregate functions
COUNT,SUM,AVG,MINandMAXturn many rows into one value, as inSELECT AVG(price) FROM items.- Taught in pk-sql-joins, Count, sum and group
- and, or, not
andis true when both sides are;orwhen either is;notflips true and false.- Taught in pk-py-logic, Combining conditions
- append
items.append(x)adds x to the end of a list, making it one longer.- Taught in pk-py-loops, Lists
- arithmetic
- Sums with
+,-,*and/.//divides and drops the remainder;%gives the remainder. - Taught in Numbers and expressions
- array
- A NumPy grid of numbers. Its shape, such as (3, 4), says how many rows and columns it has.
- Taught in From lists to arrays, pk-np-arrays
- assert
assert testdoes nothing when the test is True and stops with an AssertionError when it's False. A few asserts with known answers test a function.- Taught in Testing with assert, pk-fn-testing
- assignment
- Storing a value in a variable with
=. The right side is worked out first, then stored. - Taught in Values and variables
- axis
- Which way a sum or mean runs.
axis=0works down the columns;axis=1works along the rows. - Taught in Summarizing data, Project: a year of weather, pk-np-selecting
- balanced tree
- A tree whose branches are about the same height, so it has about log n levels and searches stay fast.
- Taught in Walking and balancing trees, pk-ds-trees
- bar chart
- One bar per group, for comparing categories:
plt.bar(names, values), orplt.barhfor sideways bars. Sort the bars and start the axis at 0. - Taught in Bar charts that compare, pk-pd-charts
- base case
- The input so small that a recursive function answers it straight away, without calling itself. Without one, the calls never stop.
- Taught in Functions that call themselves, pk-alg-recursion
- best so far
- Finding the biggest value by keeping the best so far, and replacing it whenever a bigger one comes along.
- Taught in While loops and patterns, Project: analyze a small dataset
- Big-O
- A way to describe how an algorithm's steps grow with the input size n, keeping only the fastest-growing part, such as O(1), O(n), O(n²) or O(2ⁿ).
- Taught in Big-O, pk-alg-search
- bigram
- Two neighboring words, such as
the cat. Counting bigrams records which words follow which. - Taught in Counting what follows, pk-ai-bigrams
- bigram model
- A language model that guesses the next word from the last word alone, using how often each word followed it in the training text.
- Taught in Chances from bigrams, pk-ai-bigrams
- binary search
- Finding an item in a sorted list by checking the middle and throwing away the half that can't hold it, again and again. About log₂ n comparisons, O(log n).
- Taught in Binary search in code, Linear and binary search, pk-alg-search
- binary search tree
- A tree of nodes where everything smaller is down the left branch and everything bigger is down the right, so a search picks one side at each node.
- Taught in Binary search trees, pk-ds-trees
- break and continue
breakends a loop at once.continueskips the rest of the current pass and moves on to the next item.- Taught in pk-py-loops, Stopping early
- broadcasting
- How NumPy combines arrays of different shapes, by stretching any side of size 1 to match.
- Taught in Math on whole arrays, pk-np-arrays
- byte-pair encoding
- Building a vocabulary by starting from single letters and merging the pair of neighbors that appears most often, again and again. Rare words become a few common pieces.
- Taught in Pieces of words
- calculated column
- A column worked out from others, row by row, with no loop:
df["income"] = df["price"] * df["sold"]. - Taught in Make new columns, pk-pd-grouping
- call stack
- The pile of function calls waiting for each other, newest on top. Each return takes the top call off and hands its answer to the one below.
- Taught in The call stack, pk-alg-recursion
- chart labels
plt.title,plt.xlabelandplt.ylabelname the chart and its axes. With several lines, give each alabel=and callplt.legend().- Taught in Your first chart, pk-pd-charts
- chat history
- The list of messages an app keeps and sends again on every call, since the model remembers nothing between calls. Often cut down to the last few turns.
- Taught in Remember the conversation, pk-bai-prompts
- chat messages
- What a chat model takes: a list of dicts, each with a
role(system, user or assistant) and itscontent. The system message sets the rules. - Taught in Prompts are strings, pk-bai-prompts
- chunking
- Splitting a long document into small pieces, often overlapping by a few words, so each piece can be searched and fits into a prompt.
- Taught in Split long documents
- class
- A blueprint for making objects that hold their own data, such as
Dog("Rex").__init__sets each new object up. - Taught in Objects and classes
- class design
- Choosing what a class stores and which methods may change it, so its objects always hold valid data.
- Taught in Designing a class, pk-ds-classes
- classification
- Predicting which group something belongs to, such as spam or not spam, rather than a number.
- Taught in Classification
- classifier
- A model that predicts a label, such as
KNeighborsClassifierorLogisticRegression. It uses the same fit and predict as any other model. - Taught in pk-skl-models, Classifiers
- code review
- Reading and testing code before trusting it, whoever or whatever wrote it. Edge-case tests and running the code catch most mistakes.
- Taught in Checking AI-written code
- column types
- Each column holds one type, such as int, float or str. Numbers stored as text add up wrongly until
.astype(int)converts them. - Taught in Clean messy data, pk-pd-grouping
- commit
con.commit()saves the changes made since the last commit;con.rollback()throws them away.cursor.rowcountsays how many rows a change touched.- Taught in pk-sql-joins, Change and delete rows
- comparison
- A test such as
x > 3orx == 3that gives True or False.==compares;=stores. - Taught in Decisions
- composition
- Building a class out of other objects it holds as attributes: a shelf has books.
- Taught in Objects inside objects, pk-ds-classes
- confusion matrix
- A table counting a classifier's right and wrong answers of each kind, such as true positives and false negatives.
- Taught in Is the classifier any good?, pk-ml-classify
- confusion_matrix
confusion_matrix(y_true, y_pred)counts right and wrong answers of each kind, rows for real labels and columns for predicted ones.precision_scoreandrecall_scorework from the same counts.- Taught in pk-skl-pipelines, Mistakes and thresholds
- context window
- How many of the latest words a model can look back over when it guesses the next one. Words further back drop out.
- Taught in More context, better guesses, pk-ai-next-word
- contiguous memory
- Slots side by side in one block, so any slot can be reached in one step from its number.
- Taught in How a list is stored
- copying
- Making a new object with the same contents, such as
a.copy(), so changes to one don't reach the other. - Taught in Names point to objects
- correlation
- A number from −1 to 1 for how closely two columns move together on a straight line. It shows a link, not a cause.
- Taught in Spot a relationship
- cosine similarity
- How closely two vectors point the same way:
a @ b / (norm(a) * norm(b)). 1 means the same direction; 0 means nothing in common. - Taught in Text as vectors
- counter
- A variable that starts at 0 and goes up by 1 each time something happens.
- Taught in While loops and patterns
- counterexample
- One input where a function gives the wrong answer. A single counterexample proves code is wrong, however many tests pass.
- Taught in Proving it works, pk-alg-sorting
- counting steps
- Measuring how much work code does by counting how often its main line runs, rather than timing it. A loop inside a loop over n items runs n × n times.
- Taught in Counting steps, pk-alg-search
- counting with a dictionary
- Keeping how often each thing appears:
counts[x] = counts.get(x, 0) + 1for each item. - Taught in pk-py-dicts, Dictionaries, Project: analyze a small dataset, Project: count the words
- cross-validation
- Cutting the rows into folds and testing on each one in turn:
cross_val_score(model, X, y, cv=5)gives one score per fold. Compare models by the mean. - Taught in pk-skl-pipelines, Cross-validation, Project: who will cancel?
- CSV and read_csv
- CSV is plain text with a header line and comma-separated values.
pd.read_csv(file)loads it; checkdf.dtypesafterward. - Taught in Read a CSV file
- data analysis
- Asking a question of data, then cleaning, selecting and summarizing it to answer.
- Taught in Project: a year of weather
- DataFrame
- A pandas table: named columns and numbered rows.
pd.DataFrame(data)makes one from a dictionary of lists;df.shapegives (rows, columns). - Taught in Tables with pandas, pk-pd-filtering
- debugging
- Finding and fixing a bug by checking what the code really does against what you expected, with prints, the traceback and a failing test.
- Taught in Finding the bug, pk-fn-testing
- decision boundary
- The edge between where a model says yes and where it says no. For one neuron with two inputs it's a straight line, w1·x + w2·y + b = 0.
- Taught in Decision boundaries
- decision threshold
- The chance above which a classifier says yes, 0.5 for
predict. Comparingpredict_probawith a lower threshold raises recall; a higher one raises precision. - Taught in pk-skl-pipelines, Mistakes and thresholds
- decision tree
- A model that learns a chain of yes-or-no questions about the features and follows them to an answer.
DecisionTreeClassifierin scikit-learn;export_textprints its rules. - Taught in pk-skl-pipelines, Decision trees
- default argument
- A parameter with a value to use when the call leaves it out, such as
def greet(name, greeting="Hi"). - Taught in pk-py-functions, More about functions
- dictionary
- Pairs of keys and values, such as
{'cat': 2}. You look a value up by its key. - Taught in pk-py-dicts, Dictionaries
- DISTINCT
SELECT DISTINCT city FROM shopsdrops repeated rows, so each city appears once.- Taught in pk-sql-queries, Sort, trim and dedupe
- dot product
- Multiply two lists of numbers pair by pair, then add the results.
np.dot(a, b)ora @ b. A model's weighted sum is a dot product. - Taught in Rows, columns and the dot product
- dunder method
- A method with double underscores, like
__init__or__repr__, that Python calls for you at the right moment. - Taught in Designing a class, pk-ds-classes
- dynamic array
- A row of slots that moves to a bigger block when it fills up. Python's list is one, so
appendaverages one step. - Taught in How a list is stored
- early return
- Leaving a function with
returnas soon as a special case is handled, so the rest of the function deals only with the usual case. - Taught in Return early, return clearly, pk-fn-return
- edge case
- An input at the limits, such as an empty list, zero, one item or a negative number, where code that works on normal input often breaks.
- Taught in Edge cases and bad input, pk-fn-testing
- element-wise
- Math on arrays that works cell by cell, so
a + badds each pair of matching numbers. - Taught in Math on whole arrays, pk-np-arrays
- embedding
- The list of numbers a model uses for a token. Words used in similar ways get nearby embeddings, and directions between them carry meaning.
- Taught in A map of meaning, pk-ai-bigrams
- error
- How far one prediction is from the real value, the prediction minus the actual value.
- Taught in Measuring error
- eval
- A set of test questions with expected answers, run against an AI app to get a pass rate and to catch regressions after a change.
- Taught in Test the answers, Project: a help-desk bot
- f-string
- A string with an
fbefore the quotes. Values in curly brackets are put into the text, as inf"{name} is {age}". - Taught in pk-py-strings, Text
- feature
- One input to a model, such as size or age. With several features a model has one weight for each:
w1 * x1 + w2 * x2 + b. - Taught in More than one input
- feature scaling
- Putting features on similar scales, for example by normalizing, so one big-numbered feature doesn't swamp training.
- Taught in More than one input
- feature table (X)
- What a scikit-learn model learns from: a 2-D table with one row per example and one column per feature, such as
[[500], [800]]. y holds one answer per row. - Taught in pk-skl-models, Your first scikit-learn model, Project: who will cancel?
- filtering rows
- Keeping the rows that meet a condition:
df[df["price"] > 3]. Join conditions with&(and) or|(or), each in brackets. - Taught in Filter rows, pk-pd-filtering
- fit and predict
- Every scikit-learn model learns with
model.fit(X, y)and answers withmodel.predict(X).fitreturns the model, soModel().fit(X, y)makes and trains it in one line. - Taught in pk-skl-models, Your first scikit-learn model
- flag
- A True or False variable set before a loop and switched inside it, so that after the loop it says whether something happened.
- Taught in Stopping early
- frequency analysis
- Cracking a code by counting letters. In English, e is the most common letter, so the commonest coded letter is probably a shifted e.
- Taught in Project: crack the code
- function
- Named code made with
def. It runs only when it is called, such asgreet("Ada"). - Taught in Functions, Project: analyze a small dataset, Project: count the words
- functions as values
- A function can be stored, put in a list or passed to another function, like
sorted(words, key=len). Without brackets you pass it; with brackets you call it. - Taught in Functions as values, pk-fn-pipelines
- gradient
- The slope of the loss for each weight, saying which way and how steeply the loss rises. Training steps against it.
- Taught in Training linear regression, pk-ml-training
- gradient descent
- Improving a model by stepping each weight a little way downhill on the loss, again and again.
- Taught in Gradient descent, pk-ml-training
- GROUP BY and HAVING
GROUP BY teamgives one result row per team, soSUM(points)adds up each team on its own.HAVINGfilters those groups after the sums are made.- Taught in pk-sql-joins, Count, sum and group, Project: a shop's database
- groupby
- Splitting rows by a label and summarizing each group:
df.groupby("team")["score"].mean()..size()counts the rows in each group. - Taught in Group and summarize, Project: a café's sales, pk-pd-grouping
- grouping
- Collecting items under a key in a dictionary of lists, such as every score for each team.
- Taught in Nested data
- grouping
- Splitting data by a label to compare the parts, with one mask per group such as
values[labels == "red"].mean(). Check each group's size before trusting its mean. - Taught in Group and compare, pk-np-groups
- hash table
- A structure that turns each key into a number, its hash, to pick a slot, so lookups take about one step. Python's dictionaries and sets are hash tables.
- Taught in How a dictionary finds things, pk-ds-trees
- hashable
- A value that can't change, so its hash stays the same and it can be a dictionary key or set member. Strings, numbers and tuples are; lists aren't.
- Taught in How a dictionary finds things, pk-ds-trees
- helper function
- A small function that does one clear job, so a bigger task can be built from steps that are each easy to test.
- Taught in Small helpers, one pipeline, pk-fn-pipelines
- histogram
- Bars counting how many values fall in each range:
plt.hist(values, bins=5). It shows the shape of the data and any outliers. - Taught in Scatter plots and histograms, pk-pd-charts
- if statement
- Runs its indented lines only when a test is true.
elifadds more tests;elsecatches the rest. - Taught in pk-py-logic, Decisions
- image classification
- Telling what a picture shows. The pixels are flattened into a row of numbers, scored against learned detectors, and the highest score wins.
- Taught in A network that reads shapes
- index
- A position in a string or list, counted from 0.
word[0]is the first letter;word[-1]is the last. - Taught in pk-py-strings, Text, Lists
- inheritance
- Making a class that starts with everything another class has, written
class Ebook(Book): an ebook is a book. - Taught in Objects inside objects, pk-ds-classes
- int and float
- An int is a whole number, such as 3. A float has a decimal point, such as 3.0. Dividing with
/always gives a float. - Taught in Numbers and expressions
- invariant
- Something true before a loop and after every pass, such as "total is the sum of the items seen so far". If it holds at the end, the answer is right.
- Taught in Proving it works, pk-alg-sorting
- JOIN
- Matches rows from two tables on a shared key:
FROM orders JOIN customers ON orders.customer_id = customers.id. Rows with no match are left out. - Taught in pk-sql-joins, Join two tables, Project: a shop's database
- lambda
- A small function with no name, written where it's used, such as
lambda p: p[1]. Handy forkey=. - Taught in Functions as values, pk-fn-pipelines
- language model
- A program that gives every possible next word a chance, given the words so far. Chatbots write by picking from those chances one word at a time.
- Taught in Guessing the next word
- layer
- A group of neurons that all take the same inputs. A hidden layer sits between the inputs and the output.
- Taught in A small neural network
- learning rate
- How big each gradient descent step is. Too small is slow; too big overshoots and never settles.
- Taught in Gradient descent, Training linear regression, pk-ml-training
- LEFT JOIN
- A join that keeps every row of the first table. Where the second table has no match, its columns come back as NULL, which Python shows as
None. - Taught in pk-sql-joins, Join two tables
- line chart
- Points joined by a line, for values that change in order, such as over time.
plt.plot(x, y)draws one with matplotlib. - Taught in Your first chart, pk-pd-charts
- linear search
- Checking items one by one until the target turns up. It works on any list and takes up to n comparisons, O(n).
- Taught in Linear and binary search, pk-alg-search
- linked list
- A chain of nodes, each holding a value and a reference to the next node. The last one points at
None. - Taught in Linked lists, pk-ds-linked
- linking and unlinking
- Inserting or removing a node in a linked list by changing which node a reference points at, so nothing has to shift.
- Taught in Changing a linked list, pk-ds-linked
- list
- Several values in order, in square brackets, such as
[4, 8, 15]. Items are numbered from 0. - Taught in Lists
- list comprehension
- A one-line way to build a list, such as
[n * 2 for n in nums if n > 0]. - Taught in List comprehensions
- log loss
- The usual loss for a classifier. It is small when the model gives the right answer a high chance, and huge when it is confidently wrong.
- Taught in Training a classifier
- logistic regression
- A classifier made of one neuron, trained with gradient descent so its sigmoid output gives the chance of yes.
- Taught in Project: from data to a model, Training a classifier
- loop patterns
- Common shapes of loop: building a new list, keeping only some items, and
enumerate, which gives each item with its position. - Taught in Loop patterns
- loss
- A number for how wrong a model is. Lower is better. Mean squared error is one way to measure it.
- Taught in Measuring error, Gradient descent
- loss (for a language model)
- How surprised the model was by the real next word:
-math.log(chance). A high chance gives a small loss; training brings the loss down. - Taught in Learning from surprise, pk-ai-next-word
- machine learning workflow
- The usual steps: prepare and split the data, choose a model, train it, then measure it on the test data.
- Taught in Project: from data to a model
- MAE and R²
mean_absolute_erroris the average gap between guesses and answers, in the units of y.r2_scoreis 1 for perfect guesses and 0 for no better than the mean.- Taught in pk-skl-models, Score a model
- making arrays
np.arange,np.linspace,np.zerosandnp.onesmake arrays without typing every number.- Taught in Making arrays, pk-np-arrays
- mask
- A grid of true and false that picks cells out of an array, such as
data[data > 5]. - Taught in Selecting data, Project: a year of weather, pk-np-selecting
- matrix multiplication
A @ Btakes the dot product of each row of A with each column of B. It is how a model predicts for many inputs at once.- Taught in Rows, columns and the dot product, pk-np-arrays
- max_depth
- The most questions a decision tree may ask in a row. A tree with no limit can memorize its training rows; a smaller depth often does better on test rows.
- Taught in pk-skl-pipelines, Decision trees
- mean
- The average. Add the numbers up and divide by how many there are. In NumPy,
a.mean(). - Taught in Summarizing data
- mean squared error
- Square each error, then take the mean. A common loss for predicting numbers.
- Taught in Measuring error, pk-ml-training
- membership (in)
x in thingsis True whenxis inside a list or a piece of text, or is one of a dictionary's keys.not inis the opposite.- Taught in In, and sets
- merge (join)
- Lining up two tables on a shared column:
pd.merge(a, b, on="id").how="left"keeps every row of the first table, with NaN where there's no match. - Taught in Join two tables, pk-pd-grouping
- merge sort
- Sorting by splitting the list in half, sorting each half the same way, and merging the sorted halves. O(n log n).
- Taught in Merge sort, pk-alg-sorting
- method
- A function defined inside a class. It receives the object as
self, so it can read and change that object's data. - Taught in Objects and classes
- missing value
- A gap in data, written
np.nanin NumPy.np.isnan(a)finds them; most sums give nan until they are removed or filled. - Taught in Cleaning data, pk-np-groups
- missing values (NaN)
- Gaps in data, shown as
NaN..isna().sum()counts them,.dropna()removes those rows, and.fillna(0)puts a value in each gap. - Taught in Clean messy data, Project: a café's sales, pk-pd-grouping
- model
- A rule that turns an input into a prediction, such as a line,
prediction = weight × x + bias. - Taught in What a model is, pk-ml-training
- model class
- A class that keeps a model's counts and the methods that train it and use it together in one object.
- Taught in A word predictor class
- mutation
- Changing a value in place, like
appendon a list. A list passed to a function can be changed by it, because both names refer to the same list. - Taught in Functions that change lists, pk-fn-return
- nearest neighbors
- Labeling a new point with the label most of its k closest known points have.
- Taught in Classification, pk-ml-classify
- nested data
- Lists and dictionaries inside each other, such as a list of dictionaries, one per person. Index step by step:
people[0]["name"]. - Taught in Nested data
- nested if
- An
ifinside anotherif. The inner test is checked only when the outer one is true. - Taught in pk-py-logic, Combining conditions
- nested loop
- A loop inside another loop. The inner loop runs all the way through for each pass of the outer one.
- Taught in pk-py-loops, Loop patterns
- neural language model
- A language model that works out its next-word chances with a neural network instead of counts, so it can generalize to word runs it never saw.
- Taught in From counting to learning
- neural network
- Layers of neurons where each layer's outputs are the next layer's inputs. Training adjusts every weight with gradient descent.
- Taught in A small neural network
- neuron
- A weighted sum passed through an S-shaped curve, giving a number between 0 and 1. The building block of neural networks.
- Taught in A single neuron
- next-word prediction
- Guessing what word comes next. A simple model divides how often each word followed the context by the total, so the chances add up to 1.
- Taught in Guessing the next word, pk-ai-next-word
- normalizing
- Subtracting the mean and dividing by the standard deviation, so data has mean 0 and standard deviation 1.
- Taught in Summarizing data, pk-np-selecting
- np.where
np.where(test, a, b)picks fromawhere the test is true and frombwhere it is false, cell by cell.- Taught in Cleaning data, pk-np-groups
- number formatting
- Saying how an f-string shows a value, after a colon in the braces:
{x:.2f}gives two decimal places, and{x:>6}pads to 6 characters. - Taught in Converting and formatting
- NumPy
- A Python library for working with whole grids of numbers at once, much faster than looping over a list.
- Taught in From lists to arrays
- ORDER BY and LIMIT
ORDER BY price DESCsorts the result, biggest first, andLIMIT 3keeps only the first 3 rows. Without ORDER BY, the row order isn't promised.- Taught in pk-sql-queries, Sort, trim and dedupe
- order of operations
- Python works out brackets first, then
*and/, then+and-, as in math. - Taught in Numbers and expressions
- overfitting
- When a model learns its training data too closely, quirks and all, and does worse on new data.
- Taught in Overfitting
- parameter
- A function's input box. Each call fills it with the value given, so
area(3, 4)sets width to 3 and height to 4. - Taught in pk-py-functions, Functions
- parsing
- Reading structure out of text, such as cutting
"Ada,36"into fields withsplit(",")and converting the numbers. - Taught in Reading data from text
- pattern recognition
- Telling what a picture or signal shows by the patterns in its numbers. A simple reader compares pixels with stored shapes; a network learns its own patterns.
- Taught in Reading digits
- pipeline
- Steps joined into one model with
make_pipeline(StandardScaler(), LogisticRegression()). Itsfitfits every step on the training rows, andpredictruns new rows through them in order. - Taught in pk-skl-pipelines, Project: who will cancel?, Scaling and pipelines
- pixel
- One square of a picture, stored as a number. A black-and-white image is a grid of 0s and 1s; greys run from 0 to 255; color keeps three grids.
- Taught in Images are numbers
- plotting from pandas
df.plot(x="a", y="b", kind="bar")draws a chart from a table's columns; a groupby result can.plot()itself too.- Taught in Charts straight from a table, Project: a café's sales, pk-pd-charts
- precision and recall
- Precision: of the items labeled yes, how many really were. Recall: of the real yeses, how many were found.
- Taught in Is the classifier any good?, pk-ml-classify
- precondition
- Something that must be true of a function's input. Check it at the start and
raise ValueErrorwith a clear message when it isn't. - Taught in Edge cases and bad input, pk-fn-testing
- predict_proba
- Gives each row's chance of every label, in the order of
model.classes_.predictpicks the label with the highest chance. - Taught in pk-skl-models, Classifiers
- preprocessing
- Cleaning text before tokenizing it, such as lower-casing and putting spaces around punctuation, so that the same word always becomes the same token.
- Taught in Tokens, not words
- Shows a value on the screen.
print("hi")shows hi; each call prints its own line. - Taught in Values and variables
- print and return
printshows a value on the screen;returnhands it back to the code that called the function. A function with noreturngives backNone.- Taught in Return early, return clearly, pk-fn-return
- prompt template
- A prompt with blanks that code fills in, such as
f"Summarize this: {text}". The instructions stay the same; only the details change. - Taught in Prompts are strings, pk-bai-prompts
- query parameters
- A
?in the SQL that sqlite3 fills from a tuple:con.execute("SELECT * FROM users WHERE name = ?", (name,)). Safer than building SQL with f-strings. - Taught in pk-sql-queries, Safe values with ?
- queue
- A collection where the first item added is the first taken out.
collections.dequeadds and removes at both ends in one step. - Taught in Stacks and queues, pk-ds-linked
- random numbers
np.random.default_rng(seed)makes a generator of random numbers. The same seed gives the same numbers every time.- Taught in Making arrays
- range
- A run of whole numbers.
range(3)gives 0, 1 and 2, stopping before the number given. - Taught in pk-py-loops, For loops
- record
- One item of data with named fields, often a dictionary such as
{"item": "pen", "price": 2}. A list of records is a small table. - Taught in Reading data from text
- recursion
- A function solving a problem by calling itself on a smaller version of it, until it reaches a base case.
- Taught in Functions that call themselves, pk-alg-recursion
- reference
- What a name holds: a pointer to an object, not the object itself. Two names can point at the same list.
- Taught in Names point to objects
- retrieval-augmented generation
- RAG for short. Find the chunks that best match a question and put them into the prompt, so the model answers from your documents and can cite them.
- Taught in Project: a help-desk bot, Look it up, then answer, pk-bai-retrieval
- return
- Hands a value back from a function, so the call can be stored or printed. Without it a function gives back None.
- Taught in pk-py-functions, Functions
- running total
- A variable that starts at 0 and has each item added to it in turn, so it ends as the sum.
- Taught in pk-py-loops, For loops
- sampling
- Picking at random, by the chances, as
random.choices(words, weights)does. It's why the same question can get different answers. - Taught in Temperature
- scatter plot
- One dot per row, with one number along the bottom and another up the side:
plt.scatter(x, y). It shows whether two numbers move together, not why. - Taught in Scatter plots and histograms, pk-pd-charts
- scope
- Where a variable can be seen. Variables made inside a function exist only during that call.
- Taught in pk-py-functions, More about functions
- SELECT
- Asks a database for rows:
SELECT name, age FROM pets, orSELECT *for every column. In Python,con.execute(...).fetchall()gives them as a list of tuples. - Taught in Your first query
- selection sort
- Sorting by finding the smallest remaining item and swapping it into the next place, over and over. Simple but O(n²).
- Taught in Sorting by hand, pk-alg-sorting
- Series (a column)
- One column of a table, picked with
df["name"]. It has summaries built in, such as.mean(),.max()and.sum(). - Taught in Tables with pandas, pk-pd-filtering
- set
- A collection that holds each value once, with no order, such as
{1, 2, 3}.a & bkeeps what both share, anda | bjoins them. - Taught in pk-py-dicts, In, and sets
- shadowing
- When a name inside a function hides the same name outside it, or when a variable like
sumhides Python's own function of that name. - Taught in Where names live, pk-fn-return
- shift cipher
- A secret code that moves every letter the same number of places along the alphabet, wrapping round from z to a. Shifting back decodes it.
- Taught in Project: shift one letter, Project: encode a message
- sigmoid
- An S-shaped curve that turns any number into one between 0 and 1. Big numbers give nearly 1; very negative ones nearly 0.
- Taught in A single neuron
- similarity search
- Scoring every document's vector against the question's, then keeping the best few, for example with
np.argsort(scores)[::-1][:k]. - Taught in Project: a help-desk bot, Search by similarity, pk-bai-retrieval
- slice
- A run of positions, such as
nums[1:4]. It starts at the first number and stops before the second. - Taught in Selecting data, pk-np-selecting, pk-py-strings, Text
- sorted list
- A list kept in order as it grows, often with
bisect.insort, so binary search can find items and ranges quickly. - Taught in Keeping a list sorted
- sorting
sorted(items)gives a new list in order;items.sort()puts the list itself in order. Addreverse=Truefor largest first.- Taught in pk-py-loops, More with lists
- sorting a table
df.sort_values("col")orders rows smallest first; addascending=Falsefor biggest first..head(n)ordf.nlargest(n, "col")keeps the top rows.- Taught in Sort and find the top, pk-pd-filtering
- sorting and ranking
np.sortputs values in order;np.argsortgives the positions they came from, so you can sort names by scores or a table's rows by one column.- Taught in Sort and rank, pk-np-groups
- split and join
text.split()breaks a string into a list of words." ".join(words)glues a list of strings back together.- Taught in pk-py-strings, Working with text
- SQL and pandas
pd.read_sql_query("SELECT ...", con)turns a query's result into a DataFrame, anddf.to_sql("name", con, index=False)saves a DataFrame as a table.- Taught in SQL meets pandas, Project: a shop's database
- SQL table
- Rows and named columns kept in a database.
CREATE TABLE pets (name TEXT, age INTEGER)makes one, andINSERT INTO pets VALUES ('Rex', 3)adds a row. - Taught in Your first query
- stack
- A collection where the last item added is the first taken out. A Python list works as one with
appendandpop. - Taught in Stacks and queues, pk-ds-linked
- standard deviation
- How spread out numbers are around their mean. Small when they sit close together. In NumPy,
a.std(). - Taught in Summarizing data, pk-np-selecting
- StandardScaler
- Shifts and stretches each column to a mean of 0 and a spread of 1, so no feature swamps the others.
fitlearns the means and spreads;transformapplies them. - Taught in pk-skl-pipelines, Scaling and pipelines
- string
- Text in quotes, such as
"hello".+joins two strings andlencounts the letters. - Taught in pk-py-strings, Text
- string method
- A function that belongs to a string, called with a dot, such as
name.upper()ortext.strip(). It gives back a new string. - Taught in pk-py-strings, Project: count the words, Working with text
- structured output
- Asking a model to reply in JSON so code can read it with
json.loads. Check for the keys you need, and ask again when a reply doesn't parse. - Taught in Ask for JSON, pk-bai-prompts
- sum, min and max
- Built-in functions that read a whole list:
sum(nums)adds it up,minandmaxgive the smallest and largest. - Taught in More with lists
- temperature
- A number that reshapes a model's chances before it picks. Low temperature makes the top word win nearly always; high temperature evens the chances out.
- Taught in Temperature, pk-ai-next-word
- test loss
- The loss measured on data kept aside from training. It shows how a model will do on data it has never seen.
- Taught in Overfitting
- text column methods
.strruns a string method on every value in a column, such asdf["city"].str.lower()or.str.contains("x").- Taught in Make new columns, pk-pd-grouping
- text generation
- Writing by repeatedly picking a next word by chance and adding it to the text, until a stopping word such as
.. - Taught in Project: build a language model
- text vector
- A text turned into a list of numbers, such as word counts over a fixed vocabulary. Embedding models make vectors that capture meaning, not just shared words.
- Taught in Text as vectors
- token budget
- Planning around a model's token limits and prices. Estimate about 4 characters per token, leave room for the reply in the context window, and drop old messages to fit.
- Taught in Count tokens, count costs, pk-bai-prompts
- tokenization
- Cutting text into tokens, the pieces a model reads, such as words, parts of words and punctuation. Each different token gets a number, its id.
- Taught in Tokens, not words, pk-ai-next-word
- tool call
- A model reply that names a function and its arguments, such as
{"tool": "add", "args": {"a": 2, "b": 3}}. The app runs the function and sends back the result. - Taught in Let the model use tools, pk-bai-retrieval
- traceback
- The report Python prints when code fails. Its last line names the error and the line number says where it happened.
- Taught in pk-py-dicts, When code goes wrong
- train and test split
- Keeping some labeled data aside to test on, so you see how a model does on data it has never seen.
- Taught in Classification, pk-ml-classify
- train_test_split
- Shuffles the rows and keeps some back:
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=0). Fit on the training rows, check on the test rows. - Taught in pk-skl-models, Project: who will cancel?, Train and test sets
- training
- Taking many gradient descent steps, so a model's weights fit the data better and the loss falls.
- Taught in Training linear regression, pk-ml-training
- training text
- The real writing a language model learns from. Words that often follow a context end up with higher chances after it.
- Taught in Learning from surprise
- transpose
- Swapping rows and columns.
a.Tturns a (2, 3) array into a (3, 2) array. - Taught in Rows, columns and the dot product, pk-np-arrays
- tree traversal
- Visiting every node of a tree, usually with recursion. An in-order walk visits the left branch, the node, then the right branch.
- Taught in Walking and balancing trees, pk-ds-trees
- try and except
tryruns code that might fail;exceptruns instead if it does, so the program can carry on.- Taught in pk-py-dicts, When code goes wrong
- tuple
- A fixed group of values in round brackets, such as
(3, 4). A function can return one, anda, b = pairunpacks it. - Taught in pk-py-functions, More about functions
- type conversion
- Turning a value into another type:
int("42")andfloat("4.5")turn text into numbers, andstr(42)turns a number into text. - Taught in Converting and formatting
- universal approximation
- The idea that a network with enough hidden neurons can fit almost any smooth curve, because each hidden neuron can add one step and steps can build any shape.
- Taught in Bending the line
- UPDATE and DELETE
UPDATE items SET price = 5 WHERE id = 2changes rows andDELETE FROM items WHERE id = 2removes them. Without WHERE, they hit every row.- Taught in pk-sql-joins, Change and delete rows
- variable
- A name that holds a value, such as
total = 0. Giving it a new value replaces the old one. - Taught in Values and variables
- weight and bias
- The numbers a model learns. In a line, the weight sets the steepness and the bias lifts it up or down.
- Taught in What a model is, pk-ml-training
- WHERE
- Keeps only the rows that pass a test:
SELECT * FROM pets WHERE age > 2 AND name LIKE 'R%'. SQL uses one=to compare. - Taught in pk-sql-queries, Pick rows with WHERE
- while loop
- Repeats its indented lines for as long as a test is true. Something inside must change, or it never stops.
- Taught in pk-py-loops, While loops and patterns
- word pair
- Two words next to each other, often kept as a tuple such as
("on", "the")so it can be a dictionary key. - Taught in More context, better guesses