DATA-12 · DATA SCIENCE

누수 없는 전처리·학습 파이프라인Leakage-free preprocessing and pipelines

기억할 행을 정하고 대체·스케일·사전·모형을 함께 평가하기Choose fitting rows and evaluate imputation, scales, dictionaries and learners together

실습 6종 · 풀이 포함 연습문제 60개6 labs · 60 exercises with solutions

기초Foundations

1. 새 값 9를 보며 평균을 다시 구할까?1. Should a new value of nine change the fitted mean?

훈련용 숫자가 1과 3이고, 나중에 처리할 숫자가 9라고 합시다. 훈련 두 값의 평균은 (1+3)/2=2입니다. 평균을 빼는 변환을 정하면 훈련값은 −1과 1, 새 값은 9−2=7이 됩니다. 이때 기억한 숫자 2는 새 값을 보기 전에 두 훈련값으로 정했습니다.

세 값을 한꺼번에 평균하면 (1+3+9)/3=13/3입니다. 새 값의 중심화 결과도 9−13/3=14/3으로 달라집니다. 덧셈이 틀린 것이 아닙니다. 서로 다른 행에서 변환 규칙을 배운 것입니다. 새 대상을 볼 때 쓸 절차를 평가하려면 무엇을 먼저 볼 수 있는지부터 정해야 합니다.

DATA11에서 나눈 훈련·검증·시험 역할을 이제 전처리에도 적용합니다. 결측 대체값, 단위 조정, 범주 사전도 자료에서 배운 숫자이거나 규칙일 수 있습니다. 예측식 앞에 있다는 이유로 자료의 역할에서 자유로워지지는 않습니다.

Suppose training values are one and three, followed by a new value nine. The training mean is (1+3)/2=2. After deciding to subtract that remembered mean, training values become −1 and one, while the new value becomes 9−2=7. The remembered number two came from the two training rows.

Averaging all three values instead gives 13/3, so the new centered value becomes 14/3. Neither addition is wrong: the transformation learned from different rows. Evaluating a procedure for new targets starts by stating which information that procedure may use.

Carry DATA11’s training, validation and test roles into preprocessing. An imputation value, scale or category dictionary can itself be learned. Being placed before the prediction formula does not exempt it from those roles.

기초Foundations

2. 세 행의 원값·역할·변환값을 함께 둔다2. Keep values, roles and transformations together

아래는 실제 관측을 흉내 낸 설명용 세 행입니다. 원행 키는 변환 뒤에도 유지합니다. 새 행의 변환값이 훈련 두 값보다 커도 범위 밖 오류가 아닙니다. 평균을 빼는 규칙은 모든 실수 입력에 적용할 수 있습니다.

설명용 원행과 중심화
원행역할원값훈련 평균 2를 뺀 값
1훈련1-1
2훈련31
3새 행97

새 행을 평균 계산에 넣었는지는 표의 색보다 실제 합산에 들어간 키로 확인합니다. 이번 기억 목록은 {1, 2}입니다. 변환 대상 목록은 {1, 2, 3}이어도 기억 목록이 바뀌지 않습니다. 뒤 실습은 두 목록과 원래 결측 표시를 모두 반환합니다.

These are three toy rows, with source keys retained after transformation. A new transformed value larger than the training range is not automatically an error: subtracting a fixed mean is defined for every real input.

Toy records and centering
Source rowRoleOriginal valueSubtract training mean two
1Training1-1
2Training31
3New row97

Check the keys actually used in the sum, rather than relying on table colors. The fit set is {1, 2}. Transforming {1, 2, 3} does not change that fit set. The labs retain both lists and original missing flags.

기초Foundations

3. fit은 기억하기, transform은 기억을 적용하기다3. Fit remembers; transform applies that memory

평균 변환기를 작은 상자라고 생각해 봅시다. fit은 지정한 행을 읽어 평균 2를 상자에 저장합니다. transform은 각 입력에서 저장한 2를 뺍니다. transform이 새 목록을 받았다고 그 목록의 평균으로 저장값을 바꾸지 않습니다.

다시 fit을 호출하면 저장값이 바뀔 수 있습니다. 훈련용 상자와 검증용 상자를 따로 fit해 놓고 “둘 다 평균을 뺐다”고만 말하면 같은 좌표계를 썼는지 알 수 없습니다. 학습한 객체에는 어떤 열·행·순서·설정으로 기억했는지도 붙입니다.

훈련과 새 입력을 읽어 새로운 표현을 만드는 일은 수학적으로 가능할 수 있습니다. 다만 새 입력을 미리 받는 평가와, 새 입력을 받기 전에 규칙을 정하는 평가는 정보 조건이 다릅니다. 이 장은 두 계산을 이름 붙여 비교합니다.

Imagine a small transformer box. fit reads designated rows and remembers mean two. transform subtracts that stored number from each input; receiving a new list does not replace the remembered mean with that list’s mean.

Another fit call may replace the state. Fitting separate boxes on training and validation, then merely saying “both were centered” hides a possible coordinate mismatch. Record the columns, rows, ordering and settings used to learn an object.

Learning a representation from both training and new inputs can be a mathematically defined procedure. Its information condition differs from fixing a procedure before receiving new inputs. The chapter names and compares those conditions.

기초Foundations

4. 평균과 분산을 두 값으로 손계산한다4. Calculate a mean and variance from two values

가용 훈련값이 n≥1개라고 합시다. 이 장의 전처리 분산은 편차 제곱합을 n으로 나눕니다. 모분산의 비편향 추정량을 구하기 위한 n−1 분모와 목적이 다릅니다. 1과 3에서는 평균 2, 편차 −1·1, 제곱합 2, 전처리 분산 1입니다.

c=1n∑i=1nxiv=1n∑i=1n(xi−c)2z(x)=x−cs\begin{gathered}c=\frac1n\sum_{i=1}^nx_i\\v=\frac1n\sum_{i=1}^n(x_i-c)^2\\z(x)=\frac{x-c}{s}\end{gathered}

v>0이면 s=√v를 씁니다. 훈련값만으로 c와 s를 저장한 뒤 새 값에도 그대로 적용합니다. 제곱근이 무리수일 수 있으므로 실습은 c·v·s²의 정확 분수와 z의 수치 근사를 구분합니다. 가용값 0개라면 평균과 분산은 이 계산으로 정해지지 않습니다.

Assume n≥1 available training values. The preprocessing variance here divides the squared-deviation sum by n. Its purpose differs from the n−1 divisor used for an unbiased population-variance estimator. For one and three, the mean is two, deviations are −1/one, squared sum two and preprocessing variance one.

c=1n∑i=1nxiv=1n∑i=1n(xi−c)2z(x)=x−cs\begin{gathered}c=\frac1n\sum_{i=1}^nx_i\\v=\frac1n\sum_{i=1}^n(x_i-c)^2\\z(x)=\frac{x-c}{s}\end{gathered}

Use s=√v when v>0, store the training c and s, then reuse them for new values. Square roots can be irrational, so the lab separates exact fractions for c, v and s² from numerical approximations for z. No available values means this calculation cannot fit moments.

기초Foundations

5. 같은 값만 있으면 0으로 나누지 않는다5. A constant feature does not require division by zero

훈련값 2·2의 평균은 2이고 분산은 0입니다. 이 장은 이 열의 scale을 1로 정하고 상수 열이라는 표시를 남깁니다. 중심화한 훈련값은 0·0이며 새 값 9는 7입니다. 원값이 같은 훈련 열을 버린 것이 아닙니다.

n=1도 분산이 0이므로 같은 약속을 씁니다. 빈 훈련 목록과는 다릅니다. 하나의 값으로 평균은 정할 수 있지만 빈 목록에서는 정할 수 없습니다. 실제 손글씨의 픽셀 0·39는 훈련에서 항상 0이며, 이를 숨기지 않고 scale 1로 보존합니다.

중심화를 끄면 c 대신 0을 빼고, 스케일링을 끄면 s=1을 씁니다. 분산을 계산할 때의 평균과 실제로 뺄 중심값은 별도 수치입니다. 원래 평균을 빼지 않아도 분산은 훈련 평균에 대한 편차로 구합니다.

Training values two/two have mean two and variance zero. This chapter chooses scale one and retains a constant-feature flag. Centered training values are zero/zero; a new nine becomes seven. The original feature has not been deleted.

One training value also has zero preprocessing variance and uses the same rule. That differs from an empty list: one value defines a mean, none does not. Actual handwriting pixels zero and 39 are constant zero in training; retain them explicitly with scale one.

Disabling centering subtracts zero instead of c. Disabling scaling uses s=1. The mean used to calculate variance and the centering value actually subtracted are separate quantities. Variance still uses deviations from the training mean when centering is disabled.

기초Foundations

6. 평균 0·분산 1이 정규분포를 만들지는 않는다6. Zero mean and unit variance do not create normality

훈련값 1·3을 −1·1로 바꾸면 평균 0, n분모 분산 1입니다. 그러나 두 점이 갑자기 종 모양의 연속 분포가 되지는 않습니다. 순서와 값 사이의 선형 비율을 바꿀 뿐, 이 변환만으로 독립성·대표성·정규성을 얻지 않습니다.

단위가 큰 열이 거리를 지배하는 문제는 실제 손계산으로 볼 수 있습니다. 두 대상의 차이가 한 열에서 1, 다른 열에서 100이면 원단위 제곱거리 기여는 1과 10,000입니다. 각 열을 어떤 양의 scale로 나누면 기여의 상대 무게가 달라집니다. 어느 무게가 예측 문제에 맞는지는 별도 선택입니다.

따라서 표준화 뒤 성능이 반드시 좋아진다고 미리 결론내리지 않습니다. 실제 숫자 사례는 같은 훈련 중심을 사용해도 세 스케일 규칙의 시험 정답 수가 다름을 보여 줍니다.

Transforming one/three into −1/one produces mean zero and divisor-n variance one. Two points do not become a continuous bell curve. This affine transformation alone supplies no independence, representativeness or normality.

A distance example makes the scale issue concrete. Differences of one in one column and 100 in another contribute one and 10,000 to squared distance in original units. Dividing columns by positive scales changes their relative contributions. Choosing useful weights is a separate prediction decision.

Do not conclude in advance that standardization must improve performance. The actual digit example has different test-correct counts under three scale rules even though its class centroids use the same training rows.

기초Foundations

7. 단위 변경과 배운 스케일을 구별한다7. Separate a unit conversion from a learned scale

길이를 미터에서 센티미터로 바꾸는 100배는 정의한 단위 변환입니다. 반면 훈련 분산으로 나누는 scale은 훈련값에 따라 달라집니다. 둘 다 숫자를 바꾸지만 어떤 정보로 배웠는지에 대한 답이 다릅니다.

같은 자료를 x′=ax+b로 표현하고 a≠0이라 합시다. 평균은 ac+b, 전처리 분산은 a²v입니다. v>0에서 표준화한 값은 a>0이면 원래 z와 같고, a<0이면 부호가 반대입니다. 분산 0인 열은 scale 1 약속 때문에 이 식의 양의 분산 전제를 따로 확인합니다.

c′=ac+bv′=a2vz′=sign⁡(a)z\begin{gathered}c^{\prime}=ac+b\\v^{\prime}=a^2v\\z^{\prime}=\operatorname{sign}(a)z\end{gathered}

Multiplying meters by 100 to obtain centimeters is a defined unit conversion. Scaling by a training standard deviation instead depends on observed training values. Both change numbers, but they answer the information question differently.

Express identical observations as x′=ax+b with a≠0. The mean becomes ac+b and the preprocessing variance a²v. For v>0, standardized values are unchanged when a>0 and reverse sign when a<0. Check the positive-variance premise separately for constant columns using the scale-one convention.

c′=ac+bv′=a2vz′=sign⁡(a)z\begin{gathered}c^{\prime}=ac+b\\v^{\prime}=a^2v\\z^{\prime}=\operatorname{sign}(a)z\end{gathered}
기초Foundations

8. 실습 A · 기억한 수치와 새 행을 따로 바꾼다8. Lab A · change fitted state and new rows separately

훈련 목록 1·3과 새 목록 9를 입력하고 평균 2·분산 1·변환 7을 확인합니다. 새 목록만 99로 바꾸어 평균 2가 유지되는지 봅니다. 중심화와 스케일링을 각각 끄고, 훈련 2·2 및 빈 목록도 비교합니다.

숫자 자리의 null은 결측이고 0은 실제 수량입니다. 실습은 가용 훈련값으로 적합하고 결측 원위치를 보존합니다. live 조절은 JavaScript 계산입니다. 뒤의 Python/R 다운로드와 실행 출력은 정해진 입력으로 실제 실행한 별도 기록입니다.

Enter training one/three and new nine. Verify mean two, variance one and transformed seven. Changing only the new value to 99 must retain mean two. Toggle centering and scaling separately, then compare constant training two/two and an empty list.

null in a numeric position is missing; zero is an actual value. Fit available training values and retain missing positions. Live controls calculate in JavaScript. Downloadable Python/R programs and their outputs are separate actual executions at fixed inputs.

기초Foundations

9. 0과 결측을 다른 칸으로 표시한다9. Represent zero and missingness separately

훈련값이 0·결측·2·10이라고 합시다. 가용값은 0·2·10의 세 개이고 합은 12이므로 가용 평균은 4입니다. 0을 결측처럼 제외하면 평균이 6이 되어 원자료의 뜻을 바꿉니다. 결측을 0으로 채운 뒤 평균을 구하면 3이 되어 또 다른 규칙입니다.

대체 전 원값, 결측 여부, 대체 후 값을 각각 저장합니다. 원행 2가 값 4를 갖게 된 것은 새로 4를 측정했기 때문이 아닙니다. 훈련 가용 평균이라는 정한 규칙을 적용했기 때문입니다. 표에 대체 표시를 남기면 두 종류의 숫자를 다시 구별할 수 있습니다.

Take training values zero/missing/two/ten. The three available values sum to 12, so their mean is four. Excluding the genuine zero as if it were missing changes the mean to six. Filling missing with zero before computing the mean instead gives three: another procedure.

Store the original value, missing flag and completed value separately. Source row two receiving value four does not mean four was newly measured; it follows a training-mean rule. A fill flag keeps those meanings distinguishable.

기초Foundations

10. 훈련 평균 대체값 4를 새 결측에도 쓴다10. Reuse training fill value four for a new missing cell

위 네 훈련 행의 결측은 가용 훈련 평균 4로 채웁니다. 새 입력이 결측·9라면 첫 새 행도 4로 채웁니다. 새 값 9를 대체값 계산에 넣지 않습니다. 완성 목록을 원순서대로 적으면 훈련 0·4·2·10과 새 4·9입니다.

가정 평균 대체의 모든 원위치
원위치원값원래 결측?대체 후
훈련 10아니오0
훈련 2결측예4
훈련 32아니오2
훈련 410아니오10
새 1결측예4
새 29아니오9

가용 훈련 평균으로 채우면 완성 훈련 목록의 평균도 4입니다. 이는 뒤에서 증명할 대수적 성질입니다. 결측된 실제 값의 평균이 4였다는 관측 사실과는 다릅니다.

Fill the missing training cell with available training mean four. New inputs missing/nine also receive four in their missing position; nine does not enter the fill calculation. Completed values are training zero/four/two/ten and new four/nine.

Every position in the toy mean-imputation example
Source positionOriginalOriginally missing?Completed
Train 10No0
Train 2MissingYes4
Train 32No2
Train 410No10
New 1MissingYes4
New 29No9

Filling with the available training mean also preserves that mean in the completed training list. This is an algebraic property proved below, not an observation that the unobserved values really averaged four.

기초Foundations

11. 평균·중앙값·상수는 서로 다른 선택이다11. Mean, median and a declared constant are different rules

가용 훈련값 0·2·10을 순서대로 쓰면 가운데 값은 2입니다. 중앙값 대체는 결측을 2로, 평균 대체는 4로 채웁니다. 가용값이 0·2·10·20처럼 짝수 개면 이 장은 가운데 두 값 2와 10의 중점 6을 중앙값 대체값으로 씁니다.

상수 대체는 자료로 평균을 배우는 대신 미리 선언한 수를 씁니다. 상수 0이라고 정하면 결측은 0이 되지만 원래 0과 대체 0의 표시를 합치지 않습니다. 0이 적절한 대체인지 여부는 수치 입력만으로 정해지지 않습니다.

중앙값은 절댓값 손실의 최소해 중 하나이고 평균은 제곱손실의 최소해라는 연결은 DATA10과 같습니다. 그러나 어느 대체가 이후 예측 성능을 좋게 만드는지는 따로 평가해야 합니다.

Order available training values zero/two/ten: the middle value is two. Median filling therefore uses two, while mean filling uses four. For an even list such as zero/two/ten/20, this chapter chooses midpoint six of the central two/ten values.

Constant filling uses a declared number rather than learning a mean. Choosing constant zero fills missing cells with zero while retaining the distinction between an original zero and a filled zero. Numeric input alone does not establish whether zero is appropriate.

The median minimizes absolute loss and the mean minimizes squared loss, as in DATA10. Which filling rule improves a later prediction procedure still requires evaluation.

기초Foundations

12. 전부 결측인 열에서 배우지 못한 값을 숨기지 않는다12. Keep an all-missing fit column visible

훈련 한 열이 결측·결측이면 평균이나 중앙값을 구할 가용 숫자가 없습니다. 새 입력에 10이 있다고 그 값을 몰래 훈련 대체값으로 쓰지 않습니다. 학습 실패 상태와 원위치를 보여 주고, 어떤 추가 규칙이 필요한지 결정합니다.

미리 선언한 상수 0은 이런 경우에도 적용할 수 있습니다. 그 0은 관측에서 추정된 평균이 아니라 선언한 설정입니다. 열 제거·외부 기준값·별도 결측 범주 등의 다른 절차도 가능하지만, 훈련 열이 사라지면 새 입력의 열 순서도 일치시켜야 합니다.

보관 프로그램은 평균 대체의 전결측 입력에서 실제로 오류를 냅니다. 실패한 실행에 성공한 결과나 그림을 만들어 붙이지 않습니다. 라이브 계산기는 같은 경계에서 정의 상태를 표시합니다.

A training column missing/missing contains no available number from which to learn a mean or median. A new input of ten must not silently become its training fill value. Show the failed-fit state and original positions, then choose an additional rule explicitly.

A previously declared constant zero can still be applied. It is a chosen setting, not an estimated observed mean. Alternatives include dropping a column, an external reference or a separate missing category; any column removal must preserve consistent feature order for new inputs.

The archived mean-imputation programs actually raise an error for all-missing training. No successful result or plot is invented for that execution. The live calculator displays the corresponding definition state.

기초Foundations

13. 대체가 평균을 보존해도 흩어짐은 달라진다13. Preserving a mean does not preserve spread

가용 r≥1개를 가진 전체 N≥r개의 훈련 행에서 가용 평균을 c라 합시다. 나머지 N−r개를 c로 채우면 새 편차가 모두 0이므로 편차 제곱합은 같습니다. 하지만 분모가 r에서 N으로 커집니다.

∑i=1N(x~i−c)2=∑i∈R(xi−c)2vcompleted=rNvavailable\begin{gathered}\sum_{i=1}^N(\widetilde x_i-c)^2=\sum_{i\in R}(x_i-c)^2\\v_{\rm completed}=\frac rN v_{\rm available}\end{gathered}

R은 가용 원행 집합입니다. 0·결측·2·10에서 가용 평균 4, 편차 제곱합 56입니다. 가용 n분모 분산은 56/3이고 완성 분산은 14입니다. 평균을 채웠다고 새 독립 관측을 하나 얻은 것은 아니며 이 분산 감소가 실제 불확실성 감소를 뜻하지도 않습니다.

Let N≥r≥1 training rows contain r available values with available mean c. Filling the other N−r positions with c adds only zero deviations. The squared-deviation sum stays the same, while its divisor increases from r to N.

∑i=1N(x~i−c)2=∑i∈R(xi−c)2vcompleted=rNvavailable\begin{gathered}\sum_{i=1}^N(\widetilde x_i-c)^2=\sum_{i\in R}(x_i-c)^2\\v_{\rm completed}=\frac rN v_{\rm available}\end{gathered}

R is the available source-row set. For zero/missing/two/ten, mean four gives squared sum 56. Available divisor-n variance is 56/3; completed variance is 14. Filling a mean has not created an independent observation, and the numerical spread reduction is not automatically reduced uncertainty.

