Pythonと機械学習の基礎確認

len() や過学習、RAG の top-k など、実装と学習理論の境目を英語の短問で確認する。資格の過去問コピーではない。

同梱問題集の公開抜粋です。最初は問題と選択肢だけ出します。正解と解説は各問の「正解と解説を見る」を開くまで見えません。作者の既定表示は Ultra Practicebook、ライセンスは MIT です。試験団体の過去問や市販問題集の転載ではありません。

この問題集の位置づけ

旧タイトル ai practice は中身を表していませんでした。問いは Python の組み込み、データ構造の計算量、前処理、モデルの性質、LLM の推論高速化です。E資格セットが数式と学習手順の日本語解説なのに対し、こちらは英語の短問で、実装者の語彙に寄せています。

Deep Learning Engineering セットとは、ニューラルネットの層・最適化・正則化の深さが違います。こちらは過学習の定義や PCA の方向など、最初に混線する概念です。同じ「AI」という見出しで量産した複製ではありません。

コードを実行する環境ではありません。用語の取り違えを先に潰すための確認です。過学習の定義が言えない週は、SageMaker のインスタンス名より先にこちらを期限どおり回してください。

学習目標

Python のコンテナと例外、計算量、前処理、古典的なモデル、LLM 周辺の用語を、隣の分野の用語と取り違えないようにする。tuple と list、MinMax と外れ値、k-NN と次元の呪いのように、実装で実際に踏み抜く点を残す。

対象者

業務で Python を書き始めた人。機械学習の講義を一通り聞いたが、用語が日本語の印象だけで残っている人。E資格や AWS セットの前に、共通語彙を英語で確認したい人。

学習方法

四択は誤答の用語がどの分野の語かを解説で確認する。記述は quantization のように、別名が複数ある語はスラッシュで覚える。教科書の決定木・実務MLと、同じ週に「用語の問題」と「長い説明」を分けて使う。

問題

先に自分で選んでから、折りたたみを開いてください。解説は正解の言い換えだけでなく、隣の選択肢が文に入らない理由や、一緒に覚える連語を書いています。番号だけ暗記せず、解説の文を一度声に出してから次へ進んでください。

問 1

Which function returns the length of a Python list?

  1. len()
  2. size()
  3. count()
  4. length()
正解と解説を見る

正解: len()

len() is Python's built-in function for returning the number of items in a container. size() is used in NumPy, count() counts occurrences of a specific element, and length() does not exist in Python. The stem asks: Which function returns the length of a Python list?. The keyed answer is 1. Options: len(); size(); count(); length(). Keep this in the python bucket, and reject the neighbor term that solves a different job.

問 2

Which keyword is used for exception handling in Python?

  1. catch
  2. except
  3. rescue
  4. error
正解と解説を見る

正解: except

Python uses try/except blocks for exception handling. 'catch' is used in Java and C++, 'rescue' is Ruby's keyword, and 'error' is not an exception-handling keyword in any major language. The stem asks: Which keyword is used for exception handling in Python?. The keyed answer is 2. Options: catch; except; rescue; error. Keep this in the python bucket, and reject the neighbor term that solves a different job.

問 3

True/False: A Python tuple is mutable.

正解と解説を見る

正解: false

Tuples are immutable sequences in Python. Once created, their elements cannot be changed, added, or removed. This immutability makes tuples hashable and usable as dictionary keys, unlike lists. The stem asks: True/False: A Python tuple is mutable.. The keyed answer is false. Keep this in the python bucket, and reject the neighbor term that solves a different job.

問 4

Which Big-O notation is the fastest?

  1. O(1)
  2. O(n)
  3. O(n log n)
  4. O(n^2)
正解と解説を見る

正解: O(1)

O(1) represents constant time complexity — the operation takes the same time regardless of input size. Examples include hash table lookup and array index access. O(n) is linear, O(n log n) is typical for efficient sorting, and O(n^2) is quadratic.

問 5

Which data is suitable for one-hot encoding?

  1. Ordinal category
  2. Nominal category
  3. Continuous value
  4. Image
正解と解説を見る

正解: Nominal category

One-hot encoding creates binary columns for each category and is ideal for nominal (unordered) categories like color or country. Ordinal categories have inherent order and are better served by label encoding. Continuous values and images require different representations.

問 6

Why is MinMaxScaler weak to outliers?

  1. Sensitive to outliers
  2. Slow
  3. Ignores categories
  4. Requires labels
正解と解説を見る

正解: Sensitive to outliers

MinMaxScaler normalizes features to a fixed range (typically 0-1) using min and max values. A single extreme outlier shifts the min or max dramatically, compressing all other values into a narrow band. StandardScaler or RobustScaler are more resilient alternatives.

問 7

Which advantage do Transformers have over RNNs?

  1. Recursion
  2. Parallelization
  3. Lower memory use
  4. Simplicity
正解と解説を見る

正解: Parallelization

Transformers process all positions simultaneously via self-attention, enabling massive parallelization during training. RNNs must process sequences step-by-step, creating a sequential bottleneck. This parallelism allows Transformers to train on much larger datasets efficiently.

