1/99
Looks like no tags are added yet.
ndarray
NumPy's array. A grid of numbers that are all the same type.
.shape
(rows, columns). Example: 2 rows, 3 columns → (2, 3)
.ndim
How many dimensions. One row = 1. A grid = 2.
dtype
The type of the numbers inside, like int64 or float32.
np.arange(8)
[0 1 2 3 4 5 6 7]. Counts from 0, stops BEFORE 8.
.reshape(2, 3)
Folds the numbers into 2 rows and 3 columns. Rows × columns must equal the total.
arr[r, c] vs arr[r]
arr[r, c] = one number at row r, column c. arr[r] = the whole row. Start counting at 0.
Slice start:stop:step
Grabs a range. The stop number is NOT included.
arr[:, 1]
Column 1 from every row.
arr[arr > 2]
Keeps only numbers bigger than 2. Gives back a flat list.
.sum(axis=0)
Adds DOWN each column. One answer per column.
.sum(axis=1)
Adds ACROSS each row. One answer per row.
ndarray vs list (types)
Array = one type only. List = can mix types.
[1,2,3]2 vs array2
List repeats: [1,2,3,1,2,3]. Array multiplies: [2 4 6].
np.split / hsplit / vsplit
Breaks an array apart. Gives back a LIST, not an array.
Figure
The frame. The whole image.
Axes
One chart inside the frame.
plt.subplots(2, 3)
Makes 2 rows × 3 columns = 6 charts.
Picking a chart in a 2×2 grid
ax[row, col]. Start at 0. ax[1, 0] = bottom-left.
Picking a chart in plt.subplots(1, 3)
Only one row, so use one number: ax[0], ax[1], ax[2].
Class rule for plt
Only use plt for plt.subplots() and plt.style.use(). Everything else uses ax or fig.
sharex / sharey
All charts use the same x (or y) number range, so they're easy to compare.
ax.set_title vs fig.suptitle
ax.set_title = title for one chart. fig.suptitle = title for the whole figure.
Legend shows nothing
You forgot label='…' when you plotted the data.
Line plot
Shows change over time. ax.plot()
Scatter plot
Shows how two number columns relate. ax.scatter()
Bar chart
Compares amounts between categories. ax.bar()
Pie chart
Shows parts of a whole (percents). ax.pie()
Histogram / box / violin
Show how values are spread out. Box plots also show outliers.
Plotting order
Style → subplots → plot data → labels and legend → savefig (last).
pandas
Package for tables with mixed data types. Built on NumPy.
Series
One column with labels.
DataFrame
A whole table. Many Series side by side.
pd vs df
pd = pandas itself (pd.read_csv). df = your table (df.head()).
pd.read_csv('file.csv')
Loads a CSV file into a DataFrame. First line becomes the column names.
skiprows=2
Skips the first 2 lines of the file.
df.info()
Shows column names, data types, and missing counts. No print() needed.
df['col']
Grabs ONE column. Gives a Series.
df[['a', 'b']]
Grabs MANY columns. Gives a DataFrame.
.iloc[]
Picks by position number. Slice end NOT included.
.loc[]
Picks by label or name. Slice end IS included.
df.loc[:4] vs df.iloc[:4]
loc = 5 rows (0–4). iloc = 4 rows (0–3).
Filtering rows
df[df['col'] > x] keeps only rows that pass the test.
df['old'] = … vs df['new'] = …
Old name = replaces that column. New name = adds a new column.
sort_values vs sort_index
sort_values(by='col') = sort by a column. sort_index() = sort by row labels.
Does sort_values change df?
No. You must save it: df = df.sort_values(…). Same for drop and dropna.
df.groupby('col')
Splits rows into groups. Does nothing until you add .mean(), .sum(), etc.
Data wrangling
Cleaning messy data so you can use it.
Cross sectional data
Many sources, one time. (All students' grades this semester.)
Time series data
One source, many times. (One class's enrollment each year.)
Panel data
Many sources, many times. (All students' grades every semester.)
df.drop_duplicates()
Removes repeated rows. Do it early, before picking columns.
Malformed data
Data typed in wrong. Example: a letter in a number column, or 'peter' in a yes/no column.
nunique() vs unique()
nunique() = how many different values. unique() = the list of them.
isnull().sum()
Counts missing values in each column.
df.dropna()
Deletes every row that has a missing value. Save it: df = df.dropna().
df.dropna(axis=1)
Deletes every column that has a missing value.
When to use dropna
After you pick your columns.
Box plot
Box = middle 50%. Line = median. Whiskers = normal range. Dots outside = outliers.
Outliers (this class)
Leave them alone.
Machine learning
Computers that learn from examples and get better with experience. Part of AI.
Algorithm vs model
Algorithm = the learning method. Model = what it learned.
Features (X)
The clues. The input columns used to make a guess.
Target (y)
The answer. The one column you're trying to guess.
Training
Showing the model clues AND answers so it can learn.
Supervised learning
Learns from examples that have answers (labels).
Unsupervised learning
No answers given. Finds groups on its own (clustering).
Reinforcement learning
Learns by trying actions and chasing a reward. (Self-driving car.)
ML process
1) Clean, split X/y, split train/test, scale. 2) Train. 3) Predict and check.
X = df.drop(columns='Species'), y = df['Species']
X = all columns except the answer. y = just the answer column.
train_test_split order
X_train, X_test, y_train, y_test
test_size=0.25
25% for testing, 75% for training.
stratify=y
Keeps the same mix of labels in the training and testing sets.
Why scale?
So big numbers (like grams) don't drown out small numbers (like years).
StandardScaler rules
Fit on X_train only. Transform X_train and X_test. Never scale y.
Re-wrap after scaling
The scaler gives back a plain array, so put it back in pd.DataFrame to keep column names.
KNN
Guesses by majority vote of the k closest examples.
How KNN predicts
Measure distance to every example → sort → take the k closest → most common label wins.
Effect of k
Changing k changes how many neighbors vote, which can change the answer.
.fit(X_train, y_train)
Trains the model.
.predict(X_test)
Makes guesses (y_pred).
.score(X_test, y_test)
Gives accuracy: how many guesses were right (0 to 1).
ANN
Artificial neural network. Layers of nodes connected like brain neurons.
Node
One circle (one neuron) in the network.
Weight
How much a connection counts. Changed during training.
Activation function
Decides what a node sends out.
Input / hidden / output layers
Input = features in. Output = answer out. Hidden = the mystery middle.
Perceptron
ONE artificial neuron.
MLP
Many perceptrons in layers. Signals only go forward.
Loss function
Measures how wrong the model is. Goal: make it small.
Backpropagation
Sends info backward to fix the weights so the model gets less wrong.
Underfit
Too simple. Misses the pattern.
Overfit
Memorized the training data. Bad on new data.
hidden_layer_sizes=(10, 10, 10)
3 hidden layers, 10 nodes each.
max_iter=1000
How many training rounds to adjust the weights.
Confusion matrix
Grid of real answers vs guesses. Diagonal = correct. Everything else = mistakes.
Precision
When it guessed "yes," how often was it right? TP / (TP + FP)
Recall
Of all the real "yes" ones, how many did it find? TP / (TP + FN)
F1-score
Precision and recall combined into one score.
Accuracy
Right guesses ÷ all guesses.