기초Foundations

14. 결측 표시도 입력으로 삼을 때는 역할을 정한다14. A missing indicator is another declared feature

원래 결측이면 1, 아니면 0인 열을 함께 둘 수 있습니다. 설명용 목록 0·결측·2에서는 표시가 0·1·0입니다. 대체 0을 사용해 원값과 대체값이 같아져도 표시가 차이를 보존합니다.

이 표시가 의미 있는 예측 정보인지, 새 환경에서도 같은 방식으로 생기는지는 자료 수집 과정과 평가 질문에 달립니다. 결측 표시를 사용한다고 사라진 실제 값을 알아낸 것은 아닙니다. 사람·장소·시간별 결측 구조가 변하면 표시와 정답의 관계도 달라질 수 있습니다.

이 장의 작은 파이프라인 엔진은 숫자 1–2열과 평균 대체를 다룹니다. 표시를 추가한 고차원 자동 모형을 실행했다고 하지 않습니다. 완성값과 원래 표시를 반환하므로 학습자가 두 자료를 비교할 수 있습니다.

One may add an indicator equal to one for originally missing and zero otherwise. For toy values zero/missing/two it is zero/one/zero. Even if filling with zero makes original and imputed values equal, the flag preserves their distinction.

Whether the flag predicts usefully, and whether the same process applies in a new setting, depends on data collection and the evaluation question. An indicator does not recover an unobserved value. Its relationship with the outcome can change across people, places or times.

The small engine here fits mean imputation with one or two numeric features. It does not claim to execute a high-dimensional model automatically augmented with indicators. Completed values and original flags remain available for comparison.

기초Foundations

15. 먼저 대체할지 먼저 표준화할지 적는다15. State whether imputation precedes scaling

훈련 0·결측·2·10의 가용 분산은 56/3입니다. 평균 4로 먼저 채우고 완성 네 값의 분산을 구하면 14입니다. 둘은 서로 다른 scale을 만듭니다. “평균 대체와 표준화를 했다”는 한 문장만으로 순서를 알 수 없습니다.

이 장의 파이프라인은 훈련 가용값으로 평균 대체값을 적합하고, 먼저 대체한 훈련 목록의 평균·n분모 분산으로 scale을 적합합니다. 새 목록에는 저장한 대체값을 쓰고 저장한 scale로 변환합니다. 개별 scaling 실습은 대체 없이 가용값으로 적합하는 별도 계산입니다.

이처럼 전처리의 작은 단계도 어떤 입력을 받는지 명시하면 순서 차이를 직접 재현할 수 있습니다. 함수 이름만 같은지보다 각 단계가 받은 행과 이전 단계의 출력이 무엇인지 확인합니다.

Available variance for training zero/missing/two/ten is 56/3. Filling with four first gives completed divisor-n variance 14. Those create different scales. Saying only “mean imputation and standardization” does not state their order.

The pipeline in this chapter fits a training-available mean imputer, completes training values, then fits mean and divisor-n variance on the completed list. New values reuse the stored fill and scale. The individual scaling lab instead fits available values directly without imputation.

Stating each stage’s input makes these order differences reproducible. Compare the rows and preceding-stage output supplied to a function, rather than only matching function names.

기초Foundations

16. 실습 B · 원래 표시와 완성값을 함께 읽는다16. Lab B · inspect original flags and completed values

훈련 0·결측·2·10과 새 결측·9에서 평균 4와 중앙값 2를 비교하세요. 상수 대체를 선택해 설정 숫자를 바꾸고, 원래 0은 그대로인지 봅니다. 전부 결측인 훈련 입력에서 평균·중앙값이 정의되지 않는 상태와 상수 규칙이 적용되는 상태도 비교합니다.

원위치를 삭제하지 않고 원값·결측·대체 여부·완성값을 나란히 봅니다. 어떤 대체가 좋다는 결론을 내리기 전에 무엇을 배웠고 무엇을 선언했는지 먼저 말해 보세요. 뒤 고정 기록에는 mean·median의 실제 프로그램과 전결측의 실제 실패 출력이 있습니다.

Compare mean four and median two for training zero/missing/two/ten and new missing/nine. Select a declared constant and verify that the original zero is retained. Contrast undefined mean/median fits for all-missing training with an applicable constant rule.

Keep every source position and read original value, missing/fill flags and completion side by side. Before judging a procedure, explain which quantities were learned and which were declared. Fixed records include actual mean/median programs and the actual all-missing failure.

기초Foundations

17. A와 B에 숫자를 붙여도 간격은 생기지 않는다17. Numeric category codes do not create meaningful distances

배송 종류 A·B·C에 코드 1·2·3을 붙였다고 A와 C가 A와 B보다 정확히 두 배 다르다고 정한 것은 아닙니다. 이름을 바꿔도 범주의 본래 뜻은 같을 수 있는데, 숫자 차이는 코드 순서에 따라 달라집니다.

순서형 값은 다른 문제입니다. 실제 와인의 품질 점수는 순서가 있지만, 이 장의 제곱손실 계산은 점수 간격을 같게 다루는 선택까지 추가합니다. 범주 이름과 순서·수치 간격을 구별해야 거리와 손실의 뜻을 설명할 수 있습니다.

여기서는 이름 범주 하나를 여러 개의 0·1열로 나타내는 one-hot 표현부터 만듭니다. 이는 사용할 수 있는 한 표현이며 모든 문제에서 최선이라는 명제는 아닙니다.

Assigning delivery types A/B/C codes one/two/three does not establish that A and C differ twice as much as A and B. Renaming categories can preserve their meanings while changing differences between arbitrary numeric codes.

Ordered values raise another question. Actual wine quality is ordinal; squared loss additionally treats adjacent score intervals equally. Distinguish names, ordering and numerical spacing to explain a distance or loss.

Start with one-hot representation: several zero/one columns for one named category. It is an available representation, not a theorem that it is best for every problem.

기초Foundations

18. 훈련에서 처음 본 순서로 사전을 만든다18. Build a dictionary in training first-occurrence order

훈련 이름이 A·B·A이면 이 장의 사전은 [A, B]입니다. 첫 열은 A인지, 둘째 열은 B인지를 나타내고 훈련 표현은 [1, 0], [0, 1], [1, 0]입니다. 새 B는 같은 열 순서로 [0, 1]이 됩니다.

설명용 훈련 사전과 고정 열 순서
원위치범주A 열B 열
훈련 1A10
훈련 2B01
훈련 3A10
새 1B01

이 첫 등장 순서는 우리 작은 계산기의 선언입니다. 모든 라이브러리의 자동 범주 순서가 같다고 가정하지 않습니다. 실제 프로그램으로 옮길 때는 범주 목록·열 이름을 보관하고 새 행에도 동일하게 적용해야 합니다.

For training A/B/A, this chapter’s dictionary is [A, B]. Columns indicate A and B, giving [1, 0], [0, 1], [1, 0]. A new B must use the same column order and becomes [0, 1].

Toy training dictionary and fixed feature order
Source positionCategoryA columnB column
Train 1A10
Train 2B01
Train 3A10
New 1B01

First-occurrence order is our declared calculator convention. Do not assume every library’s automatic category order agrees. Preserve the actual category list and output column names when moving to a program.

기초Foundations

19. 새 C를 새로 fit하지 말고 정책을 고른다19. Choose a policy for new C rather than silently refitting

훈련 사전 [A, B]가 새 C를 만나면 두 열 중 어느 열도 C를 뜻하지 않습니다. 이 장은 두 정책을 보여 줍니다. error는 변환 실패와 낯선 원위치를 반환하고, all-zero는 C를 [0, 0]으로 바꾸되 낯선 범주 표시를 남깁니다.

새 C를 사전에 더해 세 열을 만들면 기존 모형이 받던 두 열과 달라집니다. 그 경우는 사전을 갱신하고 모형까지 다시 맞추는 별도 절차입니다. 시험 목록에서 범주를 미리 모아 놓는 계산과도 정보 조건이 다릅니다.

빈 훈련 사전은 아무 범주도 배우지 못한 상태입니다. 결측·빈 이름을 일반 문자열처럼 받아 임의의 신원으로 만들지도 않습니다. 이 작은 API는 그 입력을 거절하며, 결측 범주를 따로 설계하는 더 넓은 정책과 구별합니다.

Dictionary [A, B] has no column meaning C. The calculator offers two policies. Error returns a failed transformation with unknown positions; all-zero maps C to [0, 0] while retaining an unknown-category flag.

Appending C creates a three-column input unlike the two-column representation expected by an existing model. Updating the dictionary and refitting the learner is another procedure. Collecting categories from the test list in advance also changes the information condition.

An empty training dictionary has learned no categories. This small API rejects missing or empty names instead of inventing an identity from them; a deliberately designed missing-category policy is a broader alternative.

기초Foundations

20. one-hot 거리의 뜻을 직접 계산한다20. Calculate what one-hot distance means

두 범주 A=[1, 0], B=[0, 1]의 차이는 [1, −1]이고 제곱거리는 2입니다. 같은 A끼리는 0입니다. 세 범주를 세 열로 표현해도 서로 다른 두 알려진 범주의 제곱거리는 2가 됩니다. 코드 1·2·3처럼 특정 두 범주를 더 가깝게 만들지 않습니다.

∥[1,0]−[0,1]∥2=2∥[1,0]−[1,0]∥2=0\begin{gathered}\|[1,0]-[0,1]\|^2=2\\\|[1,0]-[1,0]\|^2=0\end{gathered}

하지만 all-zero 정책의 낯선 C=[0, 0]는 A와의 제곱거리가 1입니다. 따라서 “낯선 범주도 모두 똑같이 두 단위 떨어져 있다”는 해석은 틀립니다. 표현과 정책이 실제 거리 계산에 어떻게 들어가는지 확인해야 합니다.

Known categories A=[1, 0] and B=[0, 1] differ by [1, −1], with squared distance two. Identical A values have distance zero. With three one-hot columns, every distinct pair of known categories still has squared distance two, without the arbitrary closeness induced by codes one/two/three.

∥[1,0]−[0,1]∥2=2∥[1,0]−[1,0]∥2=0\begin{gathered}\|[1,0]-[0,1]\|^2=2\\\|[1,0]-[1,0]\|^2=0\end{gathered}

Under all-zero handling, unknown C=[0, 0] instead has squared distance one from A. It is therefore wrong to say unknown categories automatically have the same pairwise distance as known distinct categories. Inspect the representation and policy together.

기초Foundations

21. 절편과 모든 표시 열을 함께 넣을 때를 본다21. Consider an intercept together with every indicator column

훈련의 알려진 범주가 A와 B뿐이면 각 행에서 A 열+B 열=1입니다. 절편 열도 항상 1이므로 세 열이 선형으로 겹칩니다. 제곱손실의 예측값은 정해질 수 있어도 세 계수는 유일하지 않을 수 있습니다.

해결 방식에는 기준 열 하나를 빼기, 계수 제약, 규제 사용 등이 있습니다. 어느 방식을 썼는지에 따라 계수 해석과 낯선 all-zero 행의 예측이 달라질 수 있습니다. 이 장의 숫자 ridge 실습과 one-hot 실습은 별도로 두어 자동 연결했다고 꾸미지 않습니다.

훈련 [A, B]에서 열 A를 빼고 B만 두면 A는 [0]입니다. unknown도 all-zero로 두면 C 역시 [0]이므로 이 표현만으로는 둘을 구별하지 못합니다. 필요하면 원래 unknown 표시를 별도 보존해야 합니다.

If A and B are the only known training categories, their two indicators add to one in every row. An intercept column is also one, so the three columns are linearly dependent. Squared-loss fitted values can exist without unique coefficients.

Possible designs drop a reference column, constrain coefficients or regularize. These choices affect coefficient interpretation and predictions for unknown all-zero rows. The chapter keeps its numeric ridge lab separate from one-hot encoding instead of pretending they are automatically joined.

Dropping A leaves only B, so known A maps to [0]. All-zero unknown C also maps to [0], making them indistinguishable in that representation alone. Retain the original unknown flag when the distinction matters.

기초Foundations

22. 정답을 쓰는 변환은 훈련 안에서 다시 맞춘다22. Refit transformations that use outcomes inside training

범주 A의 평균 정답을 새 입력으로 쓰는 규칙을 가정해 봅시다. 훈련 A 두 행의 정답이 0·2면 평균 1입니다. 검증 A 한 행의 정답 100까지 합치면 평균 34가 됩니다. 이 수치를 검증 행에 넣으면 그 행의 정답이 이미 표현에 들어갔습니다.

같은 문제는 정답과 상관이 큰 열을 고르는 단계, 정답을 보며 이상값을 제외하는 단계에도 생깁니다. 열 선택 뒤에만 자료를 나누어서는 앞 단계가 이미 본 정보를 되돌릴 수 없습니다. 각 fold의 훈련 안에서 그 단계도 다시 맞춰야 합니다.

이 장의 API는 정답 평균 인코더를 구현하지 않습니다. 이 작은 숫자는 왜 전체 처리 순서를 평가 단위 안에 넣어야 하는지 설명하는 별도 손계산입니다. 세부 목표 인코딩에는 자기 행의 정답 재사용까지 다루는 추가 설계가 필요합니다.

Imagine encoding a category by its mean outcome. Two training A rows with outcomes zero/two give mean one. Including a validation A outcome of 100 changes it to 34. Inserting that value into the validation row already uses that row’s outcome in its representation.

The same issue can arise when choosing columns by outcome correlation or excluding observations after examining outcomes. Splitting only after feature selection cannot undo information already used. Refit those stages inside each fold’s training data too.

The API does not implement a target-mean encoder. This small calculation explains why evaluation must include the whole procedure. Detailed target encoding also needs a design for reusing a training row’s own outcome.

기초Foundations

23. 차원·순서·unknown 정책을 함께 보관한다23. Store dimensions, ordering and the unknown policy together

저장할 사전은 단순한 범주 집합만이 아닙니다. [A, B]라는 열 순서와 두 열이라는 차원, unknown을 거절할지 0으로 둘지라는 정책이 함께 필요합니다. [B, A]로 바꾸고 같은 계수를 쓰면 숫자가 다른 범주에 곱해집니다.

가령 A 계수 10, B 계수 1인 모형에서 새 B의 올바른 [0, 1]은 기여 1입니다. 열을 바꾼 [1, 0]을 넣으면 기여 10이 됩니다. 훈련 평균을 잘못 적용한 좌표 혼합과 같은 종류의 실수입니다.

전처리 객체를 저장할 때는 학습에 쓰인 행·입력 열 이름·출력 열 이름·설정·버전도 함께 둡니다. 이 기록은 계산을 다시 확인하는 데 도움이 되며, 원자료가 보장하지 않는 개인 신원이나 미래 성능을 대신 알려 주지는 않습니다.

A stored dictionary is more than a set. It needs ordered columns [A, B], dimension two and a policy for unknown categories. Swapping to [B, A] while reusing coefficients multiplies them by different categories.

For coefficients ten on A and one on B, a new B’s correct [0, 1] contributes one. Accidentally supplying [1, 0] contributes ten. This is another coordinate-mismatch error.

Store fitting rows, input/output feature names, settings and versions with a preprocessing object. They support computational inspection; they do not supply absent person identities or future-performance evidence.

기초Foundations

24. 실습 C · 사전·낯선 이름·열 순서를 본다24. Lab C · inspect dictionaries, unknown names and columns

훈련 A·B·A와 새 B·C로 시작해 [A, B] 사전과 C의 실패 상태를 읽습니다. all-zero로 바꾸면 C의 벡터와 unknown 표시가 어떻게 달라지는지 확인합니다. 훈련 순서를 B·A로 바꾸면 열 순서도 B·A가 됩니다.

벡터의 열 이름까지 함께 읽어야 비교가 됩니다. 빈 훈련, 빈 이름, 미지 범주 오류 뒤에도 이전의 성공 표를 새 결과처럼 남기지 않습니다. 고정 Python/R 예제는 all-zero 변환의 성공과 unknown-error의 실제 실패를 따로 보관합니다.

Start with training A/B/A and new B/C. Read dictionary [A, B] and C’s failed transformation. Switching to all-zero changes its vector while retaining its unknown flag. Reordering training to B/A changes the ordered columns to B/A.

Always read feature names with vectors. Empty training, empty names or unknown-category errors must not leave a previous successful table masquerading as a new result. Fixed Python/R examples separately archive successful all-zero handling and an actual unknown-error failure.

기초Foundations

25. 대체·스케일·예측을 하나의 순서로 묶는다25. Join imputation, scaling and prediction in one procedure

새 입력이 오면 먼저 저장한 대체값으로 결측을 채우고, 저장한 중심·scale로 숫자를 바꾸고, 마지막에 저장한 예측 계수를 적용합니다. 훈련에서는 이 세 단계의 필요한 수치를 순서대로 배웁니다. 이 연결을 파이프라인이라고 부릅니다.

앞 단계의 출력 열이 다음 단계의 입력 열입니다. 대체가 끝난 숫자로 scale을 배웠다면 새 입력도 같은 방식으로 대체한 뒤 변환해야 합니다. 사전의 열 순서가 바뀌면 뒤 계수도 그 순서와 맞춰야 합니다. 한 줄의 점수 앞에는 이처럼 여러 개의 학습 상태가 있습니다.

input⟶fill⟶scale⟶predict\text{input}\longrightarrow\text{fill}\longrightarrow\text{scale}\longrightarrow\text{predict}

For a new input, fill missing cells with stored values, transform with stored centers/scales, then apply stored prediction coefficients. During training, learn each required state in that order. This connected procedure is a pipeline.

One stage’s output columns become the next stage’s inputs. If scales were fitted after imputation, complete new inputs in the same way before scaling. An encoder’s column order must match subsequent coefficients. A reported score can therefore depend on several learned states.

input⟶fill⟶scale⟶predict\text{input}\longrightarrow\text{fill}\longrightarrow\text{scale}\longrightarrow\text{predict}
기초Foundations

26. 두 훈련 행으로 규제 있는 직선을 맞춘다26. Fit a regularized line to two training rows

설명용 훈련 쌍은 (x, y)=(0, 0), (2, 2)이고 새 x는 4입니다. 훈련 평균은 x와 y 모두 1, x의 n분모 분산은 1입니다. z=x−1로 바꾼 뒤 ŷ=a_z+b_z z를 맞추되, 훈련 평균 제곱오차에 b_z²를 더해 최소화합니다. 절편 a_z에는 벌점을 주지 않습니다.

대칭인 두 행에서 a_z=1이고, b_z=b라고 쓰면 두 훈련 오차의 제곱은 각각 (1−b)²입니다. 따라서 목적함수는 (1−b)²+b²입니다. 완전제곱으로 고치면 b=1/2가 최소이며 a_z=1입니다.

J(b)=(1−b)2+b2=2(b−1/2)2+1/2y^=1+12(x−1)\begin{gathered}J(b)=(1-b)^2+b^2\\=2(b-1/2)^2+1/2\\\widehat y=1+\tfrac12(x-1)\end{gathered}

새 x=4의 예측은 5/2입니다. 훈련 MSE는 1/4, 벌점도 1/4이므로 합은 1/2입니다. 벌점 없이 직선 y=x를 맞추면 훈련 오차 0이지만, 지금 최소화하는 것은 오차와 벌점의 합입니다.

Use toy training pairs (0, 0) and (2, 2), with new x=4. Both means are one and divisor-n variance of x is one. Write z=x−1 and fit ŷ=a_z+b_z z by minimizing training mean squared error plus b_z², with no intercept penalty.

Symmetry gives a_z=1. Writing b_z=b makes each squared training error (1−b)², so the objective is (1−b)²+b². Completing the square gives minimum b=1/2.

J(b)=(1−b)2+b2=2(b−1/2)2+1/2y^=1+12(x−1)\begin{gathered}J(b)=(1-b)^2+b^2\\=2(b-1/2)^2+1/2\\\widehat y=1+\tfrac12(x-1)\end{gathered}

The new prediction is 5/2. Training MSE and penalty are each 1/4, totaling 1/2. Unpenalized y=x has zero training error, but the present objective includes the penalty.

기초Foundations

27. 표준화 계수 벌점은 원단위에서 무게가 된다27. A standardized-slope penalty becomes a raw-unit weight

한 열의 변환 z=(x−c)/s에서 s>0이고, 원좌표 직선을 a+bx라 합시다. x=c+sz를 대입하면 표준화 계수는 b_z=bs, 절편은 a_z=a+bc입니다. 그러므로 λb_z²는 원좌표에서 λs²b²입니다.

