Courses3 levels
Level 1 · Foundations11 courses
Level 2 · Core5 courses
Level 3 · Advanced5 courses
Labs8 topics
Library Practice exams AI Range Pricing Start free

Foundations / How AI works

How AI works cheat sheet

Train a first model

TaskCommand
Make an environmentpython3 -m venv .venv
Activate itsource .venv/bin/activate
Install the pinned librariespip install -r requirements.txt
Record the versionspip freeze > my-versions.txt
Train on examplesmodel = LogisticRegression() then model.fit(X, y)
Predict a labelmodel.predict([sample])[0]
Predict a chancemodel.predict_proba([sample])[0][1]
Read the parametersmodel.coef_.round(3) and model.intercept_.round(3)

Load and split data

TaskCommand
Load the digitsX, y = load_digits(return_X_y=True)
Check the shapeX.shape
Count the classesnp.bincount(y)
Split the datatrain_test_split(X, y, test_size=0.25, random_state=42, stratify=y)
Train to the endLogisticRegression(max_iter=2000).fit(X_train, y_train)
Score on unseen datamodel.score(X_test, y_test)

Compare the kinds of training (lessons 4 and 5)

TaskCommand
Group points with no labelsKMeans(n_clusters=3, n_init=10, random_state=0).fit(X)
Count the points in each groupnp.bincount(km.labels_)
Make seeded groups of pointsmake_blobs(n_samples=[300, 150, 50], centers=centers, random_state=7)
Draw seeded random numbersrng = random.Random(11) then rng.random()
Learn from a rewardKeep the average reward of each action and mostly pick the best
Train in stepsSGDClassifier(loss="log_loss", random_state=0)
Fine-tune a trained modeltuned = copy.deepcopy(base) then tuned.partial_fit(X_new, y_new)
Pick rows with certain labelsnp.isin(y, [3, 8])
Shuffle the row numbersorder = np.random.default_rng(3).permutation(n)
Cut rows into sitesnp.split(order, [600, 1000]) or np.array_split(order, 4)
Average the weights of sitesnp.average([m.coef_ for m in models], axis=0, weights=sizes)
Write a note filecat > vendor-questions.txt <<'EOT', the lines, then EOT

Measure a model

TaskCommand
Score the answersaccuracy_score(y_test, pred)
Count every mistakeconfusion_matrix(y_test, pred)
Read each classclassification_report(y_test, pred, digits=3)
Find real alertsPrecision is TP / (TP + FP)
Find real attacksRecall is TP / (TP + FN)
Score a rare classrecall_score(y_true, pred) and precision_score(y_true, pred, zero_division=0)

Spot overfitting

TaskCommand
Limit a treeDecisionTreeClassifier(max_depth=depth, random_state=0).fit(X_train, y_train)
Count its leavestree.get_n_leaves()
See the signA high train score and a much lower test score
Cut a validation settrain_test_split(X_rest, noisy, test_size=0.25, random_state=42)
Repeat the splitcross_val_score(model, texts, labels, cv=5)

Train a neural network

TaskCommand
Scale the pixelsX = X / 16.0
Build the networkMLPClassifier(hidden_layer_sizes=(64,), max_iter=300, tol=1e-3, random_state=0)
Read the lossnet.loss_curve_
Count the epochsnet.n_iter_
Count the parameterssum(w.size for w in net.coefs_) + sum(b.size for b in net.intercepts_)

Search text by meaning

TaskCommand
Make word vectorsTfidfVectorizer(stop_words="english") then tfidf.fit_transform(texts)
Compress themTruncatedSVD(n_components=8, random_state=0) then svd.fit_transform(A)
Embed a querysvd.transform(tfidf.transform([query]))
Compare with the textscosine_similarity(q, V)[0]
Rank the nearestnp.argsort(-sims)[:k]

Clean a feed (lesson 10)

TaskCommand
Load a table (structured)list(csv.DictReader(f))
Load JSON lines (semi-structured)[json.loads(line) for line in f]
Load free text (unstructured)open("feed_c.dat").read()
Make case and spaces equal" ".join(text.lower().split())
Clean a feedkept, dropped = clean(rows)
Make label-keeping variantsaugment(kept)

Record the history of data (lesson 11)

TaskCommand
Hash a file in Pythonhashlib.sha256(open(path, "rb").read()).hexdigest()
Write a lineage recordpython lineage.py write lineage.json feed.csv clean.csv
Find a changed filepython lineage.py check lineage.json
Plant a canary rowecho '9001,ok,the violet heron files its report at dawn' >> shared.csv
Look for the canary in a suspect filegrep -ic "violet heron" suspect.csv

Build a text classifier (lesson 12)

TaskCommand
Chain the stepsPipeline([("tfidf", TfidfVectorizer(lowercase=True, ngram_range=(1, 2))), ("clf", LogisticRegression(C=10, max_iter=1000))])
Read the top wordsmodel["tfidf"].get_feature_names_out() and model["clf"].coef_[0]
Get the chancesmodel.predict_proba(tests)[:, 1]
Save the modeljoblib.dump(model, "phish.joblib")
Load the modeljoblib.load("phish.joblib")
Fingerprint the filesha256sum phish.joblib > phish.sha256
Check the fingerprintsha256sum -c phish.sha256
Write a model cardpython model_card.py

Judge a detector (lesson 13)

TaskCommand
Read a CSV of numbersnp.loadtxt("logins.csv", delimiter=",", skiprows=1)
Use a cut-off of 0.2(model.predict_proba(X_test)[:, 1] >= 0.2).astype(int)
Make a rare class count moreLogisticRegression(max_iter=1000, class_weight="balanced")

Safety habits