問 8

True/False: Embeddings are used for similarity calculation.

正解と解説を見る

正解: true

Embeddings map discrete items (words, sentences, images) into dense continuous vector spaces where geometric distance reflects semantic similarity. Cosine similarity or Euclidean distance between embedding vectors is widely used for search, recommendation, and clustering tasks.

問 9

What issue occurs when top-k=1 in RAG retrieval?

  1. Missing relevant chunks
  2. Slow inference
  3. Encoding failure
  4. Overfitting
正解と解説を見る

正解: Missing relevant chunks

Setting top-k=1 retrieves only the single most similar chunk, which risks missing other relevant passages needed to answer the query completely. Increasing k improves recall at the cost of including some irrelevant context. A typical production setting uses k=3 to k=10.

問 10

Name one method to speed up LLM inference.

正解と解説を見る

正解: quantization

Quantization reduces model weights from higher precision (e.g. float32) to lower precision (e.g. int8 or int4), significantly reducing memory footprint and computation time. Other techniques include KV-cache optimization, speculative decoding, and model distillation.

問 11

What Python keyword opens a file safely?

  1. file()
  2. open()
  3. with open()
  4. new()
正解と解説を見る

正解: with open()

The 'with' statement combined with open() creates a context manager that automatically closes the file when the block exits, even if an exception occurs. Using open() alone requires manual close() calls, risking resource leaks.

問 12

True/False: Python lists can hold mixed data types.

正解と解説を見る

正解: true

Python lists are heterogeneous containers that can store objects of any type simultaneously, e.g. [1, 'hello', 3.14, None]. This flexibility comes from Python's dynamic typing — each list element is a reference to an object on the heap.

問 13

Which operation is fastest for hash maps?

  1. Insert
  2. Delete
  3. Lookup
  4. All of the above
正解と解説を見る

正解: All of the above

Hash maps (dictionaries in Python) provide average O(1) time complexity for insert, delete, and lookup operations by computing a hash of the key to directly index into a bucket array. Worst case is O(n) due to hash collisions, but this is rare with good hash functions.

問 14

What is the purpose of normalization?

  1. Unify scale
  2. Remove missing values
  3. Encode categories
  4. Remove outliers
正解と解説を見る

正解: Unify scale

Normalization rescales features to a common range (e.g. 0-1 for MinMaxScaler or zero mean and unit variance for StandardScaler). This prevents features with larger magnitudes from dominating distance-based algorithms like k-NN and gradient-based optimizers in neural networks.

問 15

Which model is sensitive to the curse of dimensionality?

  1. Logistic regression
  2. k-NN
  3. Naive Bayes
  4. Decision tree
正解と解説を見る

正解: k-NN

k-Nearest Neighbors relies on distance metrics to find similar data points. In high-dimensional spaces, distances between all points converge, making the notion of 'nearest' meaningless. This phenomenon is called the curse of dimensionality. Dimensionality reduction (e.g. PCA) is a common mitigation.

問 16

What is the goal of K-means?

  1. Classification
  2. Regression
  3. Clustering
  4. Dimensionality reduction
正解と解説を見る

正解: Clustering

K-means is an unsupervised clustering algorithm that partitions data into k groups by iteratively assigning points to the nearest centroid and updating centroids. It minimizes within-cluster sum of squared distances. It requires specifying k in advance and assumes roughly spherical clusters.

問 17

True/False: PCA is a dimensionality reduction method.

正解と解説を見る

正解: true

Principal Component Analysis (PCA) projects high-dimensional data onto a lower-dimensional subspace defined by the directions of maximum variance (principal components). It preserves as much information as possible while reducing feature count, helping with visualization, noise reduction, and computational efficiency.

問 18

What direction does PCA prioritize?

  1. Largest variance
  2. Smallest variance
  3. Lowest mean
  4. Random
正解と解説を見る

正解: Largest variance

PCA finds orthogonal axes (principal components) that capture the maximum variance in the data. The first component explains the most variance, the second the next most while being orthogonal to the first, and so on. Directions with minimal variance are discarded as noise.

問 19

What activation helps reduce vanishing gradients?

  1. Sigmoid
  2. Tanh
  3. ReLU
  4. Linear
正解と解説を見る

正解: ReLU

ReLU (Rectified Linear Unit) outputs max(0, x), providing a constant gradient of 1 for positive inputs. Sigmoid and tanh saturate at extreme values, producing near-zero gradients that vanish through deep layers during backpropagation. ReLU largely solved this problem, enabling training of much deeper networks.

問 20

Which optimizer adaptively adjusts learning rates?

  1. SGD
  2. Adam
  3. RMSProp
  4. GD
正解と解説を見る

正解: Adam

Adam (Adaptive Moment Estimation) maintains per-parameter learning rates by combining momentum (first moment) and RMSProp (second moment) of gradients. This adaptive behavior helps navigate different curvatures in the loss landscape, typically converging faster than vanilla SGD.