a+bx=(a+bc)+(bs)zλbz2=λs2b2\begin{gathered}a+bx=(a+bc)+(bs)z\\\lambda b_z^2=\lambda s^2b^2\end{gathered}

이 식 덕분에 무리수 s의 제곱근을 먼저 근사하지 않고도 s²를 이용해 정확 원좌표 계수를 구할 수 있습니다. 여러 열에서는 각 b_j²에 해당 s_j²를 곱합니다. 다른 scale을 배우면 같은 λ라도 원단위 벌점의 상대 무게가 달라집니다.

훈련 오차를 합으로 정의한 소프트웨어와 평균으로 정의한 소프트웨어는 λ의 수치가 그대로 대응하지 않을 수 있습니다. 이 장은 n≥1에서 MSE+λΣb_zj²이고 절편은 무벌점이라는 약속을 사용합니다.

For z=(x−c)/s with s>0, substitute x=c+sz into raw-coordinate a+bx. The standardized slope is b_z=bs and intercept a_z=a+bc, so λb_z² becomes λs²b².

a+bx=(a+bc)+(bs)zλbz2=λs2b2\begin{gathered}a+bx=(a+bc)+(bs)z\\\lambda b_z^2=\lambda s^2b^2\end{gathered}

Thus s² permits exact raw-coordinate coefficients without first approximating an irrational square root. With multiple features, weight each b_j² by its own s_j². A different learned scale changes the raw-unit penalty even at the same λ.

A package minimizing a sum of squared errors may use a different numeric λ from one minimizing a mean. Here n≥1, the objective is MSE+λΣb_zj² and the intercept is unpenalized.

기초Foundations

28. 새 입력까지 스케일에 넣으면 두 행 예측도 바뀐다28. Including new inputs in a scale changes the two-row ridge fit

앞 훈련 (0, 0), (2, 2)는 그대로 두고 새 x=4를 스케일 계산에만 포함합시다. 세 입력 0·2·4의 평균은 2이고 분산은 8/3입니다. 정답 적합에는 여전히 두 훈련 정답 0·2만 씁니다. 원기울기 목적함수는 (1−b)²+(8/3)b²가 됩니다.

b=11+8/3=311a=1−b=811y^(4)=2011\begin{gathered}b=\frac{1}{1+8/3}=\frac3{11}\\a=1-b=\frac8{11}\\\widehat y(4)=\frac{20}{11}\end{gathered}

새 입력을 보지 않은 예측 5/2와 다릅니다. 벌점의 무게가 달라졌기 때문입니다. 이 대조를 결과 정답을 쓴 적합이라고 말하지는 않습니다. 새 입력까지 미리 사용하는 transductive 정보 조건이며, 새로운 입력을 보지 않는 inductive 평가와 구별합니다.

이 장의 pipeline에서 all-inputs는 대체값은 훈련에서 배우고 scale만 완성된 훈련·새 입력 전체에서 배우는 선언한 대조입니다. 뒤 folds의 global-inputs는 대체값과 scale 둘 다 전체 입력에서 배우는 별도 대조이므로 각 fit-state를 읽어야 합니다.

Retain training pairs (0, 0)/(2, 2), but include new x=4 when fitting the scale only. Inputs zero/two/four have mean two and variance 8/3. The learner still fits only training outcomes zero/two. Its raw-slope objective becomes (1−b)²+(8/3)b².

b=11+8/3=311a=1−b=811y^(4)=2011\begin{gathered}b=\frac{1}{1+8/3}=\frac3{11}\\a=1-b=\frac8{11}\\\widehat y(4)=\frac{20}{11}\end{gathered}

This differs from prediction 5/2 without the new input because the penalty weight changed. It has not fitted the new outcome. It uses new unlabeled inputs in a disclosed transductive condition, distinct from inductive evaluation without those inputs.

The pipeline’s all-inputs contrast learns fills from training and only scales from completed training/new inputs. The later folds global-inputs contrast learns both fills and scales from all inputs. Read their separate fit states.

기초Foundations

29. 벌점 없는 절편 회귀는 일관된 좌표 변경을 흡수한다29. Unpenalized intercept OLS absorbs a consistent affine change

원래 예측 ŷ=a+bx에서 z=(x−c)/s, s>0를 쓴다고 합시다. 계수를 a_z=a+bc, b_z=bs로 바꾸면 모든 원행에서 같은 예측을 냅니다. 역으로 a=a_z−b_z c/s, b=b_z/s로 돌아올 수 있으므로 두 좌표의 가능한 예측집합이 같습니다.

같은 훈련 행·같은 정답·절편 포함·벌점 없음에서 이런 가역 좌표 변환은 OLS 최소 예측을 보존합니다. 전체 계수를 유일하게 비교하려면 설계행렬의 열이 선형 독립인 조건도 둡니다. 여러 열에서도 각 양의 scale과 중심을 일관되게 적용하면 같은 논리입니다.

따라서 전체 입력 scale을 사용했다고 모든 알고리즘의 점수가 반드시 달라지는 것은 아닙니다. 실제 국가 사례는 이 OLS 불변성을 보입니다. 이것이 새 입력을 볼 수 있는 평가라는 원칙 자체를 없애 주지는 않습니다.

For original prediction ŷ=a+bx, define z=(x−c)/s with s>0. Coefficients a_z=a+bc and b_z=bs preserve every prediction. The inverse mapping a=a_z−b_z c/s and b=b_z/s shows that both coordinates permit the same prediction set.

With identical training rows/outcomes, an intercept and no penalty, an invertible coordinate change preserves OLS minimizing predictions. Add full column rank when comparing unique coefficients. The argument extends to several consistently centered and positively scaled features.

Consequently, all-input scaling need not change every algorithm’s score. The actual country example exhibits OLS invariance. It does not remove the need to state whether new inputs were available.

기초Foundations

30. 훈련 계수와 다른 변환을 섞는 오류를 계산한다30. Calculate an error from mixing fitted coefficients and transforms

원예측 y=x를 훈련 평균 1·scale 1의 z=x−1 좌표로 쓰면 ŷ=1+z입니다. 새 x=4의 올바른 예측은 4입니다. 그런데 새 행에서만 평균 2·scale 2를 쓰면 z′=1이고 같은 계수는 예측 2를 냅니다. 원예측을 보존하는 계수 변경을 하지 않았기 때문입니다.

이는 두 좌표에서 각각 일관되게 OLS를 다시 맞추어 같은 예측을 얻는 앞 절의 계산과 다릅니다. 저장한 전처리와 저장한 모형을 한 묶음으로 쓰면 이런 혼합을 줄일 수 있습니다.

실제 KOR 사례의 mixed transform도 훈련 표준화 계수를 전체 입력 표준화값에 잘못 적용한 별도 시연입니다. 특정 시험 MSE가 우연히 더 낮더라도 이 불일치한 절차를 원래 fit의 올바른 재사용이라고 바꾸어 부르지 않습니다.

Express original y=x using training center one and scale one: z=x−1 gives ŷ=1+z. New x=4 correctly predicts four. If only the new row instead uses center two and scale two, z′=1 and the unchanged coefficients predict two. The required coefficient conversion was omitted.

This differs from consistently refitting unpenalized OLS in each coordinate system. Storing preprocessing and the learner as one object helps prevent the mismatch.

The actual KOR mixed-transform example likewise applies training-standardized coefficients to all-input standardized values. Even if a particular test MSE happens to fall, that mismatched computation is not correct reuse of the original fitted pipeline.

학부 심화 · 선택Advanced undergraduate · optional

31. 한두 열의 정확 방정식과 유일성을 연결한다31. Connect exact normal equations with uniqueness

심화로 훈련 n≥1행, 수치 p열, λ≥0를 둡니다. 완성 훈련 입력의 열평균을 x̄, 정답 평균을 ȳ라 하고, n분모 공분산 행렬을 C, 입력과 정답의 공분산 벡터를 r라 합시다. S는 양의 s_j²를 대각에 둔 행렬입니다.

(C+λS)b=ra=y‾−b⊤x‾\begin{gathered}(C+\lambda S)b=r\\a=\overline y-b^\top\overline x\end{gathered}

λ>0이면 임의의 0이 아닌 벡터 u에 대해 uᵀCu≥0이고 uᵀSu>0이므로 합은 양수입니다. 따라서 기울기 해가 유일합니다. λ=0이면 절편을 포함한 설계의 full rank가 유일 계수에 필요합니다. rank가 낮아도 OLS 최소 예측은 존재할 수 있지만 이 작은 계산기는 비유일 계수의 임의 대표를 만들지 않고 상태를 반환합니다.

브라우저 toy pipeline은 p=1 또는 2, 각 목록 최대 200행과 정확 입력 문자 예산을 둡니다. 지원 범위 초과는 수학적 해가 없다는 뜻이 아닙니다. 원자료 전용 계산은 별도로 명시한 실제 크기를 다룹니다.

For an advanced connection, take n≥1 training rows, p numeric features and λ≥0. Let C be the divisor-n covariance matrix of completed training inputs, r their covariance vector with outcomes, and S the diagonal matrix of positive s_j². Let x̄ and ȳ be training means.

(C+λS)b=ra=y‾−b⊤x‾\begin{gathered}(C+\lambda S)b=r\\a=\overline y-b^\top\overline x\end{gathered}

For λ>0 and nonzero u, uᵀCu≥0 while uᵀSu>0, giving a positive sum and unique slopes. At λ=0, full rank of the intercept design gives unique coefficients. Rank-deficient OLS can still have minimizing predictions; this small calculator reports a nonunique-coefficient state rather than inventing a representative.

The toy browser pipeline supports one/two features, at most 200 rows per list and an exact-input character budget. Exceeding that scope is not mathematical nonexistence. Dedicated actual-data calculations handle their separately declared sizes.

기초Foundations

32. 실습 D · 적합 상태·원계수·예측·벌점을 함께 본다32. Lab D · inspect fit states, coefficients, predictions and penalty

두 훈련 행 x=0·2, y=0·2와 새 x=4, λ=1을 입력하세요. train-only에서 원절편 1/2·원기울기 1/2·예측 5/2를 확인합니다. all-inputs 대조에서는 8/11·3/11·20/11을 봅니다. λ=0으로 바꾸면 일관된 좌표의 예측이 같아지는지도 확인합니다.

결측이 포함된 한두 열을 넣고 어떤 훈련값으로 먼저 대체했는지 읽습니다. 출력은 각 행의 원입력·대체 후 입력·원래 결측 표시·예측·제곱오차를 보존합니다. 새 정답은 평가에만 쓰며, 비워 두면 정답 없는 예측을 보여 줍니다. 훈련 정답이 빠진 행은 조용히 제거하지 않고 입력 오류로 처리합니다.

Enter training x=0/two, y=0/two, new x=four and λ=1. Train-only fitting gives raw intercept/slope 1/2 and prediction 5/2. The all-inputs contrast gives 8/11, 3/11 and 20/11. Set λ=0 and verify invariant predictions under consistent coordinates.

Try missing cells in one/two features and inspect training fill values first. Each output row retains original inputs, completed inputs, missing flags, prediction and squared error. New outcomes are used only for evaluation; omitting them gives predictions without a score. Missing training outcomes trigger an input error instead of silent row deletion.

기초Foundations

33. 네 행에서 번갈아 가릴 원행을 정한다33. Assign held-out roles in four concrete rows

설명용 네 쌍은 (0, 0), (2, 2), (4, 4), (6, 6)입니다. fold 0에서는 원행 1·3을 가리고 2·4로 학습합니다. fold 1에서는 반대로 합니다. 여기서 fold 번호는 0부터 시작하는 선언한 역할 이름이며 원행 번호는 1부터 표시합니다.

설명용 네 행의 가림 순서
원행xy검증 fold
1000
2221
3440
4661

각 행의 가려진 예측은 자신이 학습에 들어가지 않은 적합에서 얻습니다. 전처리도 그 적합의 훈련 행 안에서 배우는 것이 핵심입니다. 두 번 얻은 검증 손실은 훈련 행을 공유하거나 의존할 수 있으므로 독립 시험 두 번으로 세지 않습니다.

Use toy pairs (0, 0), (2, 2), (4, 4), (6, 6). Fold zero holds out source rows one/three and trains on two/four; fold one reverses them. Fold indices start at zero, while displayed source rows start at one.

Held-out roles for four toy rows
Source rowxyValidation fold
1000
2221
3440
4661

Each held-out prediction comes from a fit excluding that row. Crucially, learn its preprocessing from that fit’s training complement too. Fold losses can share training data or dependencies; do not count them as independent repeated tests.

기초Foundations

34. 가린 행마다 평균과 스케일이 달라진다34. Means and scales change with the training complement

fold 0의 훈련 x는 2·6이라 평균 4·분산 4입니다. λ=1 ridge의 원기울기는 1/2, 원절편은 2입니다. 가린 x=0·4의 예측은 2·4입니다. fold 1의 훈련은 0·4라 평균 2·분산 4이고, 원기울기 1/2·절편 1을 얻어 가린 x=2·6을 2·4로 예측합니다.

원행 순서로 되돌리면 예측은 2·2·4·4이고 실제 y=0·2·4·6과의 제곱오차는 4·0·0·4입니다. 전체 네 가림 오차의 평균은 2입니다. 각 fold 안의 두 행 평균 손실도 2라 이번에는 단순 평균이 같지만, 일반적으로는 행 수 가중치가 필요합니다.

LOOF=(4+0+0+4)/4=2L_{\rm OOF}=(4+0+0+4)/4=2

Fold zero trains on x=two/six, with mean four and variance four. At λ=1, raw ridge slope is 1/2 and intercept two, predicting held-out zero/four as two/four. Fold one trains on zero/four, with mean two and variance four; slope 1/2 and intercept one predict held-out two/six as two/four.

In source order, predictions are two/two/four/four. Outcomes zero/two/four/six give squared errors four/zero/zero/four and pooled mean two. Both folds happen to have equal sizes; unequal folds generally require row-count weights.

LOOF=(4+0+0+4)/4=2L_{\rm OOF}=(4+0+0+4)/4=2
기초Foundations

35. 전체 입력에서 scale을 배우는 대조를 손계산한다35. Calculate a contrast using the global input scale

네 입력 0·2·4·6을 먼저 모두 보면 평균은 3이고 분산은 5입니다. 각 fold의 학습 정답은 여전히 두 훈련 행만 쓰지만 원기울기 벌점의 무게가 4에서 5로 바뀝니다. 기울기는 4/(4+5)=4/9가 됩니다.

fold 0 절편은 4−(4/9)4=20/9이므로 가린 0·4를 20/9·4로 예측합니다. fold 1 절편은 2−(4/9)2=10/9이고 가린 2·6을 2·34/9로 예측합니다. 원순서 제곱오차는 400/81·0·0·400/81입니다.

Lglobal=20081≈2.46914L_{\rm global}=\frac{200}{81}\approx2.46914

이번 대조의 손실은 오히려 커졌습니다. 전체 입력을 미리 본 계산이 항상 점수를 낮춘다는 수학적 법칙은 없습니다. 어떤 정보로 절차를 맞추고 어떤 절차를 평가하는지 일치시키는 것이 먼저입니다.

Looking at all inputs zero/two/four/six first gives mean three and variance five. Each learner still fits two training outcomes, but the raw-slope penalty weight changes from four to five. The slope becomes 4/(4+5)=4/9.

Fold zero’s intercept is 20/9, giving held-out predictions 20/9 and four. Fold one’s intercept is 10/9, giving predictions two and 34/9. Source-order squared errors are 400/81, zero, zero, 400/81.

Lglobal=20081≈2.46914L_{\rm global}=\frac{200}{81}\approx2.46914

This global-input contrast has a larger loss here. No mathematical law says that seeing all inputs must lower a score. First align the information used to fit a procedure with the procedure the evaluation is intended to assess.

기초Foundations

36. 각 fold에서 대체값과 사전도 새로 배운다36. Refit fills and dictionaries inside every fold

네 입력이 0·결측·4·6이고 같은 fold 역할이라 합시다. fold 0 훈련은 결측·6이라 가용 평균 6으로 먼저 채웁니다. fold 1 훈련은 0·4라 평균 2를 기억하고, 가린 결측 행에는 2를 씁니다. 전체 입력의 가용 평균 10/3을 모든 fold에 한 번만 적용한 절차와 다릅니다.

한 fold의 훈련 열이 전부 결측이면 그 fold의 평균 대체는 정의되지 않습니다. 해당 가림 예측을 실패로 남기고 전체 완전 OOF MSE도 미정의로 표시합니다. 실패 행을 몰래 빼서 다른 분모의 평균을 원래 전체 점수처럼 제시하지 않습니다.

범주 사전도 같은 원리입니다. 가린 fold에만 C가 있다면 그 fold의 훈련 사전은 C를 모르므로 선언한 unknown 정책을 적용합니다. 모형 후보를 바꾸는 동안 같은 fold를 재사용할 때도 이 단계들을 각 훈련 안에 둡니다.

Use inputs zero/missing/four/six with the same folds. Fold zero trains on missing/six and first fills with six. Fold one trains on zero/four, remembers fill two and applies two to its held-out missing cell. This differs from fitting global available mean 10/3 once for every fold.

If a fold’s training feature is entirely missing, its mean imputation is undefined. Keep its held-out predictions failed and the complete pooled OOF MSE undefined. Silently omitting failed rows changes the denominator and cannot represent the original complete score.

The same applies to category dictionaries. A C occurring only in a held-out fold is unknown to that fold’s training dictionary. Apply the declared policy. Keep all stages inside each training complement while comparing model candidates.

기초Foundations

37. fold 평균을 합칠 때 원행 수를 센다37. Weight fold means by their held-out row counts

가림 집합 V_k가 서로 겹치지 않고 전체 n≥1개의 행을 한 번씩 덮는다고 합시다. 각 손실이 유한하고, 비어 있지 않은 fold의 평균을 L_k라 하면 전체 행 평균은 n_k/n의 가중 평균입니다. 빈 fold는 합에 기여하지 않으며 그 자체 평균을 0으로 만들 필요가 없습니다.

nk=∣Vk∣Lpooled=∑k:nk>0nknLk\begin{gathered}n_k=|V_k|\\L_{\rm pooled}=\sum_{k:n_k>0}\frac{n_k}{n}L_k\end{gathered}

한 fold의 3행 평균이 0, 다른 fold의 1행 평균이 8이면 전체 행 평균은 2이고 fold 평균의 단순 평균은 4입니다. 전처리 비교를 하면서도 실제 평가 단위와 분모가 유지되는지 봐야 합니다. 일부 행의 예측이 미정의라면 이 전체 평균 공식에 그 행의 손실을 넣을 수 없습니다.

Suppose disjoint held-out sets V_k cover all n≥1 rows exactly once. With finite losses and mean L_k in each nonempty fold, pooled row loss weights that fold by n_k/n. Empty folds contribute no rows; their own undefined means need not be invented as zero.

nk=∣Vk∣Lpooled=∑k:nk>0nknLk\begin{gathered}n_k=|V_k|\\L_{\rm pooled}=\sum_{k:n_k>0}\frac{n_k}{n}L_k\end{gathered}

If a three-row fold averages zero and a one-row fold averages eight, pooled row loss is two while the unweighted fold mean is four. Preserve the evaluation unit and denominator while comparing preprocessing. A row with undefined prediction does not supply a finite loss to the complete-score formula.

기초Foundations

38. 설정을 고른 뒤 무엇을 다시 맞출지 정한다38. Decide what to refit after choosing settings

여러 λ나 대체 전략을 검증으로 비교했다면 선택한 설정과 학습할 수치를 나눕니다. λ=1이라는 설정은 유지하되, 정한 최종 훈련 범위가 늘어났다면 그 범위에서 대체값·scale·계수도 모두 다시 맞춥니다. 예전 scale과 새 계수를 섞거나 그 반대로 섞지 않습니다.

DATA11의 시험 역할은 후보 선택에 사용하지 않는 것으로 정했습니다. 시험 정답을 보고 λ를 다시 고르면 그 점수는 원래의 별도 평가와 같은 역할을 유지하지 못합니다. 최종 배포용 재학습과 선택 절차의 평가 결과도 구별해서 기록합니다.

시간 자료에서는 재학습 때 실제로 알 수 있는 시점까지만 씁니다. 입력의 발표 지연·개정 이력까지 알려 주지 않는 보관 파일을 과거 실시간 파일로 바꾸어 부르지 않습니다.

After validation compares λ values or fill strategies, separate chosen settings from quantities to refit. Keep chosen λ=1, but if the declared final training range expands, refit fills, scales and coefficients on that range together. Do not mix an old scaler with new coefficients or the reverse.

DATA11 reserved test outcomes from candidate selection. Revising λ after examining them changes their evaluation role. Record deployment refitting separately from evaluation of the selection procedure.

For time data, refitting may use only information available by its declared cutoff. An archived file without release delays/revision histories does not become a historical real-time vintage.

기초Foundations

39. 실습 E · 각 가림 행의 학습 상태로 되돌아간다39. Lab E · trace held-out rows back to their fitted states

네 행 0·2·4·6과 동일한 y, fold 0·1·0·1을 시작값으로 둡니다. λ=1에서 within-training의 OOF MSE 2와 global-inputs의 200/81을 비교합니다. 각 fold의 훈련 원위치·대체값·scale·원계수·검증 원위치를 펼쳐 읽습니다.

결측과 빈 fold를 추가해 정의 상태가 어떻게 바뀌는지 확인하세요. k는 2–10이며 설명용 목록은 최대 100행입니다. 전체 점수는 모든 요구 행의 예측이 가능할 때만 계산합니다. global-inputs 대조가 가린 입력을 보았어도 가린 정답을 fit에 쓰지는 않는다는 두 사실을 따로 읽습니다.

Start with x=y=zero/two/four/six and folds zero/one/zero/one. At λ=1, compare within-training OOF MSE two with global-inputs 200/81. Inspect each fold’s training positions, fills, scales, raw coefficients and validation positions.

Add missing cells and empty folds to inspect definition states. The toy list supports at most 100 rows and k from two through ten. Complete pooled scores require every required prediction. Distinguish the global-input contrast seeing held-out inputs from its learner never fitting held-out outcomes.

대학원 연결Graduate bridge

40. 평가하는 대상은 앞 단계를 포함한 전체 규칙이다40. Evaluation concerns the entire fitted procedure

훈련 정답 0·2에서 상수 예측 1을 배웠다고 합시다. 새 정답 Y가 0 또는 2를 각각 확률 1/2로 가지면 새 제곱손실은 어느 경우든 1입니다. 고정한 훈련 상태에서 새 정답의 평균 손실은 1입니다. 새 정답을 먼저 보고 그 값 자체를 예측으로 선택하면 손실은 0이지만 다른 절차를 평가한 것입니다.

심화로 D를 훈련 자료 전체, A(D)를 대체값·사전·scale·계수까지 포함한 적합 규칙이라고 씁니다. 새 (X, Y)가 D와 독립이고 손실이 적분 가능하다면, 고정한 D에서의 기대 손실은 새 (X, Y)의 법칙으로 평균합니다. 후보나 전처리도 D의 함수여야 그 선언한 절차의 평가입니다.

R(D)=E ⁣[ℓ{Y,A(D)(X)}∣D]R(D)=\mathbb E\!\left[\ell\{Y,A(D)(X)\}\mid D\right]

새 입력 묶음까지 받는 절차라면 A(D, X_new)처럼 정보 조건을 다시 적을 수 있습니다. 수식을 바꾸어 그 절차를 정확히 정의하는 일과, 입력을 전혀 보지 않는 A(D)의 평가라고 부르는 일은 다릅니다. 어느 경우에도 한 번의 고정 파일 점수가 이 기대값과 반드시 같지는 않습니다.

Suppose training outcomes zero/two produce constant prediction one. If a new Y equals zero or two with probability 1/2 each, either squared loss is one. Its conditional expected loss with this fitted state fixed is one. Seeing Y first and predicting it gives zero loss, but evaluates a different procedure.

For an advanced notation, let D contain all training data and A(D) include fitted fills, dictionaries, scales and coefficients. If new (X, Y) is independent of D and loss is integrable, conditional risk averages over the new-observation law. Candidate and preprocessing choices must also be functions of the information declared for that procedure.

R(D)=E ⁣[ℓ{Y,A(D)(X)}∣D]R(D)=\mathbb E\!\left[\ell\{Y,A(D)(X)\}\mid D\right]

A procedure supplied new unlabeled inputs can instead be written A(D, X_new), with a different information condition. Precisely defining that procedure differs from calling it evaluation of A(D) before seeing inputs. A score from one fixed file need not equal the resulting expected risk.

기초Foundations

41. 짧은 Python 코드에서 기억과 적용을 분리한다41. Separate remembering and applying in a short Python program

다음 코드는 외부 학습 라이브러리 없이 훈련 1·3의 평균과 n분모 분산을 구합니다. 새 9는 마지막 적용에서만 등장합니다. 두 상수 c와 scale을 함수 밖으로 보관하면 어떤 숫자가 기억인지 드러납니다.

import math
training = [1.0, 3.0]
c = sum(training) / len(training)
v = sum((x - c)**2 for x in training) / len(training)
scale = math.sqrt(v) if v > 0 else 1.0
def transform(values):
    return [(x - c) / scale for x in values]
print(c, v, transform(training), transform([9.0]))

이 입력의 출력은 2.0 1.0 [-1.0, 1.0] [7.0]입니다. 함수가 완성되었다고 결측·빈 목록 처리까지 구현된 것은 아닙니다. 앞 실습 엔진과 뒤 긴 실제 프로그램은 그 상태를 별도로 다룹니다. 새 프로세스에서 내려받은 전체 파일을 처음부터 실행하는 경로를 기본으로 둡니다.

This code fits training mean and divisor-n variance without an external learning library. New nine appears only in the final application. Keeping c and scale outside the transform function exposes the remembered state.

import math
training = [1.0, 3.0]
c = sum(training) / len(training)
v = sum((x - c)**2 for x in training) / len(training)
scale = math.sqrt(v) if v > 0 else 1.0
def transform(values):
    return [(x - c) / scale for x in values]
print(c, v, transform(training), transform([9.0]))

The output is 2.0 1.0 [-1.0, 1.0] [7.0]. This short function does not implement missing/empty input handling; the calculator and longer actual programs handle those states separately. The default reproduction path downloads a complete file and runs it from the beginning in a fresh process.

기초Foundations

42. base R에서도 저장한 중심과 scale을 재사용한다42. Reuse the stored center and scale in base R

R의 sd는 보통 n−1 분모를 쓰므로 이 장의 전처리 분산은 직접 계산합니다. 두 값 1·3에 sd를 바로 쓰면 √2이지만 아래 scale은 1입니다. 정의를 맞추어야 언어가 다른 결과도 대조할 수 있습니다.

training <- c(1, 3)
center <- mean(training)
v <- mean((training - center)^2)
scale_value <- if (v > 0) sqrt(v) else 1
transform_values <- function(values) (values - center) / scale_value
print(list(center=center, variance=v,
           train=transform_values(training),
           new=transform_values(c(9))))

수치 결과는 중심 2·분산 1·훈련 −1, 1·새 7입니다. 목록 출력의 모양은 Python 문자열과 다릅니다. 보관 R 프로그램은 options(digits=17, warn=1)와 UTC 환경을 명시하며, 원CSV의 UTF-8 BOM도 명시적으로 처리합니다. 표시 자릿수와 계산 정의를 구분해 비교합니다.

Base R sd normally uses divisor n−1, so calculate the chapter’s preprocessing variance explicitly. Calling sd on one/three gives √2, while the following scale is one. Match definitions before comparing languages.

training <- c(1, 3)
center <- mean(training)
v <- mean((training - center)^2)
scale_value <- if (v > 0) sqrt(v) else 1
transform_values <- function(values) (values - center) / scale_value
print(list(center=center, variance=v,
           train=transform_values(training),
           new=transform_values(c(9))))

The numerical results are center two, variance one, training −1/one and new seven. R’s list display differs from Python’s string output. Archived R programs declare options(digits=17, warn=1), UTC and explicit UTF-8 BOM input handling. Compare display settings separately from the calculation’s definition.

기초Foundations

43. 실제 한국 45개 연도를 같은 훈련 정답으로 비교한다43. Compare 45 actual Korean years using identical training outcomes

보관 World Bank 자료에서 한국 1980–2024의 45개 연도에 2015 USD/인 GDP와 기간 기대수명을 짝짓습니다. 선택한 훈련 1980–2014는 35행, 검증 2015–2019는 5행, 시험 2020–2024는 5행입니다. 같은 35개 훈련 정답으로 절편 포함 OLS를 맞춥니다.

GDP의 훈련 전용 scale과 45행 전체 입력 scale을 각각 사용해도 계수까지 일관되게 바꾸면 원좌표 예측은 정확히 같습니다. 계산기는 실제 원소수로 두 적합을 다시 계산하고 선택한 연도의 원값·원키·예측을 보여 줍니다. 혼합 좌표의 수치 시연은 별도로 표시합니다.

이 직선은 국가 성장의 인과효과가 아닙니다. 단위와 같은 훈련 정답을 유지한 전처리 비교입니다. 2026 보관본은 과거 각 시점에 공개되어 있던 빈티지라는 근거가 없으므로 과거 실시간 예측실험이라고 쓰지 않습니다.

Pair World Bank Korean GDP per person in 2015 USD with period life expectancy for 45 years, 1980–2024. The chosen training range 1980–2014 has 35 rows, validation 2015–2019 five and test 2020–2024 five. Fit intercept OLS to the identical 35 training outcomes.

Training-only and all-45-input GDP scales give exactly the same raw-coordinate predictions when coefficients are fitted consistently. The calculator refits both from source decimals and shows a selected year’s values, source keys and prediction. A numerical mixed-coordinate illustration is displayed separately.

The line is a preprocessing comparison with fixed units/outcomes, not a causal growth effect. The retained 2026 snapshot does not establish historical publication vintages, so it is not presented as a real-time forecasting experiment.

기초Foundations

44. 실제 손글씨에서 같은 중심과 다른 거리 무게를 본다44. Inspect identical training centroids with different distance weights

실제 optdigits.tra 3,823행으로 숫자별 64픽셀 평균 중심을 만들고, 제공 시험 optdigits.tes 1,797행에서 가장 가까운 중심의 숫자를 고릅니다. 픽셀은 8×8 블록의 0–16 정수이며 선택한 원행의 64값을 그대로 그립니다.

거리의 각 열 기여는 원값 차이의 제곱을 선택한 scale 제곱으로 나눈 값입니다. 같은 중심을 양쪽에서 같은 평균으로 빼면 평균은 차이에서 상쇄됩니다. raw, 훈련 전용 scale, 전체 입력 scale의 고정 시험 정답 수는 각각 1,606·1,599·1,595입니다. 이 비교에서 표준화가 자동 개선되지는 않았습니다.

dℓ2=∑j=164(xj−cℓj)2sj2d_\ell^2=\sum_{j=1}^{64}\frac{(x_j-c_{\ell j})^2}{s_j^2}

c_ℓj는 훈련 숫자 ℓ의 j픽셀 평균입니다. scale이 0인 열은 1을 쓰며 실제 훈련 상수 열은 인덱스 0·39입니다. 선택 행의 거리는 JavaScript 정확 분수로 새로 계산하고, 전체 1,797행 점수는 별도 실제 프로그램의 고정 결과로 구분합니다. 원파일·행 키는 작성자 ID가 아닙니다.

Build ten 64-pixel class centroids from 3,823 actual optdigits.tra rows, then choose the nearest centroid for 1,797 provided optdigits.tes rows. Pixels are integer block counts from zero through 16 on an 8×8 grid; display the selected source row’s actual 64 values.

Each squared-distance term divides the original squared difference by the chosen squared scale. Subtracting the same centering value from both points cancels it. Fixed test-correct counts for raw, training-only and all-input scales are 1,606, 1,599 and 1,595. Standardization did not automatically improve this example.

dℓ2=∑j=164(xj−cℓj)2sj2d_\ell^2=\sum_{j=1}^{64}\frac{(x_j-c_{\ell j})^2}{s_j^2}

Here c_ℓj is training class ℓ’s mean at pixel j. Zero variance uses scale one; actual training-constant feature indices are zero and 39. The selected row’s distances are newly calculated as exact fractions in JavaScript; whole-test scores are separate fixed actual-program results. File/row keys are not writer IDs.

기초Foundations

45. 같은 952개 와인 정답에서 ridge 벌점의 변화를 본다45. Compare ridge penalties using the same 952 wine outcomes

실제 와인 1,599행은 정답을 뺀 11입력 패턴을 함께 배정한 952·321·326행 역할을 사용합니다. 같은 훈련 952개 품질 정답과 alcohol·volatile acidity 두 입력으로 λ=1 ridge를 맞추며 절편에는 벌점을 주지 않습니다.

두 열의 scale을 952개 훈련 입력에서 배운 경우와 1,599개 전체 입력에서 배운 경우를 비교합니다. 원좌표 목적함수의 벌점은 λΣs_j²b_j²이므로 scale 변화가 두 원기울기에 주는 무게를 바꿉니다. 계산기는 실제 원소수·정확 분수로 계수와 세 역할 MSE·MAE를 다시 구합니다.

전체 입력 조건에서도 시험 정답을 fit에 쓰지는 않습니다. 하지만 시험 입력을 미리 안다는 조건은 다릅니다. 품질 점수는 순서형이며 제곱·절댓값 손실은 간격을 수치적으로 다루는 선택입니다. 동일 11입력 패턴을 실제 병이나 생산자 신원으로 바꾸어 부르지 않습니다.

Use the actual 1,599-wine input-pattern split with role counts 952, 321 and 326. Fit λ=1 ridge to the same 952 training quality outcomes and two inputs, alcohol/volatile acidity, without penalizing the intercept.

Compare scales learned from 952 training inputs with those from all 1,599 inputs. The raw-coordinate penalty λΣs_j²b_j² changes its weights on raw slopes when scales change. The calculator refits coefficients and role MSE/MAE from original decimals and exact fractions.

All-input fitting still excludes test outcomes, while changing whether test inputs are known beforehand. Quality is ordinal; squared and absolute losses numerically treat score spacing. An identical eleven-input pattern is not established bottle or producer identity.

기초Foundations

46. 실습 F · 실제 원키·적합 범위·예측을 연결한다46. Lab F · connect actual source keys, fit scope and prediction

국가는 연도를 바꾸어 같은 원좌표 예측과 별도 mixed transform을 비교합니다. 손글씨는 원시험 행과 세 방법을 골라 실제 64블록·열별 거리 기여·정확 동률 규칙을 봅니다. 와인은 방법과 원행을 바꾸며 같은 훈련 정답으로 맞춘 계수·벌점·역할 점수를 읽습니다.

원행을 바꾸어 보는 live 계산과 전체 시험 성과를 다시 실행하는 일은 구별합니다. 원기록·결측·열순서를 보존하며 학습에 들어간 정답 수를 함께 표시합니다. 실제 프로그램은 아래 보관 출력에서 별도로 내려받아 새 프로세스로 실행할 수 있습니다.

Select a country year to compare invariant raw predictions with the separate mixed transform. Select a digit test-source row and one of three methods to inspect actual blocks, featurewise distances and exact ties. Select a wine method/source row to read coefficients, penalties and role scores fitted to the same training outcomes.

A live selected-row calculation differs from rerunning a whole-test score. Preserve source records, missingness and feature ordering, and display the number of outcomes used for fitting. Download actual programs with archived outputs below and rerun them in fresh processes.

기초Foundations

47. 원자료·수치·가정을 함께 읽는 전체 사례47. Read full cases with original observations, calculations and assumptions

국가 사례 · 일관된 단위 변환과 서로 다른 전처리 규칙을 섞는 오류

한국의 1980~2024년 실제 45개 연간 기록에서 x는 1인당 실질 GDP, y는 출생 시 기대수명으로 정합니다. 원 World Bank API에서 각각 NY.GDP.PCAP.KD와 SP.DYN.LE00.IN을 읽고 값·연도·원 API 위치를 보존했습니다. x의 단위는 2015년 불변 USD/명이고 y는 해당 시점 사망률 패턴에 근거한 집단 지표인 년입니다. 개인 수명 예측이나 GDP의 인과효과를 추정한 자료라고 해석하지 않습니다.

시간 순으로 1980~2014년 35개를 학습, 2015~2019년 5개를 검증, 2020~2024년 5개를 테스트로 정합니다. 이 분할은 보관된 2026년 사본으로 만든 사후 실습입니다. 각 지표가 해당 시점에 동시에 공개됐는지, 2014년 당시의 빈티지가 무엇인지는 확인되지 않았으므로 실제 실시간 예측 성과라고 부르지 않습니다. 학습 자료의 평균 μ와 모집단형 표준편차 s를 저장해 새 입력에도 같은 z=(x−μ)/s를 적용합니다. 여기서 분산의 분모는 n이며 n−1이 아닙니다.

같은 실제 입력에서 전처리를 배우는 범위만 다르게 계산 · 소수 반올림
전처리 적합 범위행 수GDP 평균 USD/명표준편차 USD/명검증·테스트 입력 포함
학습만3515,739.8627,987.589아니오
전체 입력4519,724.78810,308.159예

정확한 구별이 하나 있습니다. 절편이 있고 벌점이 없는 최소제곱 회귀는 되돌릴 수 있는 입력의 선형 단위 변환을 일관되게 적용하면 같은 예측 함수를 표현합니다. 학습 평균을 쓰든 전체 입력 평균을 쓰든, 같은 학습 y로 계수를 다시 맞추고 같은 변환을 적용하면 예측은 같습니다. 그러므로 “전처리에 테스트 입력을 넣으면 모든 알고리즘에서 점수가 반드시 좋아진다”는 법칙을 만들면 안 됩니다. 정보 접근의 계약이 잘못됐는지와 이번 수치가 달라졌는지는 다른 질문입니다.

z=(x−μ)/sa+bx=(a+bμ)+(bs)zα=a+bμ,β=bs\begin{aligned}z&=(x-\mu)/s\\a+bx&=(a+b\mu)+(bs)z\\\alpha&=a+b\mu,\quad\beta=bs\end{aligned}

의도적으로 잘못된 비교도 만듭니다. 학습 전처리 좌표에서 얻은 α,β를 보관해 놓고, 예측할 때만 전체 45개 입력의 다른 평균·표준편차를 끼워 넣습니다. 계수와 좌표계의 계약이 맞지 않습니다. 이것은 전체 입력으로 좌표와 계수를 함께 다시 표현한 일관된 경우와 다릅니다.

실제 y에 대한 관측 내 오차 · MSE 단위는 년², 소수 반올림
역할행 수일관된 OLS 세 표현계수·변환 혼합 오류
train350.3874364.591418
validation51.3964777.467940
test56.3851454.205753
먼저 생각한 뒤 풀이 보기: 혼합 오류의 테스트 MSE가 이번에는 더 작으면 올바른 방법인가요?

아닙니다. 테스트 5개에서 우연히 더 작아진 숫자가 좌표와 계수의 불일치를 고쳐 주지는 않습니다. 결과를 본 뒤 오류를 새 규칙으로 고르면 테스트가 선택 자료가 됩니다. 훈련 범위, 변환 매개변수, 특성 순서, 계수와 사용 시점을 함께 저장하고 미리 정한 계약으로 평가해야 합니다.

먼저 생각한 뒤 풀이 보기: 교차검증에서는 평균을 한 번만 배우면 되나요?

새 fold를 평가할 때마다 그 fold의 학습 부분으로 평균·표준편차·변수 선택·결측 대체값을 다시 배워야 합니다. 전체 학습 자료에서 한 번 전처리한 뒤 그 결과로 fold를 나누면 각 fold의 검증 정보가 이미 섞일 수 있습니다. 이번 자료에는 실제 결측을 새로 만들지 않았지만 같은 원칙이 적용됩니다.

사람의 실제 필기 기록 · 픽셀 척도가 달라지면 거리도 달라진다

UCI Optdigits 원 파일의 학습 3,823개와 테스트 1,797개를 그대로 사용합니다. 각 기록은 정규화한 필기 그림을 8×8로 나눈 64개 블록의 0~16 잉크 개수와 0~9 숫자 분류표입니다. 분류표는 물리량이 아닙니다. 원 제공 설명은 학습 30명과 그들과 다른 테스트 13명의 필기라고 적지만, 행별 작성자 ID는 제공하지 않으므로 추가적인 사람별 내부 검증을 만들었다고 주장하지 않습니다.

먼저 학습 필기만 보고 각 숫자 분류의 평균 그림, 즉 10개 중심을 만듭니다. 새 필기는 어느 중심과 제곱거리가 가장 작은지로 분류합니다. 세 규칙을 비교합니다: 원 블록값 그대로, 학습 입력으로만 정한 표준화, 학습·테스트 전체 입력으로 정한 표준화입니다. 세 규칙 모두 중심을 배우는 데 테스트 정답을 쓰지 않습니다. 마지막 규칙은 정답을 안 썼더라도 아직 보지 못할 테스트 입력의 분포를 사용한 전이적 조건입니다. 새로운 한 장만 받는 귀납적 배포와 같은 정보 계약이 아닙니다.

분산이 0인 학습 특성은 0번과 39번입니다. 이 특성의 scale을 1로 정한다는 규칙을 명시합니다. 0으로 나누거나 없는 변동을 만들어 넣지 않습니다. 이번 보관 자료에서는 테스트 입력을 포함해도 0번과 39번의 분산은 모두 0입니다. 학습에서 상수였다는 사실이 미래에도 상수라는 보장은 아닙니다. 표준화는 숫자를 정규분포로 바꾸는 작업도 아닙니다.

실제 픽셀별 매개변수 · 분산 분모 n, 소수 반올림
픽셀학습 평균전체 입력 평균학습 분산전체 입력 분산
00.0000000.0000000.0000000.000000
207.1865037.15818537.72273737.850956
390.0000000.0000000.0000000.000000
539.2832859.11548035.28490835.686842
dk2(x)=∑j=063(xj−ckj)2sj2y^=arg⁡min⁡kdk2(x)\begin{aligned}d_k^2(x)&=\sum_{j=0}^{63}\frac{(x_j-c_{kj})^2}{s_j^2}\\\widehat y&=\arg\min_k d_k^2(x)\end{aligned}

입력과 중심에 같은 평균을 빼면 거리에서 평균은 상쇄되지만 척도 s_j²는 남습니다. 작은 분산의 픽셀 차이는 더 크게 가중됩니다. 원 단위·학습 표준화·전체 입력 표준화는 서로 다른 거리 선택입니다. 이 자료에서는 승자와 차점의 거리가 모두 양의 간격으로 떨어져 있어 마지막 부동소수점 자리의 동률 처리로 분류가 바뀌지 않았음을 검사했습니다.

같은 실제 1,797개 테스트 기록의 고정 규칙 비교
규칙맞힌 개수정확도테스트 입력으로 전처리 적합
원 블록값160689.371%아니오
학습만 표준화159988.982%아니오
전체 입력 표준화 · 전이적159588.759%예
먼저 생각한 뒤 풀이 보기: 표준화했는데 점수가 떨어졌다면 계산이 잘못됐나요?

반드시 그렇지는 않습니다. 표준화는 각 특성을 어떤 척도로 가중할지 바꾸며 모든 문제에 최선인 법칙이 아닙니다. 이 중심 분류기에서는 원 값의 1,606개 정답이 학습 표준화의 1,599개보다 많습니다. 테스트 결과를 보고 여기서 방법을 최종 선택했다고 주장하면 별도의 새 평가가 필요합니다. 이 표는 고정 자료에서 규칙의 차이를 이해하는 사후 비교입니다.

먼저 생각한 뒤 풀이 보기: 테스트 정답을 안 봤으면 어떤 전처리든 괜찮나요?

어떤 정보를 배포 때 사용할 수 있는지에 달려 있습니다. 정답 없는 미래 입력을 한꺼번에 사용하도록 미리 정한 전이적 설계는 가능하지만, 새 사람·새 입력 한 개를 받는 문제와 동일한 평가라고 말하면 안 됩니다. 변환을 적합한 원행 목록과 파일·매개변수 해시를 보관하세요.

제품 실무 사례 · 표준화가 벌점의 뜻까지 바꾸는 와인 점수 회귀

포르투갈 Vinho Verde 적포도주의 실제 1,599개 실험실·관능평가 기록을 다시 읽습니다. 실제 생산기업, 병, 배치, 측정 시점을 식별할 정보는 없으므로 한 기업의 제품 성과나 기업 간 비교라고 부르지 않습니다. 11개 화학 입력의 정확히 같은 패턴을 묶어 앞 장과 같은 결정적 규칙으로 학습 952행·검증 321행·테스트 326행을 정합니다. 품질 정답은 패턴 키에 넣지 않고 모든 원행을 보존합니다. 이 패턴 묶음도 실제 동일 병을 증명하는 ID가 아닙니다.

두 실제 입력 alcohol과 volatile acidity를 골라 품질 점수를 제곱손실로 회귀합니다. 품질은 적어도 세 평가의 중앙값으로 제공된 순서형 점수이므로 점수 간격을 같다고 다루는 것은 이 손실모형의 선택입니다. 입력의 원 단위는 원 표의 변수 이름·척도를 보존하며, 원문에서 확인되지 않은 농도 단위를 새로 붙이지 않습니다. 같은 제품의 반복 측정 여부가 불명확하므로 독립 관측이나 성분을 바꿨을 때의 인과효과를 사실로 선언하지 않습니다.

두 실습 모두 같은 952개 학습 정답만 사용하고, 절편에는 벌점을 주지 않으며 λ=1을 고정합니다. 한쪽은 전처리의 평균·분산을 학습 입력으로만 적합하고, 다른 쪽은 정답 없이 전체 1,599개 입력을 사용합니다. 뒤쪽은 명시적 전이적 정보 조건입니다. 검증·테스트 정답을 이용해 계수나 λ를 정한 것은 아닙니다. 제곱손실의 분모와 λ를 함께 적어 라이브러리마다 다른 벌점 관례를 혼동하지 않도록 합니다.

zij=(xij−μj)/sjL=1n∑i∈T(yi−a−βTzi)2+λ(β12+β22)βj=sjbj\begin{aligned}z_{ij}&=(x_{ij}-\mu_j)/s_j\\L&=\frac1n\sum_{i\in T}(y_i-a-\beta^Tz_i)^2\\&\quad+\lambda(\beta_1^2+\beta_2^2)\\\beta_j&=s_jb_j\end{aligned}

원 좌표의 기울기를 b_j라 하면 벌점은 λΣs_j²b_j²입니다. 따라서 표준편차를 바꾸면 같은 λ라도 원 단위의 기울기에 부과하는 벌점이 달라집니다. 절편을 자유롭게 두면 평균 이동 자체는 흡수할 수 있지만, 벌점 척도 변화는 앞 국가 사례의 벌점 없는 OLS 불변성과 다릅니다. 제공 코드는 이 원 좌표 형태의 2×2 연립식을 정확한 분수로 풀고 예측·오차도 다시 계산합니다.

같은 학습 정답·다른 전처리 범위의 실제 기록 오차 · 반올림
전처리 범위역할행 수MSE 점수²MAE 점수
학습만train9520.4773660.563564
학습만validation3210.4100790.531612
학습만test3260.5950210.628910
전체 입력train9520.4770850.563319
전체 입력validation3210.4099230.531341
전체 입력test3260.5945160.628668
먼저 생각한 뒤 풀이 보기: 전체 입력으로 적합한 쪽의 오차가 조금 작으면 미래 제품에도 낫다는 뜻인가요?

이 자료에서 고정한 차이일 뿐입니다. 정해진 귀납적 평가에서 미래 입력을 미리 쓰는 것은 정보 계약을 바꿉니다. 전이적 설계를 택했다면 그 조건과 새 입력을 받는 방식을 먼저 밝혀야 합니다. 또한 이 분할에는 실제 시간·기업·병 ID가 없어 새 생산기업이나 미래 출하분에 대한 성능을 인증하지 못합니다.

먼저 생각한 뒤 풀이 보기: 이 파이프라인과 함께 무엇을 저장해야 하나요?

특성 이름과 순서, 학습 원행·패턴 역할, 단위·결측 규칙, n을 쓴 분산, 0분산 처리, 적합한 μ·s, λ와 손실의 분모, 절편 벌점 여부, 계수·버전·입력 해시를 저장합니다. 실제 모든 입력이 가용한 이번 자료에 가상 결측을 실측처럼 덧붙이지 않았습니다. 저장한 파이프라인 전체를 같은 규칙으로 새 자료에 적용하는 것이 핵심입니다.

Country case · Consistent coordinate changes versus a mismatched transformation

Use 45 actual Korean annual records for 1980–2024: x is GDP per capita and y is life expectancy at birth. Re-read World Bank indicators NY.GDP.PCAP.KD and SP.DYN.LE00.IN, preserving values, years and original API positions. GDP is constant 2015 USD per person; life expectancy is a period population indicator in years, not an individual lifespan prediction. Their fitted association is not a causal GDP effect.

Choose chronological roles: 35 training years in 1980–2014, five validation years in 2015–2019 and five test years in 2020–2024. This retrospective exercise uses a retained 2026 snapshot. Concurrent publication and the 2014 real-time vintage are not established, so the scores are not certified live forecasting performance. Store the training mean μ and population-form standard deviation s, then apply the same z=(x−μ)/s to later inputs. This variance uses denominator n, not n−1.

Different scaler fit scopes on actual inputs · displayed decimals rounded
Scaler fit scopeRowsGDP mean USD/personSD USD/personUses validation/test inputs?
Training only3515,739.8627,987.589No
All inputs4519,724.78810,308.159Yes

An important qualification: unpenalized least squares with an intercept represents the same prediction function after a consistent invertible affine change of input coordinates. Refit coefficients on the same training outcomes and transform inputs consistently, and predictions remain unchanged whether the coordinate mean came from training inputs or all inputs. Thus including test inputs does not mathematically guarantee a better score for every algorithm. Information-access validity and numerical score changes are separate questions.

z=(x−μ)/sa+bx=(a+bμ)+(bs)zα=a+bμ,β=bs\begin{aligned}z&=(x-\mu)/s\\a+bx&=(a+b\mu)+(bs)z\\\alpha&=a+b\mu,\quad\beta=bs\end{aligned}

Construct a deliberately invalid comparison: keep coefficients α,β expressed in training-scaler coordinates, but transform prediction inputs with the different all-input mean and scale. The coordinates no longer match the coefficients. This differs from consistently re-expressing both inputs and coefficients in all-input coordinates.

Errors against actual outcomes · MSE in years², displayed decimals rounded
RoleRowsThree consistent OLS representationsMismatched coefficients/transform
train350.3874364.591418
validation51.3964777.467940
test56.3851454.205753
Think first, then reveal: If the mismatch happens to lower this test MSE, is it a valid method?

No. A smaller score on five outcomes does not repair inconsistent coordinates. Adopting an error as a new rule after seeing test outcomes also turns the test set into selection data. Store the fit scope, transform parameters, feature order, coefficients and timing, then evaluate the stated contract.

Think first, then reveal: May we learn one scaler once before cross-validation?

Each fold must learn its scaler, feature selection and imputation from that fold’s training subset. Preprocessing all records once before dividing folds can expose validation information. We do not fabricate missing values here, but the same fitting-scope principle applies.

Actual human handwriting records · Changing feature scales changes distances

Keep the UCI Optdigits files’ 3,823 training and 1,797 test records. Each record contains 64 block counts from 0 to 16 in an 8×8 arrangement, plus a digit class from 0 to 9. Class labels are not physical quantities. Provider metadata reports 30 training writers and 13 different test writers, but per-row writer IDs are unavailable; we do not invent additional writer-level internal validation.

Build ten class centroids from training handwriting only. Classify a new record by the nearest squared distance. Compare raw block counts, training-only standardization and standardization learned from all training/test inputs. None uses test labels to learn centroids. The last rule nevertheless accesses the distribution of future test inputs: an explicit transductive condition, distinct from inductive deployment that receives a new record alone.

Training features 0 and 39 have zero variance. Explicitly set their scale to 1 rather than dividing by zero or inventing variation. In this retained dataset, features 0 and 39 still have zero variance after the test inputs are included. Being constant in training does not guarantee being constant in future inputs. Standardization also does not make a distribution Gaussian.

Actual feature parameters · variance denominator n, displayed decimals rounded
PixelTraining meanAll-input meanTraining varianceAll-input variance
00.0000000.0000000.0000000.000000
207.1865037.15818537.72273737.850956
390.0000000.0000000.0000000.000000
539.2832859.11548035.28490835.686842
dk2(x)=∑j=063(xj−ckj)2sj2y^=arg⁡min⁡kdk2(x)\begin{aligned}d_k^2(x)&=\sum_{j=0}^{63}\frac{(x_j-c_{kj})^2}{s_j^2}\\\widehat y&=\arg\min_k d_k^2(x)\end{aligned}

Subtracting the same mean from inputs and centroids cancels the mean in their difference, but the scale s_j² remains. Differences in low-variance features receive greater weight. Raw, training-scaled and all-input-scaled coordinates therefore choose different distances. Every winning class has a checked positive gap from the runner-up here, avoiding ambiguous last-bit ties.

Fixed rules on the same actual 1,797 test records
RuleCorrectAccuracyFits scaler using test inputs?
Raw block counts160689.371%No
Training-only scaling159988.982%No
All-input scaling · transductive159588.759%Yes
Think first, then reveal: Does a lower score after scaling necessarily mean a calculation error?

No. Scaling changes feature weights and is not universally optimal. The raw-count centroid rule gets 1,606 correct versus 1,599 for training-only scaling. Selecting a final method because of these test scores would require a new evaluation set. This is a retrospective comparison of fixed rules, not certified model selection.

Think first, then reveal: Is any preprocessing valid as long as test labels remain hidden?

It depends on the deployment information contract. A declared transductive design may allow a batch of unlabeled future inputs, but it is not the same evaluation as receiving one new person’s input. Retain the fitted record set, source files, parameters and hashes.

Product practice case · Scaling changes the meaning of a ridge penalty

Re-read 1,599 actual laboratory and sensory-evaluation records for Portuguese Vinho Verde red wine. Producer, bottle, batch and measurement date are not identified, so this is not one firm’s performance or a comparison between firms. Group exact patterns of all eleven chemical inputs and reuse the previous chapter’s deterministic rule: 952 training, 321 validation and 326 test rows. Exclude quality from the grouping key and preserve every row. A pattern group is not a verified bottle ID.

Select actual alcohol and volatile-acidity inputs and regress the quality score under squared loss. Quality is an ordinal sensory score reported as the median of at least three evaluations; treating its intervals as equal is a choice of loss model. Preserve source feature names/scales without inventing concentration units not established in the source metadata. Unknown repeated-product identity prevents asserting independent products or causal effects of changing a chemical component.

Both scenarios use the same 952 training outcomes, an unpenalized intercept and fixed λ=1. One fits scaler moments only on training inputs; the other accesses all 1,599 unlabeled inputs under an explicit transductive condition. Neither fits coefficients or λ using validation/test outcomes. State the loss denominator with λ to avoid confusing different library penalty conventions.

zij=(xij−μj)/sjL=1n∑i∈T(yi−a−βTzi)2+λ(β12+β22)βj=sjbj\begin{aligned}z_{ij}&=(x_{ij}-\mu_j)/s_j\\L&=\frac1n\sum_{i\in T}(y_i-a-\beta^Tz_i)^2\\&\quad+\lambda(\beta_1^2+\beta_2^2)\\\beta_j&=s_jb_j\end{aligned}

With original-coordinate slopes b_j, the penalty becomes λΣs_j²b_j². Changing scales therefore changes the original-unit penalty even with the same λ. A free intercept can absorb a mean shift, but changed penalty scales differ from the country example’s unpenalized OLS invariance. The companion solves the original-coordinate 2×2 system using exact fractions and independently recalculates predictions and errors.

Same training outcomes, different scaler scope · actual-record errors rounded
Scaler scopeRoleRowsMSE score²MAE score units
Training onlytrain9520.4773660.563564
Training onlyvalidation3210.4100790.531612
Training onlytest3260.5950210.628910
All inputstrain9520.4770850.563319
All inputsvalidation3210.4099230.531341
All inputstest3260.5945160.628668
Think first, then reveal: If all-input scaling slightly lowers an error here, does it prove better future products?

It is a difference on this fixed dataset. Accessing future inputs changes an inductive information contract. A transductive design must declare that access and how new batches arrive. Missing time/producer/bottle IDs also prevent certifying performance for a new producer or future shipment.

Think first, then reveal: What must accompany the saved pipeline?

Save feature names/order, training row/pattern roles, units/missing-value rules, variance denominator, zero-variance rule, fitted μ/s, λ and loss denominator, intercept penalty status, coefficients, versions and input hashes. All actual inputs here are available; no fabricated missing records are presented as observations. Apply the complete saved contract to new data.

기초Foundations

48. 공식 읽기·실행 기록에서 확인할 부분을 고른다48. Choose precise reading ranges and actual execution records

먼저 scikit-learn Common pitfalls §12.1–12.2에서 훈련 변환을 새 입력에 재사용하는 예제와 분할 뒤 fit하는 순서를 읽습니다. 수치 예제의 점수가 모든 자료에서 재현되는 법칙이라고 읽지 않습니다. StandardScaler의 정의·scale_·Notes에서는 저장한 훈련 수치, 분산 0의 scale 1, ddof=0을 확인합니다.

Preprocessing의 standardization·categorical encoding에서는 변환 API와 unknown 처리를 봅니다. 우리 첫 등장 사전·toy 결측 거절은 이 장의 약속이며 라이브러리 전체 동작을 흉내 낸 실행기가 아닙니다. 평균 0·분산 1만으로 정규분포가 만들어진다는 해석도 피합니다.

보관 실행은 Python 3.11.8·Matplotlib 3.10.0과 base R 4.5.1의 34개 실제 새 프로세스이며, 전결측·unknown 오류 4개와 성공 SVG 30개를 포함합니다. 입력·코드·출력 해시, R 표시 옵션, locale·시간대를 공개합니다. 브라우저는 코드 편집 후 실행을 제공하지 않으며 live JavaScript와 고정 실행 기록을 구별합니다.

Python · R · 원자료·단위·가공·출처

Read scikit-learn Common pitfalls §12.1–12.2 for reusing training transformations and fitting after the split. Its example scores are not universal laws. In StandardScaler’s definition, scale_ and Notes, inspect stored training statistics, scale one for zero variance and ddof=0.

Read standardization and categorical-encoding ranges in Preprocessing for transform APIs and unknown handling. Our first-occurrence dictionary and rejection of missing toy category names are declared chapter conventions, not an emulator of every library behavior. Mean zero and variance one also do not imply a normal distribution.

Archived execution uses Python 3.11.8/Matplotlib 3.10.0 and base R 4.5.1 in 34 actual fresh processes, including four all-missing/unknown failures and 30 successful SVGs. Input/code/output hashes, R display options, locale and time zone are disclosed. The browser does not execute edited code; live JavaScript and fixed execution records are separate.

Python · R · Inputs, units, transformations and sources

Python·R 코드 실행 방법Run the Python/R companions

자료 묶음을 풀고 코드와 실제데이터 폴더를 함께 두세요. 터미널에서 코드 파일이 있는 폴더로 이동해 아래 명령을 실행합니다. 코딩이 처음이라면 손계산과 웹 실습을 먼저 하고, 데이터 사이언스 입문에서 코드를 배운 뒤 돌아와도 됩니다.Extract the bundle, keeping the scripts beside the data folder. In a terminal, enter the script folder and run the commands below. Beginners can complete hand calculations and browser labs first, returning to code after studying introductory data science.

python data12-reproduce.py
Rscript --vanilla --encoding=UTF-8 data12-reproduce.R

결과 파일은 각 코드에 지정된 결과 폴더에 저장됩니다. CSV 원자료는 덮어쓰지 않습니다.Result files are saved in the result directory specified by each script; the input CSVs are not overwritten.

영상·학자·함께 읽기Videos, thinkers and guided reading

본문의 질문을 넓히는 선택 학습입니다. 영상을 보기 전 질문을 먼저 읽고, 자신의 답을 쓴 뒤 해설과 비교하세요. 자료의 언어·선수 지식은 각 항목에 표시했습니다.Optional extensions to the chapter. Read the question first, write your answer, then compare with the explanation. Language and prerequisites are indicated below.

Inria · 파이프라인의 단계를 눈으로 추적하기Inria · Visually trace pipeline steps

Inria/scikit-learn developers · official MOOC

파이프라인 그림에서 입력 변환과 예측기의 순서를 찾아보세요. 예쁜 그림만으로 적합 범위가 맞는 것은 아니므로 각 단계가 어느 원행으로 fit됐는지 함께 적습니다.Trace transforms and the predictor in the pipeline display. A diagram alone does not establish correct fit scope; record which source rows fitted each stage.

교재 안의 YouTube 플레이어에서 재생합니다. 원영상에서 제공하는 자막은 플레이어의 CC·설정에서 선택할 수 있습니다.Playback stays in this chapter’s YouTube player. Available captions can be selected through CC/settings.

보고 읽은 뒤 답하기Respond after watching/reading 그림에 scaler가 있으면 누출이 자동으로 없어지나요?Does a scaler in a diagram automatically eliminate leakage?

생각을 점검하는 해설Check your reasoning

아닙니다. 분할 전 전체 자료에 미리 적합했는지, fold별 학습 범위 안에서 적합했는지 확인해야 합니다.No. Check whether it was fitted on all data before splitting or inside each fold’s training subset.

가엘 바로코 · 통계적 질문과 재사용 가능한 도구Gaël Varoquaux · Statistical questions and reusable tools

Researcher’s official biography

연구자의 공식 소개에서 통계적 학습과 공개 도구 개발의 연결을 읽습니다. 재사용 가능한 도구도 관측 단위·배포 정보·평가 표적을 대신 정해 주지는 않습니다.Read the author’s account of statistical learning and open tools. Reusable software does not select observation units, deployment information or evaluation targets for us.

공식 자료 읽기 ↗Read official resource ↗

보고 읽은 뒤 답하기Respond after watching/reading 라이브러리 기본 설정만 따르면 평가 질문도 정해지나요?Do library defaults determine the evaluation question?

생각을 점검하는 해설Check your reasoning

아닙니다. 사용할 수 있는 정보와 미래 대상, 분할·손실·매개변수의 뜻을 분석자가 먼저 정해야 합니다.No. Specify available information, future targets, splits, loss and parameter meanings first.

scikit-learn 공식 · 일관되지 않은 전처리와 누출Official scikit-learn · Inconsistent preprocessing and leakage

Documentation 1.9.1 · §12.1–12.2 definitions and pipeline guidance

변환을 배운 자료와 적용할 자료를 나누는 설명을 읽습니다. 이 장의 불변 OLS 반례처럼 모든 누출이 매번 점수를 높이는 것은 아니지만, 미래 정보 계약을 어기는 문제는 별도로 남습니다.Read the distinction between fitting and applying a transform. As the invariant OLS example shows, every leak need not raise every observed score; a violated future-information contract remains a separate issue.

공식 자료 읽기 ↗Read official resource ↗

보고 읽은 뒤 답하기Respond after watching/reading 테스트 점수가 달라지지 않으면 정보 접근 규칙도 맞나요?Does an unchanged test score prove valid information access?

생각을 점검하는 해설Check your reasoning

아닙니다. 변환의 수학적 불변성과 평가 설계의 적절함을 따로 점검합니다.No. Audit mathematical invariance and evaluation design separately.

StandardScaler 공식 · 저장되는 평균·분산·상수 특성Official StandardScaler · Stored moments and constant features

Documentation 1.9.1 · formula, scale_/mean_/var_ and Notes only

분모 n인 분산, 학습 평균·척도의 재사용, 0분산에서 scale1 규칙을 확인합니다. 평균0·분산1 변환이 정규분포 생성이나 모든 모델의 성능 향상을 보장하는 것은 아닙니다.Check denominator-n variance, reuse of fitted moments and scale 1 for a constant feature. Centering/scaling does not guarantee a Gaussian distribution or better performance for every model.

공식 자료 읽기 ↗Read official resource ↗

보고 읽은 뒤 답하기Respond after watching/reading R 기본 sd와 같은 분모인가요?Is this the same denominator as base R sd?

생각을 점검하는 해설Check your reasoning

R의 기본 sd는 n−1을 사용합니다. 재현 코드는 mean((x−mean(x))²)의 제곱근으로 이 장의 n 분모를 명시합니다.Base R sd uses n−1. The companion explicitly uses the square root of mean((x−mean(x))²) to implement this chapter’s denominator n.

연습문제 · 계산에서 설명과 증명까지Exercises: calculation, explanation and proof

먼저 혼자 풀고 풀이를 여세요. 숫자와 함께 단위·포함 기준·계산 이유를 확인하세요.Attempt each problem before opening its solution. Check units, inclusion rules and the reason for the calculation.

1. 훈련에서 기억한 2Remember two from training

설명용 훈련값은 1·3이고 새 값은 9입니다. 훈련 평균만 빼는 변환에서 기억할 평균과 세 변환값을 구하세요.

Training values are one/three and the new value is nine. Subtract only the training mean. Find the stored mean and all three transformed values.

풀이와 확인할 이유Solution and explanation

훈련 평균은 (1+3)/2=2입니다. 훈련 1은 −1, 훈련 3은 1, 새 9는 7이 됩니다. 새 9는 평균을 배우는 두 행에 포함하지 않습니다.

The stored mean is (1+3)/2=2. Training values become −1/one and new nine becomes seven. Nine did not enter the two fitting rows.

2. 세 값을 본 다른 평균A different mean from three inputs

훈련 1·3과 새 9를 모두 평균해 중심화하는 별도 규칙을 가정합니다. 평균과 새 값의 중심화 결과를 구하고, 훈련 평균 2를 쓴 결과와 비교하세요.

A contrasting rule centers using training one/three together with new nine. Find its mean and centered new value, then compare with training mean two.

풀이와 확인할 이유Solution and explanation

전체 평균은 13/3이고 새 중심값은 9−13/3=14/3입니다. 훈련 평균만 쓰면 7이었습니다. 둘 다 덧셈은 맞지만 변환을 배운 입력 범위가 다릅니다.

The all-input mean is 13/3 and the new centered value is 14/3, versus seven with training mean two. The arithmetic is valid in both cases; their fitting information differs.

3. n분모와 n−1 분모Divisor n versus n−1

훈련 1·3의 평균 편차 제곱합을 구하세요. 이를 n=2로 나눈 전처리 분산과 n−1로 나눈 분산, 각각의 표준편차를 비교하세요.

For training one/three, find the squared-deviation sum. Compare variance and standard deviation using n=2 versus n−1.

풀이와 확인할 이유Solution and explanation

평균 2에 대한 편차 제곱합은 1+1=2입니다. 전처리 분산은 1·표준편차는 1이고, n−1 분산은 2·표준편차는 √2입니다. 어느 분모를 선택했는지 맞춰야 코드 출력을 비교할 수 있습니다.

The squared-deviation sum about mean two is two. Divisor-n variance/SD are one/one, while divisor-(n−1) variance/SD are two/√2. Match the declared divisor before comparing code outputs.

4. 상수 훈련 열A constant training column

훈련 2·2와 새 9에서 중심화·스케일링을 모두 켭니다. 전처리 분산이 0이면 scale 1을 쓴다는 약속 아래 결과와 상수 열 표시를 구하세요.

Center and scale training two/two and new nine. Use scale one when preprocessing variance is zero. Find results and the constant-feature flag.

풀이와 확인할 이유Solution and explanation

평균 2·분산 0이고 scale은 1입니다. 훈련 결과는 0·0, 새 결과는 7이며 constantFeature는 참입니다. 분산 0으로 나누지도, 원열을 삭제하지도 않습니다.

Mean two and variance zero give scale one. Training becomes zero/zero, new nine becomes seven and constantFeature is true. There is no division by zero or deletion of the original feature.

5. 한 행과 빈 목록One row versus no rows

전처리 평균·n분모 분산과 scale 1 약속을 씁니다. 훈련 [5]에서 새 8의 결과를 구하고, 훈련이 빈 목록일 때의 정의 상태와 비교하세요.

Use divisor-n moments and scale one for zero variance. Find the transformed new eight after training [5], then compare with empty training.

풀이와 확인할 이유Solution and explanation

[5]는 평균 5·분산 0·scale 1이므로 새 8은 3입니다. 빈 목록은 평균도 정해지지 않아 적합 미정의입니다. 한 행의 0분산과 관측 0개의 부재는 다른 상태입니다.

Training [5] has mean five, variance zero and scale one, so eight becomes three. Empty training has no fitted mean. One row with zero variance differs from no available observation.

6. 중심화만 끄기Disable centering only

훈련 1·3에서 분산은 훈련 평균에 대해 계산하되 centering=false, scaling=true입니다. 훈련과 새 9의 변환을 구하세요.

Use training one/three. Compute variance about its training mean, but set centering=false and scaling=true. Transform training and new nine.

풀이와 확인할 이유Solution and explanation

계산된 훈련 평균은 2·분산은 1입니다. 실제로 빼는 중심값은 0이고 scale은 1이므로 1·3·9가 그대로 남습니다. 분산 계산용 평균과 변환에서 뺄 값이 다릅니다.

The fitted mean is two and variance one, but the subtracted center is zero and scale one. Values remain one/three/nine. The variance mean differs from the center actually subtracted.

7. 스케일링만 끄기Disable scaling only

훈련 1·5와 새 9에서 centering=true, scaling=false입니다. 평균·분산과 세 변환값을 구하세요.

For training one/five and new nine, set centering=true and scaling=false. Find fitted moments and transformed values.

풀이와 확인할 이유Solution and explanation

평균은 3, 편차는 −2·2라 분산은 4입니다. 스케일링을 껐으므로 scale은 1이고 변환값은 −2·2·6입니다. 분산 4를 알고 있어도 이 설정에서는 2로 나누지 않습니다.

Mean three and deviations −2/two give variance four. With scaling disabled, scale is one and results are −2/two/six. Knowing variance four does not activate division by two.

8. 양의 단위 환산A positive unit conversion

훈련 1·3과 새 9를 모두 100배하여 100·300·900으로 표현합니다. 두 표현 모두 훈련 n분모 분산으로 표준화할 때 평균·분산·새 z를 비교하세요.

Multiply training one/three and new nine by 100. Standardize each representation using its own training divisor-n variance. Compare moments and the new z.

풀이와 확인할 이유Solution and explanation

원표현은 평균 2·분산 1·새 z=7입니다. 100배 표현은 평균 200·분산 10,000·scale 100이므로 (900−200)/100=7입니다. 양의 단위 환산이 표준화된 새 값을 보존했습니다.

Original moments are mean two/variance one with new z seven. Converted moments are 200/10,000 with scale 100; (900−200)/100 is again seven. Positive unit conversion preserves the standardized value.

9. 음의 배율A negative multiplier

훈련 x=1·3과 새 x=9를 x′=−2x+5로 바꿉니다. 두 좌표 모두 양의 훈련 표준편차로 표준화할 때 새 값의 관계를 구하세요.

Transform training x=one/three and new nine by x′=−2x+5. Standardize each coordinate with its positive training SD. Compare the new values.

풀이와 확인할 이유Solution and explanation

바꾼 훈련은 3·−1이고 평균 1·분산 4·scale 2입니다. 새 x′=−13은 (−13−1)/2=−7입니다. 원래 새 z=7의 부호가 뒤집힙니다. 양의 scale을 쓰더라도 원좌표의 음의 배율 방향은 남습니다.

Transformed training three/−1 has mean one, variance four and scale two. New x′=−13 gives z′=−7, the negative of original z seven. A positive scale does not erase reversal from the negative input multiplier.

10. 표준화와 분포 모양Standardization and distribution shape

확률변수가 −1과 1을 각각 확률 1/2로 가집니다. 평균과 분산을 구하고 정규분포인지 판단하세요.

A random variable equals −1 or one with probability 1/2 each. Find its mean/variance and decide whether it is normal.

풀이와 확인할 이유Solution and explanation

평균은 0, 두 값의 제곱은 1이므로 분산은 1입니다. 그러나 두 점에만 질량이 있는 이산 분포이며 연속 정규분포가 아닙니다. 평균 0·분산 1은 정규성의 충분조건이 아닙니다.

Mean is zero and variance one because both squared values equal one. It is a two-point discrete law, not a continuous normal law. Zero mean/unit variance is insufficient for normality.

11. 평균 대체의 여섯 위치Six positions under mean filling

훈련 [0, null, 2, 10]과 새 [null, 9]에 훈련 가용 평균을 대체합니다. 대체값·완성 목록·원래 결측 위치를 쓰세요.

Fill training [0, null, 2, 10] and new [null, 9] with the available training mean. Give the fill, completed lists and originally missing positions.

풀이와 확인할 이유Solution and explanation

가용 합 12를 3으로 나누어 4를 기억합니다. 완성 훈련은 [0, 4, 2, 10], 새 목록은 [4, 9]입니다. 원래 결측은 훈련 두 번째·새 첫 번째이며 원래 0은 결측이 아닙니다.

Remember four from available sum 12/count three. Completed training is [0, 4, 2, 10], new inputs [4, 9]. Original missing positions are training second and new first; the genuine zero is not missing.

12. 중앙값 대체Median filling

훈련 가용값이 0·2·10이고 새 값 하나는 결측입니다. 평균 대체와 중앙값 대체의 결과를 각각 구하세요.

Available training values are zero/two/ten and one new input is missing. Compare mean and median filling.

풀이와 확인할 이유Solution and explanation

평균은 12/3=4이고 순서상 가운데는 2입니다. 따라서 새 결측은 규칙에 따라 4 또는 2가 됩니다. 같은 원자료에서도 선택한 목적과 대체 규칙이 다릅니다.

The mean is four; the middle ordered value is two. The new missing cell receives four or two according to the chosen rule. These are distinct procedures on identical observations.

13. 짝수 개 중앙값 약속An even-count median convention

훈련 가용값 0·2·10·20에서 가운데 두 값의 중점을 중앙값 대체값으로 선택합니다. 평균과 선택한 중앙값을 구하세요.

For training zero/two/ten/20, choose the midpoint of the two central ordered values as the median fill. Find it and the mean.

풀이와 확인할 이유Solution and explanation

합 32를 4로 나눈 평균은 8입니다. 중앙 두 값은 2와 10이므로 중점은 6입니다. 절댓값 손실은 [2, 10]의 모든 상수에서 최소지만, 이 계산기는 그중 중점 6을 고릅니다.

The mean is 32/4=8 and the central midpoint is (2+10)/2=6. Every constant in [2, 10] minimizes absolute loss, while this calculator selects representative six.

14. 전결측과 선언한 상수All missing with a declared constant

훈련 [null, null]과 새 [null, 0]을 처리합니다. 평균 규칙과 미리 선언한 상수 −2 규칙의 정의 상태·완성 새 값을 비교하세요.

Process training [null, null] and new [null, 0]. Compare a mean rule with a declared constant −2, including definition states and completed new inputs.

풀이와 확인할 이유Solution and explanation

평균은 가용값이 없어 적합 미정의입니다. 상수 −2는 자료로 배우지 않고 선언했으므로 적용 가능하며 새 목록은 [−2, 0]입니다. 두 번째 0은 원래 관측값이므로 −2로 바꾸지 않습니다.

Mean fitting is undefined without available values. Declared constant −2 remains applicable, giving new [−2, 0]. The observed zero stays zero rather than being replaced.

15. 대체 뒤 분산Variance after filling

훈련 [0, null, 2, 10]에 가용 평균을 대체합니다. 대체 전 가용 n분모 분산과 완성 네 행의 n분모 분산을 구하세요.

Fill training [0, null, 2, 10] with its available mean. Find divisor-n variance before filling among available values and after completion of all four rows.

풀이와 확인할 이유Solution and explanation

평균 4에서 가용 편차는 −4·−2·6이고 제곱합은 56입니다. 가용 분산은 56/3, 채운 값의 편차는 0이므로 완성 분산은 56/4=14입니다. 비율은 3/4이며 이는 새 정보를 측정한 결과가 아닙니다.

About mean four, deviations −4/−2/six have squared sum 56. Available variance is 56/3. The filled value adds zero deviation, giving completed variance 56/4=14, a ratio of 3/4. No additional value was measured.

16. 0을 잘못 제외하기Incorrectly removing zero

훈련 [0, null, 2, 10]의 올바른 가용 평균과, 실제 0을 제외한 평균 및 결측을 먼저 0으로 채운 평균을 비교하세요.

Compare the available mean of [0, null, 2, 10] with excluding the genuine zero and with first filling missing by zero.

풀이와 확인할 이유Solution and explanation

올바른 평균은 (0+2+10)/3=4입니다. 실제 0을 제외하면 (2+10)/2=6이고, 결측을 먼저 0으로 채우면 (0+0+2+10)/4=3입니다. 결측 처리 순서와 실제 0 보존이 모두 결과에 영향을 줍니다.

The correct available mean is four. Excluding genuine zero gives six; filling missing with zero first gives three. Both the missing-data rule and preservation of actual zero affect the result.

17. 새 9가 대체값에 들어갔는가Did new nine enter the fill fit?

훈련 [0, null, 2, 10], 새 [null, 9]입니다. 훈련 평균 대체값을 구하고, 새 가용 9까지 평균에 넣은 대조 값과 비교하세요.

Use training [0, null, 2, 10] and new [null, 9]. Compare the training mean fill with a contrasting fill including new observed nine.

풀이와 확인할 이유Solution and explanation

훈련 대체값은 4입니다. 새 9까지 쓰면 가용 합 21·개수 4에서 21/4입니다. 같은 의미의 train-only fit이라고 부를 수 없으며 새 입력을 포함한 다른 fit 범위를 기록해야 합니다.

Training fill is four. Including nine gives available sum 21/count four, hence 21/4. That is a different fitting scope and cannot be described as the same training-only fit.

18. 대체와 스케일의 순서Order of filling and scaling

훈련 [0, null, 2, 10]에서 평균 4를 씁니다. 가용값에서 먼저 배운 scale과 평균 대체 후 네 값에서 배운 scale을 비교하고, 원래 0의 표준화값을 쓰세요.

Use mean four for training [0, null, 2, 10]. Compare scaling fitted on available values first with scaling fitted after filling all four, and transform the original zero.

풀이와 확인할 이유Solution and explanation

가용값 scale은 √(56/3), 완성값 scale은 √14입니다. 따라서 원래 0의 변환은 각각 −4/√(56/3), −4/√14입니다. 중심은 같지만 분모가 달라 결과도 다릅니다.

Available-value scale is √(56/3), completed-value scale √14. The original zero becomes −4/√(56/3) or −4/√14. Equal centers do not make different scales equivalent.

19. 평균 보존 증명Prove preservation of the mean

N≥r≥1개 훈련 위치 중 r개가 가용이고 가용 평균 c가 유한합니다. 나머지를 c로 채우면 완성 평균이 c임을 증명하세요.

Among N≥r≥1 training positions, r available values have finite mean c. Prove that filling the rest with c preserves the completed mean.

풀이와 확인할 이유Solution and explanation

가용 합은 rc이고 새로 채운 합은 (N−r)c입니다. 총합은 Nc이므로 N으로 나누면 c입니다. 이 항등식은 미관측 실제 값의 평균을 추론하는 명제가 아니라 선택한 완성값의 대수입니다.

rc+(N−r)cN=c\frac{rc+(N-r)c}{N}=c

Available sum is rc and filled sum (N−r)c. Their total Nc divided by N is c. This algebra concerns chosen completed values, not identification of the actual unobserved mean.

rc+(N−r)cN=c\frac{rc+(N-r)c}{N}=c

20. 대체 표시가 필요한 이유Why retain fill flags?

원래 입력 [0, null]을 상수 0으로 채웠습니다. 완성값만 [0, 0]을 저장하면 어떤 정보가 사라지며, 어떤 표시를 함께 남겨야 하나요?

Constant-zero filling maps original [0, null] to [0, 0]. What is lost if only the completed values are stored, and which flags should be retained?

풀이와 확인할 이유Solution and explanation

어느 0이 원래 관측이고 어느 0이 채운 값인지 복원하지 못합니다. 원위치별 originalMissing=[false, true]와 채운 표시를 함께 둡니다. 두 위치가 같은 완성값을 가져도 관측 근거는 다릅니다.

The completed vector cannot reveal which zero was observed and which filled. Preserve originalMissing=[false, true] and fill flags by original position. Equal completed values need not have equal observational status.

21. 첫 등장 사전A first-occurrence dictionary

이 장의 first-occurrence 규칙으로 훈련 A·B·A와 새 B를 one-hot 표현하세요. 열 순서를 직접 쓰세요.

Apply the chapter’s first-occurrence convention to training A/B/A and new B. State the ordered columns and one-hot vectors.

풀이와 확인할 이유Solution and explanation

사전은 [A, B]입니다. 훈련 벡터는 [1, 0], [0, 1], [1, 0]이고 새 B는 [0, 1]입니다. 열 이름 없이 벡터만 적으면 어떤 범주가 1인지 뜻을 잃습니다.

Dictionary [A, B] gives training [1, 0], [0, 1], [1, 0] and new B [0, 1]. Feature names are needed to interpret each one.

22. 훈련 순서를 바꾸기Reorder training categories

훈련 B·A·B에 첫 등장 사전을 맞춥니다. 새 B·A의 벡터와, 훈련 A·B였을 때 열 순서와의 차이를 쓰세요.

Fit a first-occurrence dictionary to B/A/B. Encode new B/A and compare with columns fitted to A/B.

풀이와 확인할 이유Solution and explanation

새 사전은 [B, A]이므로 새 B는 [1, 0], A는 [0, 1]입니다. [A, B] 사전의 벡터와 위치가 바뀌었습니다. 같은 문자열 범주에 같은 계수를 적용하려면 열 이름과 계수 순서를 함께 맞춰야 합니다.

New dictionary [B, A] maps B to [1, 0] and A to [0, 1], reversing positions from [A, B]. Match named columns with coefficient order.

23. unknown 정책 둘Two unknown policies

훈련 사전 [A, B]에서 새 C를 만났습니다. error와 all-zero 정책의 벡터·정의 상태·unknown 표시를 비교하세요.

Dictionary [A, B] encounters new C. Compare error and all-zero policies: vector, definition state and unknown flag.

풀이와 확인할 이유Solution and explanation

error는 벡터를 만들지 않고 변환 미정의와 unknown=true를 남깁니다. all-zero는 [0, 0]을 만들고 변환은 정의되지만 unknown=true는 유지합니다. 어느 경우도 새 사전 열 C를 몰래 fit하지 않습니다.

Error supplies no vector and reports undefined transformation with unknown=true. All-zero supplies [0, 0] and a defined transformation, while retaining unknown=true. Neither silently fits a new C column.

24. 알려진 범주와 미지 범주의 거리Known and unknown category distances

A=[1, 0], B=[0, 1], unknown C=[0, 0]입니다. A–B와 A–C의 제곱거리를 구하세요.

Take A=[1, 0], B=[0, 1] and unknown C=[0, 0]. Find squared distances A–B and A–C.

풀이와 확인할 이유Solution and explanation

A−B=[1, −1]이므로 제곱거리는 2입니다. A−C=[1, 0]이므로 1입니다. unknown을 0으로 표현한 정책은 알려진 서로 다른 범주와 같은 거리 구조를 만들지 않습니다.

A–B has difference [1, −1] and squared distance two; A–C has [1, 0] and distance one. An all-zero unknown policy has a different distance structure from known distinct categories.

25. 기준 열을 뺀 경우Dropping a reference column

사전 [A, B]에서 A 열을 빼고 B 표시 열만 저장합니다. unknown도 all-zero로 표현하면 A와 새 C를 이 한 열로 구별할 수 있나요?

Drop A from dictionary [A, B], keeping only the B indicator. If unknown maps to all-zero, can this feature distinguish A from new C?

풀이와 확인할 이유Solution and explanation

A는 B가 아니므로 [0], unknown C도 [0]입니다. 이 한 열만으로 구별할 수 없습니다. 원래 unknown 표시를 별도로 보존하거나 다른 정책을 설계해야 합니다.

Known A and unknown C both map to [0], so this feature alone cannot distinguish them. Preserve the unknown flag or choose another declared policy.

26. 절편과 두 열의 의존Dependence of intercept and two indicators

모든 훈련 행이 A 또는 B이고 절편·A표시·B표시 세 열로 예측합니다. 세 계수가 유일하지 않을 수 있음을 계수 이동으로 보이세요.

All training rows are A or B. Use intercept, A indicator and B indicator. Show a coefficient shift preserving training predictions.

풀이와 확인할 이유Solution and explanation

모든 행에서 A+B=1입니다. 절편에 t를 더하고 A·B 계수에서 각각 t를 빼도 각 훈련 예측은 같습니다. 따라서 유일 계수 조건이 없습니다. unknown [0, 0]의 예측은 절편 이동에 따라 바뀔 수 있어 처리 약속도 중요합니다.

Since A+B=1, adding t to the intercept and subtracting t from both category coefficients preserves each training prediction. Coefficients are not uniquely determined. Unknown [0, 0] instead changes with the intercept, making the convention consequential.

27. 정답 평균 변환의 합산An outcome-mean transformation

훈련 A의 정답이 0·2이고 검증 A의 정답은 100입니다. 범주별 정답 평균을 입력으로 쓸 때 train-only 평균과 검증 정답까지 넣은 평균을 구하세요.

Training A outcomes are zero/two; validation A outcome is 100. Compare category outcome means fitted using training only and including validation.

풀이와 확인할 이유Solution and explanation

train-only 평균은 1입니다. 검증 정답까지 넣으면 (0+2+100)/3=34입니다. 검증 행에 34를 넣으면 그 행 정답이 이미 표현에 들어갑니다. 전체 전처리를 평가의 훈련 안에서 맞춰야 하는 예입니다.

Training gives one; including validation gives 34. Assigning 34 to the validation row uses its own outcome in the representation. Fit the entire outcome-using transformation within the evaluation’s training data.

28. 사전 fit에 새 이름만 쓰는 경우Adding an unlabeled new category

훈련 A·B, 새 C의 정답은 보지 않고 이름 C를 사전에 추가했습니다. 시험 정답 fit과 같은 일인가요? 기존 두 열 모형을 그대로 쓸 수 있나요?

Training categories are A/B. Add new C to the dictionary without seeing its outcome. Is this fitting test outcomes, and can the old two-column learner be used unchanged?

풀이와 확인할 이유Solution and explanation

정답을 쓰지 않았으므로 시험 정답으로 적합한 일은 아닙니다. 그러나 새 입력의 범주를 미리 본 다른 정보 조건이고, 열이 두 개에서 세 개가 되어 기존 두 열 계수와 그대로 결합할 수 없습니다. 정보 범위와 차원 일치를 각각 설명해야 합니다.

No outcome was fitted, but the procedure used new input categories in advance. Its feature dimension also changed from two to three, so the old two-column coefficients cannot simply be reused. Information scope and dimension consistency are separate issues.

29. 빈 사전An empty dictionary

훈련 범주가 빈 목록이고 새 입력은 A입니다. 사전에 A가 있다고 가정하거나 성공한 0열 벡터로 평가해도 되나요? 이 장의 정의 상태를 쓰세요.

Training categories are empty and new input is A. May the calculator pretend A was learned or score a successful zero-column representation? State its convention.

풀이와 확인할 이유Solution and explanation

훈련에서 배운 범주가 없으므로 fitDefined=false입니다. 새 A를 배운 범주로 만들지 않고 변환·평가도 미정의로 둡니다. 이 계산 범위의 상태와 별도로, 사전 지정 범주를 제공하는 다른 절차는 명시적으로 설계할 수 있습니다.

No training category was learned, so fitDefined=false and transformation/evaluation remain undefined. A separately declared external dictionary would be another explicitly designed procedure.

30. 열 뒤바꿈의 예측Prediction after swapping columns

사전 [A, B]의 계수가 [10, 1]이며 절편은 0입니다. 새 B의 올바른 벡터와, 실수로 뒤바꾼 벡터의 예측을 비교하세요.

Dictionary [A, B] has coefficients [10, 1] and zero intercept. Compare prediction for new B with its correct vector and an accidentally swapped vector.

풀이와 확인할 이유Solution and explanation

올바른 B=[0, 1]은 예측 1입니다. 뒤바꾼 [1, 0]은 예측 10입니다. 같은 벡터 길이만 검사해서는 잡지 못하므로 열 이름·순서와 모형을 함께 보관해야 합니다.

Correct B=[0, 1] predicts one; swapped [1, 0] predicts ten. Matching vector lengths alone misses this error. Preserve column names/order with the learner.

31. 두 행 ridge의 해Two-row ridge solution

훈련 쌍 (0, 0), (2, 2), z=x−1, 예측 a_z+bz를 둡니다. 절편은 무벌점이고 목적은 훈련 MSE+b²입니다. 대칭 최적 a_z=1을 이용해 b·원절편·새 x=4의 예측을 구하세요.

Training pairs are (0, 0)/(2, 2), with z=x−1 and prediction a_z+bz. Minimize training MSE+b² without intercept penalty. Given symmetric optimum a_z=1, find b, the raw intercept and prediction at x=4.

풀이와 확인할 이유Solution and explanation

목적은 (1−b)²+b²=2(b−1/2)²+1/2이므로 b=1/2입니다. 원식은 1+(x−1)/2=1/2+x/2이며 새 예측은 5/2입니다. 훈련 MSE와 벌점은 각각 1/4입니다.

The objective equals (1−b)²+b²=2(b−1/2)²+1/2. Thus b=1/2, raw prediction is 1/2+x/2 and new prediction 5/2. Training MSE and penalty are each 1/4.

32. λ를 0으로 바꾸기Set λ to zero

훈련 (0, 0), (2, 2)에서 절편을 포함한 직선의 훈련 MSE만 최소화합니다. 정확히 맞는 원계수와 새 x=4 예측을 구하세요. 양의 scale을 일관되게 바꾸어도 예측이 같나요?

Fit an intercept line to (0, 0)/(2, 2) by training MSE alone. Find exact raw coefficients and prediction at four. Does a consistently changed positive scale preserve predictions?

풀이와 확인할 이유Solution and explanation

두 서로 다른 x를 통과하는 유일 직선은 a=0, b=1이므로 예측 4입니다. 벌점 없이 절편을 포함한 가역 affine 좌표 변경은 가능한 예측집합을 보존하므로 계수도 일관되게 다시 맞추면 예측이 같습니다.

The unique line is a=0, b=1, predicting four. With no penalty and an intercept, an invertible affine coordinate change preserves the prediction set, so consistently refitted coefficients preserve predictions.

33. 전체 입력 scale의 다른 해A different all-input scale solution

훈련 (0, 0), (2, 2)만으로 정답 적합을 하되 scale²은 입력 0·2·4 전체 분산 8/3을 씁니다. λ=1, 절편 무벌점에서 원기울기·절편·x=4 예측을 구하세요.

Fit outcomes only from (0, 0)/(2, 2), but use squared scale 8/3 from inputs zero/two/four. At λ=1 with an unpenalized intercept, find raw slope/intercept and prediction at four.

풀이와 확인할 이유Solution and explanation

훈련 평균 x̄=ȳ=1이므로 a=1−b입니다. 목적 (1−b)²+(8/3)b²의 최소 기울기는 3/11이며 절편은 8/11입니다. 새 예측은 8/11+12/11=20/11입니다. 새 정답을 쓰지는 않았지만 새 입력으로 벌점 무게가 달라졌습니다.

Training means give a=1−b. Minimizing (1−b)²+(8/3)b² gives slope 3/11 and intercept 8/11, predicting 20/11. No new outcome was fitted, but the new input changed the penalty weight.

34. 오차만 작으면 목적도 작은가Does smaller error mean smaller objective?

훈련 (0, 0), (2, 2), scale²=1에서 목적은 훈련 MSE+b²입니다. 직선 y=x와 ŷ=1/2+x/2의 MSE·벌점·목적을 비교하세요.

For training (0, 0)/(2, 2) and squared scale one, minimize training MSE+b². Compare y=x with ŷ=1/2+x/2.

풀이와 확인할 이유Solution and explanation

y=x는 MSE 0·벌점 1·목적 1입니다. 두 번째는 두 오차가 ±1/2이므로 MSE 1/4·벌점 1/4·목적 1/2입니다. 훈련 오차만 낮은 첫 직선이 이 규제 목적에서 더 좋은 해는 아닙니다.

The first has MSE zero, penalty one and objective one. The second has MSE 1/4, penalty 1/4 and objective 1/2. Lower unpenalized training error does not imply a lower regularized objective.

35. 표준화 계수에서 원기울기로Convert a standardized slope

z=(x−10)/2이고 예측은 ŷ=5+6z입니다. 원절편·원기울기와 표준화 기울기 제곱 벌점 6²을 원좌표로 표현하세요.

Let z=(x−10)/2 and ŷ=5+6z. Find raw coefficients and express standardized slope penalty 6² in raw coordinates.

풀이와 확인할 이유Solution and explanation

전개하면 ŷ=5+3(x−10)=−25+3x입니다. 원기울기 b=3·scale²=4이므로 표준화 벌점은 s²b²=4×9=36입니다. 원기울기 제곱 9만 쓰면 같은 벌점이 아닙니다.

Expanding gives ŷ=−25+3x. Raw slope three and squared scale four give s²b²=36. Penalizing only raw slope squared nine would define another objective.

36. 저장한 계수와 다른 변환Mix coefficients with another transform

원예측은 2+3x입니다. c=10, s=2 좌표로 계수를 바꾼 뒤 새 x=14를 예측하세요. 같은 변환 계수에 실수로 c′=12, s′=4를 적용한 결과와 비교하세요.

Original prediction is 2+3x. Convert coefficients to c=10, s=2 coordinates and predict x=14. Compare using the same transformed coefficients with mistaken c′=12, s′=4.

풀이와 확인할 이유Solution and explanation

올바른 표준화 절편은 2+3×10=32, 기울기는 3×2=6입니다. 올바른 z=2이므로 예측 44입니다. 잘못된 z′=(14−12)/4=1/2를 같은 계수에 넣으면 35입니다. 좌표 변경과 계수 변경을 일치시켜야 합니다.

Correct transformed intercept/slope are 32/six. Correct z=two predicts 44. Mistaken z′=1/2 with those same coefficients predicts 35. Transform and coefficient conversion must agree.

37. 상수 x와 비유일 OLSConstant x and nonunique OLS

훈련 x=2·2, y=0·2에서 절편과 기울기를 맞춥니다. λ=0의 최소 계수 전체를 쓰고, scale 1·λ=1 ridge와 비교하세요.

Fit an intercept/slope to x=two/two, y=zero/two. Give all λ=0 minimizers, then compare ridge with scale one and λ=1.

풀이와 확인할 이유Solution and explanation

OLS의 공통 예측은 평균 1이라 a+2b=1인 모든 계수가 최소입니다. ridge는 같은 예측을 만들면서 b²를 최소화하므로 b=0, a=1로 유일합니다. 훈련 MSE는 1입니다. λ=0에서 계수 비유일은 최소 예측의 부재와 다릅니다.

OLS predicts mean one, so every coefficient pair satisfying a+2b=1 minimizes error. Ridge also minimizes b² and uniquely chooses b=0, a=1. Training MSE is one. Nonunique coefficients do not mean minimizing predictions fail to exist.

38. 전결측 열의 파이프라인A pipeline with an all-missing feature

훈련 X=[[null], [null]], y=[0, 2]이고 새 X=[[10]]입니다. 파이프라인 첫 단계는 훈련 평균 대체입니다. 새 10으로 대체값을 만든 뒤 성공한 적합이라고 할 수 있나요?

Training X=[[null], [null]], y=[0, 2], new X=[[10]]. The first stage is training-mean imputation. May it learn a fill from new ten and report a successful fit?

풀이와 확인할 이유Solution and explanation

아니요. 지정된 첫 단계는 훈련 평균을 요구하지만 가용 훈련 입력이 없습니다. all-missing-fit-feature 상태이고 새 10을 몰래 fit에 넣지 않습니다. 상수 대체나 열 제거를 쓰려면 다른 선언한 파이프라인으로 바꿔야 합니다.

No. The declared first stage requires an available training value, so it reports all-missing-fit-feature. Using new ten silently changes the procedure. Constant filling or feature removal must be declared as another pipeline.

39. 두 열 ridge의 닫힌 계산A closed two-feature ridge calculation

훈련 입력 (1, 0), (0, 1), (2, 1), 정답 1·2·3입니다. 입력 평균은 (1, 2/3), 정답 평균은 2, n분모 공분산 C=diag(2/3, 2/9), r=(1/3, 1/3)입니다. scale²은 C의 두 대각, λ=1입니다. 원계수와 MSE·벌점을 구하세요.

Training inputs (1, 0)/(0, 1)/(2, 1) have outcomes one/two/three. Means are (1, 2/3) and two. Given divisor-n C=diag(2/3, 2/9), r=(1/3, 1/3), squared scales equal the diagonal of C and λ=1. Find raw coefficients, MSE and penalty.

풀이와 확인할 이유Solution and explanation

C+S=diag(4/3, 4/9)이므로 기울기는 (1/4, 3/4)입니다. 절편은 2−1/4−(3/4)(2/3)=5/4입니다. 훈련 예측 3/2·2·5/2의 MSE는 1/6입니다. 벌점은 (2/3)(1/4)²+(2/9)(3/4)²=1/6이며 목적은 1/3입니다.

C+S=diag(4/3, 4/9), so slopes are (1/4, 3/4). Intercept is 5/4. Predictions 3/2, two, 5/2 give MSE 1/6. Penalty is also 1/6, for objective 1/3.

40. 양의 규제와 유일 기울기Positive regularization and unique slopes

C는 대칭 양의 준정부호 행렬이고 S는 양의 대각 원소를 가진 대각행렬입니다. λ>0에서 C+λS가 양의 정부호임을 보이고 ridge 기울기의 유일성과 연결하세요.

C is symmetric positive semidefinite and S is diagonal with positive entries. Prove C+λS positive definite for λ>0 and connect this to unique ridge slopes.

풀이와 확인할 이유Solution and explanation

0이 아닌 u에 대해 uᵀCu≥0이고 uᵀSu=Σs_j²u_j²>0입니다. 따라서 uᵀ(C+λS)u>0이며 행렬은 가역입니다. 우변 r가 주어진 선형계의 기울기는 유일합니다. λ=0에서는 이 논리만으로 유일성을 얻지 않습니다.

u⊤(C+λS)u>0u^\top(C+\lambda S)u>0

For nonzero u, uᵀCu≥0 while uᵀSu=Σs_j²u_j²>0. Their positive-λ sum is positive, hence the matrix is invertible and the slope system has a unique solution. This reasoning does not ensure uniqueness when λ=0.

u⊤(C+λS)u>0u^\top(C+\lambda S)u>0

41. 첫 fold의 두 예측Predictions from the first fold

네 쌍 (0, 0), (2, 2), (4, 4), (6, 6)에서 원행 1·3을 가리고 2·4로 학습합니다. 평균 대체 후 훈련 n분모 scale·λ=1·절편 무벌점 ridge를 씁니다. 훈련 평균·분산·원계수·가린 예측을 구하세요.

For pairs (0, 0)/(2, 2)/(4, 4)/(6, 6), hold out rows one/three and train on two/four. Use training divisor-n scaling, λ=1 ridge and no intercept penalty. Find moments, raw coefficients and held-out predictions.

풀이와 확인할 이유Solution and explanation

가용 두 훈련 입력 2·6의 평균은 4·분산은 4입니다. 입력과 정답 공분산도 4라 기울기는 4/(4+4)=1/2, 절편은 4−(1/2)4=2입니다. 가린 0·4의 예측은 2·4입니다.

Training inputs two/six have mean four and variance four. Input/outcome covariance is four, giving slope 4/(4+4)=1/2 and intercept two. Held-out zero/four predict two/four.

42. 네 가림 오차의 평균Mean of four held-out errors

네 원행 정답은 [0, 2, 4, 6]이고 자신을 제외한 학습으로 얻은 가림 예측은 [2, 2, 4, 4]입니다. 원순서 제곱오차와 전체 OOF MSE를 구하세요.

Source-order outcomes are [0, 2, 4, 6] and held-out predictions from fits excluding each row are [2, 2, 4, 4]. Find squared errors and pooled OOF MSE.

풀이와 확인할 이유Solution and explanation

오차 제곱은 [4, 0, 0, 4]입니다. 네 행을 모두 포함한 평균은 8/4=2입니다. fold별 점수가 아니라 원행별 가림 예측을 먼저 보관하면 분모와 실패 행을 확인하기 쉽습니다.

Squared errors are [4, 0, 0, 4], averaging eight/four=two. Retaining rowwise held-out predictions makes denominators and failed rows inspectable before aggregating fold scores.

43. global-input fold의 차이The global-input fold contrast

네 쌍 (0, 0), (2, 2), (4, 4), (6, 6)과 fold 0·1·0·1, λ=1입니다. 각 learner는 훈련 정답만 쓰지만 scale²은 전체 입력의 5를 씁니다. 각 훈련 C=r=4입니다. 가림 예측과 전체 MSE를 구하세요.

Use pairs (0, 0)/(2, 2)/(4, 4)/(6, 6), folds zero/one/zero/one and λ=1. Learners use training outcomes only, but squared scale is global input variance five. Each training complement has C=r=four. Find held-out predictions and pooled MSE.

풀이와 확인할 이유Solution and explanation

기울기는 4/9입니다. fold 0 훈련 평균 4라 절편 20/9, fold 1 평균 2라 절편 10/9입니다. 원순서 예측은 [20/9, 2, 4, 34/9]이고 제곱오차는 [400/81, 0, 0, 400/81]입니다. 평균은 200/81로 within-training의 2보다 큽니다.

Slope is 4/9. Training means four/two give intercepts 20/9 and 10/9. Source-order predictions [20/9, 2, 4, 34/9] yield squared errors [400/81, 0, 0, 400/81], averaging 200/81, larger than within-training two.

44. 서로 다른 fold 크기Unequal fold sizes

서로 겹치지 않는 두 검증 fold가 전체 4행을 한 번씩 덮습니다. 첫 3행 평균 손실은 0, 나머지 1행 평균은 8입니다. 전체 행 평균과 fold 평균의 단순 평균을 구하세요.

Two disjoint validation folds cover all four rows once. A three-row fold averages zero loss; a one-row fold averages eight. Compare pooled row loss with the unweighted fold mean.

풀이와 확인할 이유Solution and explanation

행 평균은 (3×0+1×8)/4=2입니다. fold를 같은 무게로 평균하면 (0+8)/2=4입니다. 전체 행 손실을 평가하려면 fold 크기 3/4·1/4를 가중치로 씁니다.

Pooled row loss is two; the unweighted fold mean is four. Evaluating every row equally requires fold weights 3/4 and 1/4.

45. fold마다 다른 대체값Different fills inside different folds

입력 [0, null, 4, 6]에 검증 fold [0, 1, 0, 1]을 붙입니다. 각 훈련 complement의 가용 평균으로 대체합니다. fold 0·1의 대체값과 가려진 결측 행에 쓰는 값을 구하세요.

Inputs [0, null, 4, 6] have validation folds [0, 1, 0, 1]. Fit available means within training complements. Find each fold’s fill and the fill used for the held-out missing row.

풀이와 확인할 이유Solution and explanation

fold 0 훈련은 [null, 6]이므로 대체값 6입니다. fold 1 훈련은 [0, 4]라 대체값 2입니다. 원행 2의 결측은 fold 1에서 가려지므로 2로 채웁니다. 전체 가용 평균 10/3을 재사용한 것이 아닙니다.

Fold zero trains on [null, 6], giving six. Fold one trains on [0, 4], giving two. Missing source row two is held out in fold one, so it receives two rather than global available mean 10/3.

46. 실패한 fold의 전체 점수An undefined fold and the complete score

입력 [null, null, 2, 4], 정답 [0, 1, 2, 3], 검증 fold [1, 1, 0, 0]입니다. 첫 단계는 훈련 평균 대체입니다. fold 0의 상태와 완전 OOF MSE 정의 여부를 판단하세요.

Inputs are [null, null, 2, 4], outcomes [0, 1, 2, 3], validation folds [1, 1, 0, 0]. The first stage is training-mean imputation. Determine fold zero’s state and whether complete OOF MSE exists.

풀이와 확인할 이유Solution and explanation

fold 0 훈련은 원행 1·2의 전결측 입력입니다. 대체 평균을 못 배우므로 가린 원행 3·4의 예측은 실패합니다. 전체 네 행 예측이 완성되지 않았으므로 complete OOF MSE는 미정의입니다. 성공한 행만 평균한 다른 점수를 전체 점수로 바꾸어 부르지 않습니다.

Fold zero trains on all-missing source rows one/two, so its fill and predictions for rows three/four fail. Not every row receives a prediction; complete OOF MSE is undefined. A score on successful rows alone has another denominator.

47. 빈 검증 foldAn empty validation fold

k=3에서 원행 검증 역할이 [0, 1, 0, 1]입니다. 앞 두 fold는 각각 2행·평균 손실 2이고 세 번째는 비었습니다. 전체 행 평균과 빈 fold 처리 방법을 쓰세요.

With k=3, source validation folds are [0, 1, 0, 1]. The first two have two rows each and mean loss two; the third is empty. Find pooled row loss and handle the empty fold.

풀이와 확인할 이유Solution and explanation

전체 네 행 평균은 (2×2+2×2)/4=2입니다. 빈 fold의 평균은 미정의로 표시하고 행 기여가 0임을 씁니다. 임의 손실 0을 붙여 세 fold를 단순 평균한 4/3은 같은 행 평가가 아닙니다.

Pooled loss is two. Mark the empty fold mean undefined with zero row contribution. Inventing loss zero and averaging three fold means gives 4/3, a different and inappropriate row score.

48. global 대체값A global fill contrast

입력 [0, null, 4, 6] 전체에서 대체값을 한 번 배우는 global-inputs 대조와, fold [0, 1, 0, 1]의 훈련 complement 대체를 비교하세요. 세 평균을 구하세요.

For inputs [0, null, 4, 6], compare one global-input mean fill with training-complement fills for folds [0, 1, 0, 1]. Find all three means.

풀이와 확인할 이유Solution and explanation

전체 가용 평균은 (0+4+6)/3=10/3입니다. fold 0 훈련 평균은 6, fold 1은 2입니다. 가린 입력을 보았는지와 가린 정답을 쓰지 않았는지는 서로 다른 문장이므로 둘 다 기록합니다.

Global available mean is 10/3. Fold-zero training gives six and fold-one training two. Seeing held-out inputs and excluding held-out outcomes are separate facts to record.

49. 새 정답은 점수만 바꾼다New outcomes change the score only

훈련 (0, 0), (2, 2), train-only scale²=1·λ=1 ridge의 새 x=4 예측은 5/2입니다. 새 정답을 4에서 100으로 바꾸면 계수와 두 제곱손실은 어떻게 되나요?

Train-only ridge on (0, 0)/(2, 2), squared scale one and λ=1 predicts 5/2 at new x=four. Change only its outcome from four to 100. What happens to coefficients and squared losses?

풀이와 확인할 이유Solution and explanation

새 정답은 적합에 쓰지 않으므로 원절편·기울기는 1/2·1/2로 같습니다. 손실만 (4−5/2)²=9/4에서 (100−5/2)²=38,025/4로 바뀝니다. 예측을 만드는 정보와 평가 정답을 분리한 결과입니다.

Raw intercept/slope remain 1/2 because the new outcome is not fitted. Loss changes from 9/4 to 38,025/4. Separate information producing predictions from outcomes evaluating them.

50. 고정 상태의 기대 손실Expected loss of a fixed fitted state

훈련에서 정한 상수 예측은 1이고, 독립 새 정답 Y는 0 또는 2를 각각 확률 1/2로 가집니다. 기대 제곱손실과 정답을 먼저 보고 ŷ=Y를 고른 경우의 손실을 비교하세요.

Training has chosen constant prediction one. Independent new Y equals zero or two with probability 1/2 each. Compare expected squared loss with choosing ŷ=Y after seeing the outcome.

풀이와 확인할 이유Solution and explanation

고정 예측의 손실은 두 경우 모두 1이라 기대값 1입니다. ŷ=Y는 항상 손실 0이지만 새 정답을 쓴 다른 규칙입니다. 두 수치를 같은 예측 절차의 독립 성과로 비교할 수 없습니다.

The fixed prediction has loss one in either case, hence expectation one. Choosing ŷ=Y gives zero but uses a different outcome-informed rule. It is not an independent score for the original procedure.

51. 실제 연도의 세 역할Roles for actual annual records

실제 한국 연간 자료 1980–2024에서 훈련 1980–2014, 검증 2015–2019, 시험 2020–2024를 선택했습니다. 각 행 수와 전체 수를 구하고, 입력·정답의 단위를 쓰세요. 입력은 GDPpc2015USD, 정답은 period life expectancy years입니다.

Actual Korean annual data cover 1980–2024. Chosen training is 1980–2014, validation 2015–2019 and test 2020–2024. Count rows and state units for GDPpc2015USD input and period-life-expectancy-years outcome.

풀이와 확인할 이유Solution and explanation

양끝 연도를 포함해 각각 35·5·5행, 전체 45행입니다. GDP는 2015 USD/인이고 정답은 기간 기대수명 연수입니다. 연도 개수와 역할을 고정한 전처리 비교이며, 2026 보관본 자체가 과거 실시간 빈티지를 뜻하지 않습니다.

Inclusive counts are 35/five/five, totaling 45. GDP units are 2015 USD per person; outcomes are years of period life expectancy. The retained 2026 snapshot alone does not establish historical real-time vintages.

52. 국가 OLS 불변성Country OLS invariance

같은 35개 훈련 행·정답으로 절편 포함·벌점 없는 full-rank OLS를 맞춥니다. 훈련 scale 또는 전체 입력 scale 모두 양수이며 각 좌표에서 계수를 일관되게 맞춥니다. 원예측 a+bx가 두 좌표에서 같은 예측집합을 갖는 이유를 보이세요.

Fit full-rank intercept OLS without penalty to identical 35 training rows/outcomes. Training-only and all-input scales are positive and coefficients are fitted consistently in each coordinate. Prove their possible prediction sets coincide for a+bx.

풀이와 확인할 이유Solution and explanation

z=(x−c)/s에서 a_z=a+bc, b_z=bs이면 같은 예측입니다. 역으로 b=b_z/s, a=a_z−b_zc/s이므로 일대일입니다. 따라서 같은 훈련 손실의 최소 예측을 보존합니다. 이 특수 불변성이 모든 규제 모형이나 모든 정보 조건까지 같게 만들지는 않습니다.

For z=(x−c)/s, use a_z=a+bc and b_z=bs. The inverse is b=b_z/s, a=a_z−b_zc/s. This bijection preserves training losses and their minimizing predictions. It does not establish invariance for every regularized learner or information condition.

53. 실제 숫자 정답 수의 분모Denominators for actual digit scores

동일한 제공 시험 손글씨 1,797행에서 raw·훈련 scale·전체 입력 scale의 정답 수는 각각 1,606·1,599·1,595입니다. 정확도 분수와 순위를 쓰고 어떤 방법이 자동 개선되었다고 할 수 있는지 설명하세요.

On the same 1,797 provided test images, raw/training-scale/all-input-scale methods get 1,606/1,599/1,595 correct. State exact accuracy fractions and ranking. Does standardization automatically improve this result?

풀이와 확인할 이유Solution and explanation

정확도는 1606/1797, 1599/1797, 1595/1797입니다. 같은 분모에서 raw>훈련 scale>전체 입력 scale입니다. 이번 관측 성과는 표준화가 자동 개선된다는 주장을 뒷받침하지 않습니다. 중심은 모두 훈련에서 맞추었고 전체 입력 방법도 시험 정답을 fit에 쓴 것은 아닙니다.

Accuracies are 1606/1797, 1599/1797 and 1595/1797. Raw ranks first, then training-only and all-input scaling. This observed comparison does not show automatic improvement. Centroids all use training outcomes; the all-input scaler still excludes test outcomes.

54. 상수 픽셀의 거리 기여Distance contributions from constant pixels

실제 훈련 픽셀 인덱스 0·39가 항상 0입니다. 선택한 시험 행에서도 두 값은 0이고 각 훈련 중심도 0입니다. 분산 0에서 scale 1 약속을 쓸 때 두 열의 제곱거리 기여와 보존 여부를 쓰세요.

Actual training pixel indices zero and 39 are always zero. They and each training centroid are also zero in a selected test row. Use scale one for zero variance. Find their squared-distance contributions and whether columns were deleted.

풀이와 확인할 이유Solution and explanation

각 기여는 (0−0)²/1=0입니다. 열을 삭제하거나 0으로 나눈 것이 아니라 scale 1로 유지했습니다. 픽셀 원위치가 남아 있어 실제 8×8 그림과 64열 순서를 연결할 수 있습니다.

Each contributes (0−0)²/1=0. Columns remain with scale one rather than being deleted or divided by zero. Preserved positions still align the 64 features with the 8×8 image.

55. 거리 무게로 순위가 바뀌기Changing a nearest-centroid ranking

설명용 중심 c₀=(0, 0), c₁=(3, 4), 새 x=(3, 0)입니다. 원단위 제곱거리와 scale²=(1, 4)로 나눈 제곱거리를 계산하고 최근접 중심을 비교하세요.

Toy centroids are c₀=(0, 0), c₁=(3, 4), new x=(3, 0). Compare raw squared distances with distances divided by squared scales (1, 4).

풀이와 확인할 이유Solution and explanation

원단위 거리는 c₀까지 9, c₁까지 16이라 0을 고릅니다. 가중 거리는 c₀까지 9, c₁까지 16/4=4라 1을 고릅니다. 같은 중심과 입력이어도 열별 무게가 최근접 순위를 바꿀 수 있습니다.

Raw distances nine/16 choose class zero. Weighted distances nine/four choose class one. Identical centroids and input can produce another nearest label when feature weights change.

56. 원단위 벌점 두 개Two raw-coordinate penalties

설명용 원기울기는 (2, −1), λ=1이고 절편은 무벌점입니다. scale²=(4, 9)와 (1, 16)의 표준화 기울기 제곱 벌점을 각각 구하세요. 실제 와인의 추정 계수라고 가정하지 않습니다.

Toy raw slopes are (two, −1), λ=1 and the intercept is unpenalized. Compute standardized-slope penalties for squared scales (four, nine) and (one, 16). These are not claimed actual wine estimates.

풀이와 확인할 이유Solution and explanation

첫 벌점은 4×2²+9×(−1)²=25, 둘째는 1×2²+16×(−1)²=20입니다. 같은 λ와 같은 원기울기라도 학습한 scale에 따라 표준화 계수 벌점이 달라집니다.

Penalties are 4·2²+9·(−1)²=25 and 1·2²+16·(−1)²=20. Identical λ and raw slopes can carry different standardized penalties under different scales.

57. 실제 와인 정답의 사용 수Actual wine outcome use

실제 와인 역할은 훈련 952·검증 321·시험 326행입니다. train-only와 all-input scale 모두 같은 952개 훈련 정답으로 계수를 맞춥니다. 전체 입력 행 수, 적합에서 제외한 정답 수와 전체 입력 scale의 정보 차이를 쓰세요.

Wine roles contain 952 training, 321 validation and 326 test rows. Both scaler methods fit coefficients to the same 952 training outcomes. Give total inputs, outcomes excluded from fitting and the all-input scaler’s information difference.

풀이와 확인할 이유Solution and explanation

전체 입력은 1,599행이고 적합에서 제외한 검증·시험 정답은 647개입니다. 전체 입력 scale은 1,599개 입력을 보지만 learner 정답은 여전히 952개입니다. 시험 정답 제외와 시험 입력 미사용은 같은 조건이 아닙니다.

There are 1,599 inputs and 647 validation/test outcomes excluded from fitting. All-input scaling sees 1,599 inputs while the learner still fits 952 outcomes. Excluding test outcomes differs from excluding test inputs.

58. 합 오차 소프트웨어의 λTranslate λ to a sum-error objective

n=4에서 이 장 목적이 MSE+(1/2)Σβ_zj²입니다. 같은 최소해를 얻으려면 SSE+αΣβ_zj² 형태의 목적에서 α를 얼마로 두어야 하나요? 절편은 두 경우 모두 무벌점입니다.

At n=4, the chapter minimizes MSE+(1/2)Σβ_zj². What α gives the same minimizers for SSE+αΣβ_zj²? Both leave the intercept unpenalized.

풀이와 확인할 이유Solution and explanation

전체 목적에 양수 4를 곱해도 최소해는 같습니다. 4MSE=SSE이고 벌점 계수는 4×1/2=2이므로 α=2입니다. λ 숫자를 소프트웨어 사이에 그대로 복사하기 전에 합·평균 정의를 확인합니다.

Multiplying the entire objective by positive four preserves minimizers. Four times MSE is SSE and four times 1/2 is two, so α=2. Check sum versus mean normalization before copying a numeric penalty between packages.

59. 단위 환산과 ridge의 불변 목적Unit conversion preserves the ridge objective

모든 훈련 열의 분산이 양수이고 x′_j=a_jx_j+d_j, a_j≠0를 모든 행에 일관되게 적용합니다. 각 표현에서 훈련 scale을 배우고 절편 무벌점 MSE+λΣs_j²b_j²를 씁니다. 예측과 목적을 보존하는 계수 대응을 보이세요.

Every training feature has positive variance. Apply x′_j=a_jx_j+d_j with a_j≠0 consistently to all rows. Fit each training scale and minimize intercept-unpenalized MSE+λΣs_j²b_j². Give a coefficient mapping preserving predictions/objectives.

풀이와 확인할 이유Solution and explanation

b′_j=b_j/a_j, a′=a−Σb_jd_j/a_j로 두면 원예측이 같습니다. 새 scale²은 a_j²s_j²이므로 s′_j²b′_j²=s_j²b_j²입니다. 따라서 오차와 벌점 모두 같고 계수 대응도 가역이라 최소해집합이 대응합니다. 분산 0의 scale 1 약속은 이 양의 분산 증명 범위에서 제외합니다.

sj′2bj′2=sj2bj2s_j^{\prime2}b_j^{\prime2}=s_j^2b_j^2

Set b′_j=b_j/a_j and a′=a−Σb_jd_j/a_j. Predictions agree. New squared scales are a_j²s_j², so each weighted slope square is unchanged. The invertible mapping preserves error, penalty and minimizer sets. Constant-feature scale-one conventions lie outside this positive-variance proof.

sj′2bj′2=sj2bj2s_j^{\prime2}b_j^{\prime2}=s_j^2b_j^2

60. 전체 파이프라인의 조건부 평가Conditional evaluation of an entire pipeline

D의 함수 A(D)는 전처리와 예측을 모두 포함합니다. D와 독립인 새 평가 쌍 m≥1개는 같은 법칙을 따르고 각 손실은 적분 가능합니다. R(D)=E[ℓ(Y, A(D)(X))|D]라 할 때 평균 평가 손실의 조건부 기대를 구하세요. 평가 입력까지 다시 fit하면 같은 논증이 그대로 적용되나요?

A(D), including preprocessing and prediction, is a function of D. There are m≥1 new evaluation pairs with a common law independent of D and integrable losses. Let R(D)=E[ℓ(Y, A(D)(X))|D]. Find conditional expected average loss. Does the same argument apply unchanged after fitting evaluation inputs?

풀이와 확인할 이유Solution and explanation

선형성으로 각 항의 조건부 기대가 R(D)이므로 평균의 조건부 기대도 R(D)입니다. 분산 공식을 추가하지 않는 이 기대 항등식에는 평가 행 사이 독립보다 같은 조건부 주변법칙이 핵심입니다. 평가 입력으로 다시 fit하면 규칙이 A(D, X_eval)이 되어 각 행과 규칙의 결합법칙을 다시 분석해야 하며 같은 고정 A(D) 논증을 그대로 쓰지 않습니다.

E[L‾∣D]=1m∑i=1mR(D)=R(D)\mathbb E[\overline L\mid D]=\frac1m\sum_{i=1}^mR(D)=R(D)

Each term has conditional expectation R(D), so linearity gives the same expectation for their mean. This expectation identity needs matching conditional marginals; evaluation-row independence would be additional for variance formulas. Refitting on evaluation inputs creates A(D, X_eval), requiring analysis of its joint law with evaluated rows rather than reusing the fixed-A(D) argument.

E[L‾∣D]=1m∑i=1mR(D)=R(D)\mathbb E[\overline L\mid D]=\frac1m\sum_{i=1}^mR(D)=R(D)

자료와 출처Data and sources

실습에 추가한 실제 입력과 출처Additional observed lab inputs and provenance

실제 자료 사례Actual-data cases · 원자료·단위·결측·변환·출처Inputs, units, missingness, transformations and sources

자료별 확보일·원행 식별·단위·이용 조건은 출처 기록을 확인하세요. 학습 사본은 제공처의 현재 최신 자료와 다를 수 있습니다.Consult each source record for retrieval dates, row identifiers, units and terms. Teaching copies can differ from current provider releases.

자료사전·출처·이용 조건Data dictionary, sources and terms