최근접 이웃·거리·국소 평균·차원Nearest neighbours, metrics, local averages and dimension
가까운 사례를 고르는 규칙에서 실제 자료의 검증·차원·한계까지From choosing nearby records to real-data evaluation, dimension and limitations
실습 6종 · 풀이 포함 연습문제 60개6 labs · 60 exercises with solutions
기초Foundations
1. 비슷한 사례에서 답을 빌린다1. Borrow an answer from similar examples
처음 보는 문제에서 비슷한 경험을 찾는 것은 익숙한 생각입니다. 새 동네의 집 월세를 예상할 때도 비슷한 크기·위치의 집을 살펴볼 수 있습니다. 최근접 이웃(k-nearest neighbours, kNN)은 이 생각을 계산 규칙으로 만듭니다. 먼저 무엇을 비슷하다고 볼지 숫자로 정하고, 가까운 기록을 고른 다음 그 기록의 실제 결과를 모읍니다. 처음부터 모든 집에 맞는 하나의 직선을 추정하는 방식과는 출발점이 다릅니다.
설명을 위해 입력 점수 1·2·5인 가상의 집 세 채와 월세 10·14·26을 가정합시다. 단위도 설명용이라고 정합니다. 새 집의 점수가 3.5라면 세 집까지 거리는 2.5·1.5·1.5입니다. 가까운 두 집의 결과를 평균하면 (14+26)/2=20입니다. 여기서 20은 정한 거리와 이웃 수 아래의 예측입니다. 실제 새 집의 월세를 관측했다는 뜻도, 이 세 집이 실제 조사 자료라는 뜻도 아닙니다.
이 규칙의 장점은 왜 그 답이 나왔는지 원행까지 추적하기 쉽다는 점입니다. 반대로 잘못된 단위나 관련 없는 특성으로 비슷함을 정하면 엉뚱한 이웃에게 답을 빌리게 됩니다. 이 장은 거리 계산만 배우고 끝내지 않습니다. 동률·결측·스케일·검증·차원과 실제 국가·개인·기업 자료를 차근차근 연결합니다.
설명용 세 집과 새 집 · 실제 조사 아님
집
입력 점수
가정한 월세
3.5까지 거리
A
1
10
2.5
B
2
14
1.5
C
5
26
1.5
새 집
3.5
아직 관측하지 않음
0
When facing something new, we often look for a similar experience. To predict the rent of a new home, we might inspect homes with similar size and location. The k-nearest-neighbours rule makes this idea explicit: define similarity numerically, select nearby records, and combine their observed outcomes. It begins differently from fitting one line intended to describe every home.
For an assumed illustration, three homes have input scores 1, 2 and 5 and rents 10, 14 and 26 in illustrative units. A new score of 3.5 has distances 2.5, 1.5 and 1.5. Averaging the two nearest outcomes gives twenty. This is a prediction under a declared distance and neighbour count. It is neither an observation of the new rent nor a claim that these invented homes were surveyed.
The rule makes an answer traceable to source records. But inappropriate units or irrelevant features can direct it toward the wrong comparisons. We therefore study ties, missingness, scaling, evaluation and dimension alongside the arithmetic, before applying the method to actual country, individual and business records.
Three assumed homes and a query; not actual survey records
Home
Input score
Assumed rent
Distance to 3.5
A
1
10
2.5
B
2
14
1.5
C
5
26
1.5
Query
3.5
Unobserved
0
기초Foundations
2. 입력·이웃·예측·실제 결과를 구분한다2. Separate features, neighbours, prediction and outcome
훈련 자료 한 행은 어떤 대상을 관찰한 기록입니다. x는 예측에 쓸 입력, y는 그 대상에서 이미 관찰한 결과입니다. 새 대상의 입력을 x₀라고 쓰고, 우리가 계산한 답을 ŷ(x₀)라고 씁니다. 새 대상의 실제 결과 y₀는 나중에 얻거나 평가용으로 따로 숨겨 둡니다. ŷ와 y₀를 같은 열에 적으면 예측이 얼마나 틀렸는지 확인할 수 없습니다.
입력은 여러 개일 수 있습니다. 예를 들어 기업 사례의 x는 통화 초·통화 횟수·통화 실패 횟수이고, 결과는 이후 이탈 여부입니다. 사람이 실제로 이탈했는지 모른다는 것과, 이미 이탈을 알아낸 뒤 그 결과를 예측 입력에 섞는 것은 다릅니다. 전자는 예측 문제이고 후자는 답을 미리 본 평가가 될 수 있습니다. 이용 가능 시점과 자료의 단위를 먼저 확인합니다.
순수한 이웃 검색에는 결과 y가 없어도 됩니다. 반면 이웃의 결과를 평균해 예측하려면 그 이웃에게 유효한 y가 있어야 합니다. 따라서 이 장의 neighbours 실습은 입력이 완전한 행을, predict 실습은 입력과 훈련 결과가 함께 완전한 행을 사용합니다. 실제 개인 자료에서 이 두 분모가 다른 이유를 숨기지 않습니다. 결측 y를 임금 0이나 비이탈로 만들어 넣지 않습니다.
(xi,yi),i=1,…,n;x0⟼y(x0),y0 is held out
A training row records one observed unit. Its x contains predictors and its y an already observed outcome. Write the new unit’s predictors as x₀ and the computed answer as ŷ(x₀). Its actual outcome y₀ is obtained later or held aside for evaluation. Keeping predictions and actual outcomes in separate columns makes errors measurable.
Features can form a vector. In the business case they are seconds of use, call frequency and failed calls; the outcome is subsequent churn. Not yet knowing churn is a prediction problem. Inserting information that already reveals it into the inputs can instead make evaluation answer-aware. Verify when each field was available and what its units mean.
Pure geometric search does not require y, whereas predicting from neighbours requires valid training outcomes. The neighbours API uses complete predictors; predict also requires complete training outcomes. Their denominators can therefore differ in the actual individual case. Missing earnings or churn labels are not replaced by zero.
(xi,yi),i=1,…,n;x0⟼y(x0),y0 is held out
기초Foundations
3. 수직선의 거리는 방향을 없앤 차이3. Distance on a line is a difference without direction
수직선에서 2와 5 사이는 세 칸입니다. 2−5는 −3이지만 거리는 −3칸이라고 하지 않으므로 절댓값을 씁니다. |2−5|=|5−2|=3입니다. 같은 위치라면 차이가 0이고 거리도 0입니다. 새 점 3.5에서 앞의 집들을 비교할 때도 이 규칙을 한 행씩 적용했습니다.
가까운 순서와 결과가 큰 순서는 다른 순서입니다. x=1,2,5에서 결과가 10,14,26이더라도 이웃은 y를 보고 고르지 않습니다. 결과값이 마음에 든다는 이유로 가까운 두 집을 바꾸면 공개한 규칙이 달라집니다. 훈련 기록이 먼저 주어지고, 새 입력과 거리 규칙으로 이웃이 정해진 뒤에 그 결과를 모읍니다.
소수와 분수도 같은 규칙입니다. 1/3과 5/6의 거리는 |2/6−5/6|=1/2입니다. 컴퓨터 화면에 두 아주 작은 거리가 모두 0.0000으로 보이더라도 수학적으로 같다고 단정할 수 없습니다. 실습은 입력을 정확한 분수로 보존해 순위를 정하고, 기본 화면에는 읽기 쉬운 근삿값을 표시합니다. 정확값 펼치기는 그 순서의 근거를 확인하는 용도입니다.
d(a,b)=∣a−b∣,d(31,65)=21
The points two and five are three steps apart. Their difference can be negative, but distance is nonnegative, so use an absolute value: |2−5|=|5−2|=3. Equal positions have distance zero. The distances from the new score 3.5 follow this same row-by-row calculation.
Ordering inputs by proximity differs from ordering outcomes by size. Even when outcomes rise with x, neighbours are selected without inspecting which y gives a preferred answer. Changing neighbours because their outcomes look attractive changes the announced procedure. Fix the records and rule, select using inputs, then combine outcomes.
Fractions follow the same rule: the distance from 1/3 to 5/6 is 1/2. Two tiny distances displayed as 0.0000 need not be equal. The engine ranks exact rational values while displaying concise approximations. The exact-value disclosure preserves the evidence behind the ordering.
d(a,b)=∣a−b∣,d(31,65)=21
기초Foundations
4. 두 방향을 함께 재는 피타고라스4. Combine two directions using Pythagoras
가로로 3칸, 세로로 4칸 떨어진 두 점을 생각합시다. 길을 따라 가로·세로를 따로 걸으면 일곱 칸이지만, 두 점을 바로 잇는 선분은 길이 5입니다. 직각삼각형에서 3²+4²=5²이기 때문입니다. 두 입력 좌표를 a=(a₁,a₂), b=(b₁,b₂)라고 하면 유클리드 거리는 두 좌표 차이의 제곱을 더한 뒤 제곱근을 취합니다.
가까운 순서만 찾을 때에는 제곱근을 생략할 수 있습니다. 9와 25의 순서가 제곱근 3과 5의 순서와 같기 때문입니다. 제곱근은 0 이상에서 단조 증가합니다. 따라서 이 장의 squaredEuclidean은 거리의 제곱을 정확히 계산합니다. 예에서 출력 25는 거리 25칸이라는 뜻이 아니라 5칸을 제곱한 값입니다. 분자·분모를 보존하기 위해 크기 순서를 바꾸는 근사 제곱근을 사용할 필요가 없습니다.
단위를 함께 읽습니다. 두 좌표가 모두 미터라면 거리 제곱의 단위는 m²입니다. 한 좌표는 소득 원, 다른 좌표는 나이 년이라면 제곱을 더하기 전에 두 척도를 어떤 비중으로 비교할지 정해야 합니다. 다차원 계산이 가능하다는 사실이 서로 다른 단위를 아무 근거 없이 더해도 된다는 뜻은 아닙니다.
Imagine two points separated by three horizontal and four vertical steps. Walking along the two directions takes seven steps; the straight segment has length five because 3²+4²=5². Euclidean distance squares each coordinate difference, adds them, and takes a square root.
For ranking neighbours, the square root can be omitted: nine precedes twenty-five just as three precedes five. The square-root function is increasing on nonnegative values. Our squaredEuclidean API therefore computes squared distance exactly. An output of twenty-five means a five-step distance squared, not twenty-five steps. Exact rational ranking needs no approximate square root.
Units still matter. Two metre coordinates give squared-distance units m². Income in currency and age in years need a declared comparison scale before their contributions are added. Being able to calculate with multiple dimensions does not justify adding incompatible units without a rationale.
5. 거리의 조건과 제곱거리의 반례5. Metric conditions and a squared-distance counterexample
수학에서 metric이라고 부르는 거리는 네 가지를 만족합니다. 음수가 아니고, 같은 점 사이에서만 0이며, 두 점의 순서를 바꾸어도 같고, 중간 점을 거쳐 가는 길보다 직접 거리가 길지 않아야 합니다. 마지막 조건이 삼각부등식입니다. 지도에서 A에서 C까지 직접 가는 최단 길이는 A에서 B를 거쳐 C로 가는 특정 길보다 길 수 없다는 생각입니다.
제곱 유클리드 거리는 이 네 조건을 모두 만족하지 않습니다. 수직선의 0·1·2를 보세요. 0과 2의 제곱거리는 4인데, 0과 1 및 1과 2의 제곱거리 합은 1+1=2입니다. 4≤2가 아니므로 삼각부등식이 깨집니다. 그런데 각 새 점에서 이웃을 가까운 순서로 고르는 일에는 여전히 유용합니다. 이웃 순위가 같다는 성질과 모든 거리 공리를 만족한다는 성질을 바꾸어 쓰지 않습니다.
어떤 좌표의 가중치를 0으로 두거나 일정한 좌표를 버리면, 원래 서로 다른 두 벡터의 비교값이 0이 될 수 있습니다. 선택한 좌표만 보는 공간에서는 같은 점이지만 전체 원입력 공간에서는 다른 점입니다. 맨해튼·체비쇼프 거리나 가중 유클리드 제곱비교값에 제곱근을 취한 거리는 남긴 좌표의 거리이며 전체 원공간에서는 준거리(pseudometric)가 될 수 있습니다. 반면 제곱 유클리드 비교값 자체는 삼각부등식을 일반적으로 만족하지 않으므로 보통 준거리라고도 부르지 않습니다. 버린 좌표의 구별 불가능성과 제곱의 삼각부등식 실패를 따로 확인합니다.
4(0−2)2>2(0−1)2+(1−2)2
A mathematical metric is nonnegative, equals zero only for identical points, is symmetric, and satisfies the triangle inequality. The last condition says a direct shortest distance cannot exceed a particular route through an intermediate point.
Squared Euclidean distance does not satisfy all four conditions. On the line at zero, one and two, the squared distance from zero to two is four, but the two squared distances through one sum to two. Thus the triangle inequality fails. Squared distance is nevertheless useful for neighbour ranking. Identical neighbour ordering is different from satisfying every metric axiom.
Setting a coordinate weight to zero or dropping a constant coordinate can give zero dissimilarity to vectors that differ in the original input space. They coincide only after projection. Manhattan, Chebyshev and the square root of weighted squared Euclidean dissimilarity can then be metrics on retained coordinates and pseudometrics on the full space. Squared Euclidean dissimilarity itself still generally fails the triangle inequality, so it is not in general a pseudometric either. Distinguish lost coordinate separation from the separate failure caused by squaring.
4(0−2)2>2(0−1)2+(1−2)2
기초Foundations
6. 길을 따라 걷기와 가장 큰 차이6. Walking along axes and taking the largest difference
맨해튼 거리 L1은 각 좌표 차이의 절댓값을 더합니다. 가로 3·세로 4라면 7입니다. 체비쇼프 거리 L∞는 좌표별 절댓값 가운데 가장 큰 것을 골라 4입니다. 서로 다른 질문에 해당합니다. 한 방향씩 움직이는 총량이 중요한지, 여러 조건 중 가장 큰 불일치가 중요한지에 따라 쓰임이 달라질 수 있습니다.
세 가지 거리가 같은 이웃을 고르리라고 기대할 수는 없습니다. 새 점이 (0,0)이고 후보 A=(3,0), B=(2,2)라고 합시다. 제곱 유클리드는 A가 9, B가 8이라 B가 가깝습니다. 맨해튼은 A가 3, B가 4라 A가 가깝습니다. 체비쇼프는 A가 3, B가 2라 B가 가깝습니다. 이것은 계산 오류가 아니라 무엇을 가까움이라고 정의했는지가 달라진 결과입니다.
어떤 거리를 쓸지 실제 시험 결과를 반복해서 보고 고르면 시험 자료도 선택 과정에 쓰인 것입니다. 먼저 업무·과학적 의미를 따지고, 후보 거리를 비교할 경우 같은 훈련·검증 설계 안에서 비교해야 합니다. 나중의 실제 기업 사례에서는 서로 다른 단위가 만든 순위 변화와 거리 규칙 자체가 만든 변화를 구분합니다.
d1(a,b)=j∑∣aj−bj∣,d∞(a,b)=jmax∣aj−bj∣
Manhattan distance, L 1, adds the absolute differences along each coordinate: three plus four is seven. Chebyshev distance, L∞, takes their maximum, four. These answer different questions, such as total movement along axes versus the largest discrepancy among requirements.
They need not select the same neighbour. From the origin, compare A=(3,0) and B=(2,2). Squared Euclidean values nine and eight favor B. Manhattan values three and four favor A. Chebyshev values three and two favor B. The difference follows from the definition, not an arithmetic error.
Repeatedly choosing a metric by inspecting test performance also uses the test data for selection. First consider its scientific or operational meaning; compare candidate metrics inside the same training and validation design. In the business case we separate changes caused by units from changes caused by the distance definition itself.
d1(a,b)=j∑∣aj−bj∣,d∞(a,b)=jmax∣aj−bj∣
기초Foundations
7. 원·마름모·상자가 뜻하는 근방7. Neighbourhoods shaped like circles, diamonds and boxes
문턱 r보다 가까운 모든 점을 모으면 거리가 만든 근방의 모양을 볼 수 있습니다. 평면에서 유클리드 거리는 원의 안쪽, 맨해튼 거리는 축 방향 꼭짓점을 가진 마름모 안쪽, 체비쇼프 거리는 각 좌표의 차이가 r 이하인 정사각형 안쪽을 고릅니다. 같은 숫자 r을 썼다고 같은 점의 집합이 되지는 않습니다.
제곱거리를 쓰면 반지름도 맞게 변환해야 합니다. 유클리드 반지름 r=2의 원은 제곱거리 4 이하의 점을 포함합니다. 제곱거리 2 이하를 택하면 반지름은 √2라 다른 창입니다. 실습에서 출력하는 kthDissimilarity가 어느 단위인지 확인하세요. 이 장은 고정 반지름 검색과 고정 이웃 수 k 검색을 구별합니다. k가 고정이면 자료가 성긴 곳에서 더 먼 이웃까지 가야 할 수 있습니다.
모든 입력 특성을 동일하게 비교하는 원도 원좌표의 단위가 바뀌면 길쭉한 타원에 해당할 수 있습니다. 스케일링은 숫자를 보기 좋게 줄이는 장식만이 아니라 어떤 방향의 차이를 더 중요하게 보는지 바꾸는 선택입니다. 목표가 예측인지, 사례를 설명하는 검색인지에 따라 의미와 평가 기준을 함께 정해야 합니다.
{x:d2(x,x0)≤r}={x:d2(x,x0)2≤r2}
Collecting all points closer than a radius reveals the geometry. Euclidean neighbourhoods in a plane are disks, Manhattan neighbourhoods are diamonds, and Chebyshev neighbourhoods are axis-aligned squares. Giving their radii the same number does not make the selected point sets identical.
Squared distance requires a corresponding threshold. A Euclidean radius of two means squared distance at most four. Squared distance at most two instead gives radius √2. Read the units of kthDissimilarity. Fixed-radius search differs from fixed-k search: keeping k fixed can require reaching farther in a sparse region.
A circle after scaling can represent an ellipse in the original coordinates. Scaling is therefore more than making displayed numbers smaller: it changes the relative importance of directions. Connect that choice to whether the task is prediction or descriptive retrieval and to how the result will be evaluated.
{x:d2(x,x0)≤r}={x:d2(x,x0)2≤r2}
기초Foundations
8. 실습 A · 계산·단위·거리의 뜻을 확인8. Lab A · Check arithmetic, units and distance meaning
먼저 (0,0)과 (3,4)를 입력하고 제곱 유클리드 25·맨해튼 7·체비쇼프 4를 손으로 예상한 뒤 확인합니다. 제곱 유클리드 출력 25를 실제 거리 25라고 적지 않습니다. 이어 (0,0)에서 A=(3,0), B=(2,2)를 각각 비교하여 거리 선택만으로 첫째 이웃이 바뀌는지 확인하세요. 아직 어느 후보의 y도 보지 않고 하는 계산입니다.
단위 실험에서는 새 점 (0,0), A=(1,100), B=(2,0)을 가정합니다. 원척도 제곱거리는 10001과 4라 B가 가깝습니다. 두 번째 좌표의 기준 척도를 100으로 두면 A의 비교값은 1²+(100/100)²=2, B는 2²=4여서 A가 가까워집니다. 이것은 답이 저절로 더 좋아졌다는 말이 아니라 두 입력의 상대 비중을 바꾼 결과입니다.
마지막에는 한 좌표 가중치를 0으로 두고, 그 좌표만 다른 두 점의 비교값이 0이 되는지 보세요. 출력의 metric 여부·정확값·단위를 함께 설명합니다. 직접 입력한 척도는 가정한 값입니다. 이후 실습의 훈련 전용 range·variance는 실제 훈련 행에서 계산하는 별도의 절차이며, 새 시험 행을 미리 포함해 그 값을 계산하지 않습니다.
Enter the origin and (3,4), predicting squared Euclidean twenty-five, Manhattan seven and Chebyshev four before running. Do not label twenty-five an ordinary Euclidean distance. Next compare A=(3,0) and B=(2,2) from the origin and see whether changing only the metric changes the nearest point, without examining either outcome.
For a units experiment, assume A=(1,100), B=(2,0) and a query at the origin. Raw squared distances 10001 and four favor B. Giving the second coordinate scale one hundred changes A to two and B to four, favoring A. This changes relative feature importance; it does not establish improved predictive performance.
Set one coordinate weight to zero and inspect whether two points differing only there now have dissimilarity zero. Explain the metric flag, exact value and units together. User-entered scales are assumptions. Later range and variance scaling are learned from training records, with held-out records excluded from that fitting step.
학부Undergraduate
9. 가까운 순서에서 k번째를 찾는다9. Find the kth record in proximity order
새 점 x₀=0과 훈련 점수 −3,−2,−1,1,2,3을 생각합시다. 거리는 3,2,1,1,2,3입니다. 가까운 순서로 정렬하면 거리 1인 두 행, 거리 2인 두 행, 거리 3인 두 행이 나옵니다. k는 결과가 큰 행을 몇 개 택할지 정하는 수가 아니라 이 순서의 경계를 정하는 양의 정수입니다. 이 장에서 k는 원행 수를 셉니다. 한 행의 관찰 가중치가 10이라고 열 명의 별도 이웃으로 복제하지 않습니다.
k=3이면 세 번째 행의 거리는 2입니다. 그런데 그 거리에는 두 행이 있습니다. 여기서 정확히 세 행만 남길지, 같은 거리인 행을 모두 남길지 선택해야 합니다. 먼저 경계 거리와 동률 집합을 정하고 그 규칙을 공개합니다. 자료가 대칭적이거나 점수가 정수일수록 이런 상황은 드물지 않습니다. 소수 표시에 나타난 동률과 정확한 값의 동률도 다릅니다.
거리 제곱을 썼다면 경계 값은 4입니다. 그 값에 제곱근을 취해 반지름 2라고 설명할 수 있지만, 순위는 처음부터 정확한 거리 제곱으로 정할 수 있습니다. 이웃 표에는 선택된 원행·원입력·비교값을 함께 보여 줍니다. 누가 답에 들어왔는지 모르는 채 최종 평균만 복사하지 않습니다.
d(1)≤⋯≤d(n),tk=d(k),Nkall(x0)={i:di≤tk}
From a query at zero, training scores −3,−2,−1,1,2,3 have distances 3,2,1,1,2,3. Sorting gives two records at each of distances one, two and three. The positive integer k sets a boundary in this proximity order; it does not select the largest outcomes. Here k counts rows, not replicated units of sample weight.
For k=3, the third distance is two, but two rows share that boundary. A rule must choose between exactly three rows and including the complete tie. Integer scores and symmetric arrangements make ties common. Ties in rounded display values also differ from exact ties.
With squared distances, the boundary is four. It corresponds to radius two, but ranking needs no approximate square root. The neighbour table retains source rows, original predictors and exact dissimilarities so a final average can be traced to its comparisons.
d(1)≤⋯≤d(n),tk=d(k),Nkall(x0)={i:di≤tk}
학부Undergraduate
10. 같은 거리의 행을 모두 포함하는 규칙10. Include every row tied at the kth distance
이 장의 기본 ties=include는 k번째와 같은 거리인 행을 모두 포함합니다. 앞의 대칭 점수에서 k=3이면 −2,−1,1,2의 네 행이 선택됩니다. 요청한 k는 3이지만 실제 사용 행은 4개입니다. 두 숫자를 함께 보고해야 “세 이웃 평균”이라고 쓰고 네 행을 몰래 쓰는 혼동을 피할 수 있습니다.
관측 결과가 각각 6,8,12,14라면 이 네 행의 같은 무게 평균은 10입니다. 거리가 같은 두 행 중 결과가 낮은 행을 빼면 평균을 의도적으로 바꿀 수 있지만, 그것은 공개한 이웃 규칙이 아닙니다. 동률 판단은 입력과 거리로 끝내고 결과를 보고 결정하지 않습니다. 입력 순서를 바꾸어도 all-tie 집합과 정확한 가중평균은 유지됩니다.
동률 전체 포함이 모든 연구에 유일한 정답은 아닙니다. 정확히 k개를 요구하는 시스템도 있을 수 있습니다. 중요한 것은 경계 동률이 실제 분모를 어떻게 바꾸는지 설명하고 구현과 맞추는 것입니다. 가중치를 바꿀 때도 이웃을 고르는 거리와 선택 후 결과를 모으는 무게를 따로 표시합니다.
Our default ties=include keeps every record at the kth dissimilarity. For the symmetric example, k=3 selects four scores: −2,−1,1,2. Requested k and actual selected count must both be reported. Otherwise a description of three neighbours can conceal a four-row calculation.
With outcomes 6,8,12,14, their equal-weight average is ten. Dropping a tied row because of its outcome could deliberately alter the answer, but would violate the declared rule. Resolve membership from inputs and distance alone. Reordering rows leaves the all-tie set and its exact weighted mean unchanged.
Including all ties is not the only possible convention. Some systems require exactly k records. What matters is stating how ties affect the denominator and implementing that statement. Also distinguish distances that select neighbours from weights that subsequently combine their outcomes.
학부Undergraduate
11. 정확히 k개를 남기면 원순서가 영향을 줄 수 있다11. Exact-k selection can depend on source order
ties=stable은 가까운 순서를 먼저 정하고 같은 거리끼리는 원래 입력 순서를 유지하여 정확히 k행을 남깁니다. 새 점 0, 두 훈련 점 −1과 1, 결과 0과 10, k=1이라면 먼저 놓인 행이 예측을 정합니다. −1을 먼저 쓰면 0, 1을 먼저 쓰면 10입니다. 거리만으로는 어느 쪽을 먼저 택할 이유가 없는데 파일 순서가 답을 바꾼 것입니다.
기본 전체 동률 규칙은 이 둘을 함께 써서 5를 예측합니다. stable을 쓴다면 이런 경계의 민감도를 별도로 확인해야 합니다. 단, 같은 거리의 행이 있다고 언제나 순서가 답을 바꾸는 것은 아닙니다. k가 커서 그 동률 집합이 통째로 들어오면 분모도 답도 그대로일 수 있습니다. 실습의 순서 민감도 표지는 경계 동률 중 일부만 잘릴 수 있을 때 켜집니다.
원행 순서를 결과 크기순으로 미리 정렬하고 stable을 쓰면, 겉으로는 단순한 순서 규칙이어도 결과 정보가 선택에 스며들 수 있습니다. 예측 전의 안정적인 식별 순서나 명시적 무작위화 규약을 고민할 수 있지만, 어떤 방식을 택했는지 남겨야 합니다. 이 장의 정확 계산은 임의 난수로 동률을 감추지 않습니다.
The stable rule retains original input order among equal distances and then keeps exactly k rows. At query zero, let two records have scores −1 and one and outcomes zero and ten. With k=1, placing the left record first predicts zero; reversing their order predicts ten. File order, rather than proximity, determines the answer.
Including all ties instead predicts five. Under stable selection, inspect this boundary sensitivity explicitly. The presence of any tie is not sufficient to create sensitivity: a larger k might include the entire tied group. Our flag identifies a boundary group that can be partially excluded.
Sorting source rows by outcome before applying stable ties can let answer information enter membership. A stable identifier rule or a declared random convention could be considered, but its choice must be recorded. This exact educational engine does not conceal a tie behind an unreported random draw.
학부Undergraduate
12. 거리 0이어도 결과가 꼭 같지는 않다12. Zero distance need not imply equal outcomes
같은 입력 x=0인 두 실제 기록이 있다고 가정합시다. 한 결과는 2, 다른 결과는 8입니다. 둘의 거리는 0이지만 같은 사람이나 같은 관측이라는 뜻은 아닙니다. 우리가 고른 입력 열에서만 구별되지 않을 수 있습니다. 입력을 더 자세히 기록하지 않았거나, 측정 오차·관측 잡음·숨은 특성이 있을 수 있지만 두 결과만으로 그 원인을 확정할 수는 없습니다.
새 입력도 0이고 k=1, 전체 동률 포함이라면 두 행을 모두 써서 5를 예측합니다. 결과가 0·1인 이진 분류라면 같은 무게의 국소 비율은 1/2입니다. 입력이 같다는 이유로 “정답을 알아냈으니 반드시 2”라고 정하지 않습니다. 분류의 확률 추정과 하나의 행동 선택도 다릅니다. 확률 1/2에서 어느 행동을 택할지는 동률 규칙·오류 비용에 달린 별도 결정입니다.
역거리 무게에서는 1/0을 계산해서 무한대를 평균하지 않습니다. 선택된 이웃 중 정확한 0거리 행이 있으면 그 행들만 남겨 관찰 무게로 정규화합니다. 아주 작지만 0이 아닌 거리는 이 경우와 구별합니다. 이 규약을 과학적 사실이나 유일한 확률모형의 결론으로 부르지 않고, 계산을 정의하는 공개 규칙으로 설명합니다.
Suppose two records share input zero but have outcomes two and eight. Zero distance does not establish that they are the same person or observation. They may simply be indistinguishable in the selected features. Omitted characteristics, noise or recording error are possible explanations, not conclusions established by these two values.
At a query of zero, k=1 with all ties includes both and predicts five. For equally weighted binary outcomes zero and one, the local class proportion is one half. Identical features do not reveal one certain outcome. Estimating a probability also differs from choosing an action, which depends on costs and a declared action-tie rule.
Inverse-distance weighting must not form a mean of infinities from division by zero. If selected neighbours contain exact zero distances, our inverse-square rule uses only those zero-distance rows and normalizes their observation weights. A tiny nonzero distance remains different. This is a disclosed convention defining the calculation, not a unique law of probability.
학부Undergraduate
13. 빠진 값과 가중치를 먼저 확인한다13. Check missing values and weights before selection
입력에 빈칸이 있는 행은 이 장의 거리 계산에 사용하지 않습니다. 좌표 하나가 없으면 그 차원을 0으로 대체하거나, 남은 좌표 수로 나누어 몰래 다른 거리를 만드는 대신 입력 불완전으로 표시합니다. 새 대상의 입력이 불완전할 때도 예측을 0으로 채우지 않고 미정의로 돌려줍니다. 실제 업무에서 대치법을 쓸 수 있지만 대치법의 학습·검증은 별도의 선택입니다.
관찰 가중치가 0인 행은 파일에 남아도 이웃 후보와 평균 분모에서 빠집니다. 음수 가중치는 허용하지 않습니다. 양의 가중치는 원행 하나의 기여를 바꾸며 k가 세는 원행 수와는 다릅니다. 설문 가중치·분석 무게·실제 반복 빈도를 모두 사람 수라고 이름 붙이지 않습니다. 실제 개인 사례는 여기서 분석 무게 1을 사용하고 원 NLS 표본 가중치가 존재함도 별도로 남깁니다.
개인 실습은 원본 3613행을 모두 보존하지만 공개한 위치 규칙으로 240행을 골라 180훈련·60시험으로 나눕니다. 훈련 결과와 입력이 함께 완전한 행은 145개, 시험 완전 행은 52개입니다. 따라서 180·145를 바꾸어 쓰면 안 됩니다. 기하학적 검색은 결과가 없어도 입력이 있으면 가능하지만, 임금 평균을 빌리는 예측은 결과가 있는 훈련 행만 씁니다.
A row with a missing coordinate is excluded from this chapter’s distance frame. We do not fill it with zero or silently calculate a different distance over fewer coordinates. An incomplete query returns an undefined prediction rather than zero. Imputation can be useful in practice, but its fitting and validation would be an additional modeling choice.
A zero-weight row remains in lineage while contributing neither a neighbour candidate nor denominator mass; negative weights are rejected. Positive observation weights change contributions but not the number of rows counted by k. Survey weights, analysis weights and replication frequencies are not interchangeable counts of people. The individual exercise uses unit analysis weights while retaining the original NLS sampling-weight field.
The individual bundle preserves all 3,613 source rows and selects 240 positions under a declared rule, assigning 180 to training and sixty to testing. Jointly complete outcomes and predictors leave 145 training and 52 test records. Geometry can use an input-complete row without its wage; predicting wages requires labeled training records. These counts must not be interchanged.
학부Undergraduate
14. 단위를 바꾸면서 비교 규칙도 지킨다14. Preserve the comparison rule when changing units
키를 미터에서 센티미터로 바꾸면 같은 사람의 숫자가 100배가 됩니다. 나이는 그대로 년으로 적는다면 원척도 제곱거리에서 키의 기여는 10000배가 됩니다. 사람은 바뀌지 않았는데 가까운 순서가 바뀔 수 있습니다. “두 특성을 썼다”라는 설명만으로는 비교를 재현할 수 없는 이유입니다. 각 특성의 단위와 척도를 함께 기록해야 합니다.
비교값이 Σwⱼ[(aⱼ−bⱼ)/sⱼ]²라면 한 좌표를 100배 할 때 그 sⱼ도 100배 하면 그 좌표의 정규화 차이는 유지됩니다. 새 단위 때문에 임의로 이웃을 바꾼 것이 아니라 같은 기하를 다른 숫자로 표현한 것입니다. 반대로 s를 그대로 두면 같은 알고리즘 이름 아래 다른 비중을 준 셈입니다. 척도를 바꾸는 것과 관계를 발견하는 것은 다릅니다.
GDP·실업률·기대수명을 다루는 국가 사례에서는 금액·%·년의 단위를 명시합니다. 기업 사례의 통화 초와 횟수도 숫자 크기가 다릅니다. 표준화가 무조건 옳은 것은 아니며, 작은 변동 범위의 잡음 좌표를 과장할 수도 있습니다. 업무상 의미가 있는 척도와 훈련 자료에서 학습한 척도를 후보로 두고, 성능은 독립적인 검증 규약으로 판단합니다.
100sj100aj−100bj=sjaj−bj
Changing height from metres to centimetres multiplies its numerical values by one hundred. If age remains in years, height’s raw squared-distance contribution increases ten thousandfold. The people did not change, yet neighbour order can change. Report feature units and scales, not merely the number of inputs.
In Σwⱼ[(aⱼ−bⱼ)/sⱼ]², multiplying one coordinate and its corresponding sⱼ by one hundred preserves the normalized difference. That expresses the same geometry in new units. Leaving its scale unchanged assigns a different relative importance despite retaining the same algorithm name.
The country case distinguishes currency, percentage points and years; telecom seconds and counts also differ numerically. Scaling is not automatically beneficial: it can amplify a nearly constant noisy feature. Consider substantive scales and training-fitted scales as explicit candidates, assessed under a separate validation protocol.
100sj100aj−100bj=sjaj−bj
학부Undergraduate
15. 척도는 훈련 자료로만 학습한다15. Learn scales only from training records
range 스케일링은 각 입력의 훈련 최댓값−최솟값을 씁니다. variance 스케일링은 관찰 무게로 계산한 훈련 평균과 모집단식 분산을 씁니다. 분모는 무게 합이지 “표본 수−1”이 아닙니다. 분산으로 정규화한 제곱 유클리드 거리는 각 차이 제곱을 그 분산으로 나누므로, 표준편차의 제곱근을 근사해 순위가 바뀌는 문제를 피할 수 있습니다. 맨해튼에 같은 분산 분모를 그대로 쓰는 절차와 혼동하지 않습니다.
훈련 값이 0과 2라면 평균은 1, range는 2, 모집단식 분산은 1입니다. 새 시험 값 100을 평가할 때도 훈련 척도는 그대로입니다. 시험 값을 끼워 넣으면 range는 100, 평균은 34, 분산은 6536/3으로 바뀝니다. 시험 결과 y를 보지 않았더라도 시험 입력을 이용해 전처리를 학습한 셈입니다. 이 장은 일반적인 새 대상 예측을 연습하므로 그 입력도 훈련 척도에 넣지 않습니다.
훈련 값이 모두 같은 좌표는 range·분산이 0입니다. 0으로 나누지 않고 그 좌표를 버렸다고 표시합니다. 새 입력이 그 상수와 다를 수 있다는 사실도 표시합니다. 모든 좌표를 버리면 모든 훈련 행이 같은 거리 0이어서 기본 동률 규칙은 모두를 포함합니다. 이것은 새 값을 0으로 예측한다는 뜻이 아니라, 남은 입력 정보 없이 훈련 결과를 모으게 되었다는 뜻입니다.
Range scaling uses the training maximum minus minimum. Variance scaling uses the training weighted mean and population-form variance, dividing by total weight rather than sample-size minus one. Squared standardized Euclidean distance divides each squared difference by that variance, avoiding an approximate square root. Using the same variance denominator in a Manhattan distance is a different procedure, which this API does not claim to implement.
Training values zero and two have mean one, range two and population variance one. A test value of one hundred does not alter those fitted scales. Including it would change the range to one hundred, mean to thirty-four and variance to 6536/3. Even without seeing test labels, fitting preprocessing to test inputs changes the evaluation protocol. Our ordinary new-unit prediction exercise excludes them.
A constant training coordinate has zero range and variance. It is dropped and disclosed rather than divided by zero; a query outside its constant value is also flagged. If every coordinate drops, all training distances become zero and the default tie rule includes all rows. The prediction is then a training-outcome summary without retained input information, not automatically zero.
16. 실습 B · 동률·원행·훈련 척도16. Lab B · Ties, source rows and trained scales
입력 −1,1,2와 결과 0,10,20을 가정하고 새 점 0, k=1을 사용합니다. 기본 전체 동률에서는 처음 두 행이 함께 선택됩니다. predict로 옮기면 평균은 5입니다. stable에서는 처음 행만 선택되어 0입니다. 두 행의 순서를 바꾸어 10이 되는지 확인하고, 왜 기본 규칙은 여전히 5인지 원행 표로 설명합니다. 서로 다른 이름을 주어 어떤 행이 바뀌었는지 추적하세요.
이어서 같은 입력에 결과가 없는 행 하나와 무게 0인 행 하나를 추가합니다. 순수 검색과 예측의 후보 분모를 비교하고, 빠진 이유가 화면에 남는지 확인합니다. k를 이용 가능한 원행 수보다 크게 입력하면 값을 몰래 줄여 계산하지 않고 오류를 알려 줍니다. 오류 뒤에 예전 정상 숫자가 새 답처럼 남아 있지 않아야 합니다.
두 입력을 가진 단위 예로 넘어가 none·range·variance를 비교하세요. 척도 표의 훈련 행 수, 각 입력 최솟값·최댓값·평균·분산과 버린 좌표를 먼저 확인합니다. 그 뒤에 새 점을 멀리 옮겨도 훈련 척도가 바뀌지 않는지 보세요. 이 과정을 한 문장으로 설명할 수 있어야 실제 자료에서 “가까운 사람”이라는 말을 무엇을 기준으로 썼는지 공개할 수 있습니다.
Use assumed inputs −1,1,2, outcomes 0,10,20, a query at zero and k=1. The default tie rule selects both first records and predict averages them to five. Stable selects the first only and gives zero. Reverse their order, check the result ten, and explain from source rows why the all-tie prediction remains five.
Add one input-complete row with a missing outcome and another with weight zero. Compare the denominators for pure search and prediction, retaining each exclusion reason. A k larger than the available row count is rejected rather than silently reduced. A failed calculation must not leave an earlier number appearing as the new result.
For two features, compare none, range and variance. First inspect training counts, coordinate minima, maxima, means, variances and dropped dimensions. Move the query far away and check that training scales remain fixed. Explaining this process makes the phrase similar people or similar records reproducible.
학부Undergraduate
17. 회귀는 가까운 결과를 평균한다17. Regression averages nearby outcomes
회귀 문제에서는 결과가 임금·판매량처럼 수로 측정됩니다. 선택된 이웃 집합을 N이라고 하고 같은 무게를 주면 예측은 이웃 결과의 합을 이웃 수로 나눈 값입니다. x₀=0에서 −1·1의 결과가 8·12라면 예측은 10입니다. 원래 입력이 0이라는 사실 때문에 결과도 0이어야 하는 것은 아닙니다. 입력 공간에서의 위치와 결과 변수의 단위는 별개입니다.
이웃 평균을 확률로 읽지 않습니다. 10이라는 임금 예측은 10% 성공 확률이 아니며, 같은 입력을 가진 모든 사람의 실제 임금이 반드시 10이라는 뜻도 아닙니다. 주어진 훈련 표와 정한 규칙에서 만든 수입니다. 모집단의 조건부 평균에 가깝기를 바라지만 그 성질에는 표본·근방·관계의 매끄러움과 같은 조건이 더 필요합니다.
좋은 예측이 모든 이웃의 결과를 정확히 맞혀야 하는 것은 아닙니다. 결과 8·12를 각각 완벽하게 외우는 규칙과, 새 대상에게 평균 10을 주는 규칙은 평가 대상이 다릅니다. 이 장은 선택된 원행마다 평균에 얼마를 기여했는지 남깁니다. 평균 하나가 왜 나왔는지와 그 평균이 새 대상에게 유용한지를 따로 확인합니다.
m(x0)=∣N(x0)∣1i∈N(x0)∑yi
A regression outcome is numerical, such as earnings or sales. Giving equal weights to a selected neighbour set N predicts its outcome sum divided by its size. At a query of zero, neighbours −1 and one with outcomes eight and twelve predict ten. An input coordinate of zero does not imply an outcome of zero; their units and roles differ.
A numerical mean is not a probability. Predicted earnings ten do not mean a ten-percent success probability, or that every person with those inputs earns exactly ten. It is the output of a rule on a training table. Approximating a population conditional mean needs further sampling and local smoothness conditions.
Memorizing both outcomes eight and twelve differs from predicting a new outcome by ten. We retain the contribution of each neighbour to make the calculation explainable, while evaluating usefulness on different records. Explaining an average does not itself establish predictive accuracy.
m(x0)=∣N(x0)∣1i∈N(x0)∑yi
학부Undergraduate
18. 왜 평균일까 · 제곱손실에서 유도18. Why the mean? Derive it from squared loss
평균은 편해서 임의로 고른 수만은 아닙니다. 이웃의 결과를 상수 a 하나로 대표하고, 틀린 양의 제곱을 더해 가장 작게 만드는 문제를 생각합시다. 결과가 2와 8이라면 (2−a)²+(8−a)²입니다. a=5일 때 두 오차가 −3·3으로 제곱합 18이며, a=2이면 0+36=36이라 더 큽니다.
미분으로 모든 a를 비교할 수 있습니다. 도함수는 2(a−2)+2(a−8)=4a−20이고 0이 되는 a는 5입니다. 이차 도함수 4가 양수라 유일한 최소입니다. 양의 무게 wᵢ가 있다면 도함수를 0으로 놓아 a=Σwᵢyᵢ/Σwᵢ를 얻습니다. 무게 합이 0이면 이 식을 쓰지 않습니다. 이웃의 결과를 상수로 근사하는 국소 제곱손실 최소화라는 뜻입니다.
손실을 바꾸면 대표값도 바뀔 수 있습니다. 절대오차를 최소화하는 값은 중앙값 집합과 연결됩니다. 이 엔진의 회귀 예측은 가중평균이며, 평가 점수로 MAE를 선택했다고 예측 방법이 자동으로 중앙값으로 바뀌지는 않습니다. 예측 규칙과 성능을 재는 손실을 별도로 적어야 계산을 재현할 수 있습니다.
The mean is not merely a convenient guess. Represent neighbour outcomes by one constant a and minimize their sum of squared errors. For outcomes two and eight the objective is (2−a)²+(8−a)². At a=5 it equals eighteen, whereas a=2 gives thirty-six.
Differentiating gives 4 a−20, which vanishes at five; the positive second derivative four establishes a unique minimum. With positive weights, the same argument gives Σwᵢyᵢ/Σwᵢ. The denominator must be positive. This is a constant approximation fitted locally under squared loss.
Changing the fitting loss can change the representative: absolute loss leads to medians. Our regression predictor remains a weighted mean even when its evaluation score is MAE. Selecting an evaluation score does not silently change the prediction rule. Document the rule and score separately.
19. 이웃 수와 평균의 무게는 다르다19. Neighbour count differs from averaging weight
새 점 양쪽의 같은 거리에서 두 이웃 결과가 2·8이고 관찰 무게가 1/3·2/3이라고 합시다. 기본 동률 포함에서 둘 다 선택됩니다. 정규화한 무게 합은 1이므로 예측은 (1/3)2+(2/3)8=6입니다. 같은 무게 평균 5와 다른 이유는 이웃을 바꾸었기 때문이 아니라 그 둘의 상대 기여를 바꾸었기 때문입니다.
관찰 무게는 각 행이 가진 분석상의 기여이고, 역거리 무게는 새 점과의 관계에 따라 달라지는 무게입니다. 두 무게를 함께 쓰면 곱한 뒤 전체 합으로 정규화합니다. 새 점이 바뀌면 거리 무게는 달라져도 원행의 관찰 무게는 그대로입니다. 반환 표는 원행 무게·거리·정규화 무게를 구별하여 보여 줍니다.
모든 관찰 무게를 같은 양수 배로 바꾸면 평균은 같습니다. 분자와 분모가 함께 같은 배로 바뀌기 때문입니다. 한 행만 0으로 만들면 후보 집합도 바뀔 수 있어 같은 변경이 아닙니다. 또한 조사 설계의 가중치를 무시한 이 사례의 단위 무게 예측을, 그 조사 모집단 전체에 대한 설계 불편 추정량이라고 부르지 않습니다.
Two equally distant neighbours have outcomes two and eight and observation weights 1/3 and 2/3. Both enter under the default tie rule, and their weighted prediction is six rather than five. The neighbour set stayed fixed; relative contributions changed.
Observation weight belongs to a training record, while distance weight depends on its relation to the query. If both are used, multiply and normalize them. Moving the query changes distance weights without changing recorded observation weights. The returned table separates source weight, dissimilarity and normalized contribution.
Multiplying every observation weight by the same positive constant leaves the mean unchanged because numerator and denominator scale together. Setting one row’s weight to zero can instead alter the candidate set. Unit-weight predictions on survey records are not automatically design-unbiased population estimates.
20. 분류는 가까운 집단의 비율부터 구한다20. Classification starts from local class proportions
결과가 이탈·비이탈처럼 범주이면 숫자 평균을 그대로 임금 예측처럼 읽지 않습니다. 선택된 이웃의 정규화 무게 가운데 각 범주가 차지하는 합을 구합니다. 같은 무게의 세 이웃 결과가 비이탈·이탈·이탈이면 이탈 비율은 2/3, 비이탈 비율은 1/3입니다. 여러 범주를 쓰더라도 비율은 음수가 아니고 모두 합해 1이어야 합니다.
이 비율은 훈련 표가 준 국소 경험 비율입니다. 실제 새 대상이 이탈할 참확률과 항상 같거나 확률 보정이 완벽하다고 보장되지 않습니다. k가 작으면 0이나 1 같은 극단적 비율이 쉽게 나올 수 있고, 잘못 확신한 확률의 로그손실은 클 수 있습니다. ML05에서 배운 확률·보정·평가의 구분이 이웃 모형에도 그대로 필요합니다.
하나의 범주를 답해야 할 때 기본 예측은 비율이 가장 큰 범주를 고릅니다. 최댓값이 같으면 선언한 범주 순서의 첫 범주를 고릅니다. 그 선택은 동률 비율을 바꾸지 않습니다. 범주 이름을 정렬하거나 원행 순서를 바꾸어 낮은 오류 비용의 선택을 구현한 것처럼 꾸미지 않습니다. 비용을 고려한 행동은 다음 절의 별도 문제입니다.
When outcomes are categories such as churn and non-churn, sum the normalized neighbour weights belonging to each class. Three equally weighted labels non-churn, churn, churn give proportions one third and two thirds. With more classes, probabilities remain nonnegative and sum to one.
These are local empirical proportions, not guaranteed true probabilities for a new person. Small k can produce extreme zero or one predictions, with severe log loss when an apparently certain prediction fails. ML05’s distinctions among probability estimation, calibration and evaluation still apply.
For a single predicted class, the default chooses a largest proportion. Equal maxima are resolved by the first declared class, without changing the probability vector. Neither alphabetic labels nor file order implement a cost-sensitive policy by themselves. That requires a separate decision rule.
21. 확률과 행동·비용은 따로 정한다21. Probabilities, actions and costs are separate
이탈 확률을 p라고 예측했을 때 반드시 p≥1/2에서 연락해야 하는 것은 아닙니다. 놓친 이탈의 비용과 불필요한 연락의 비용이 다를 수 있기 때문입니다. 설명용으로 거짓 양성 비용 1, 거짓 음성 비용 4, 맞는 결정의 비용 0을 가정합시다. 양성으로 결정할 예상 비용은 1−p, 음성으로 결정할 비용은 4p입니다. 양성을 택할 조건은 p≥1/5입니다.
이 비용은 실제 회사의 회계자료에서 얻은 수치가 아니라 가정입니다. 연락이 이탈을 줄이는 인과효과가 있다는 가정도 여기서 관측한 것이 아닙니다. 실제 개입을 결정하려면 연락 비용·효과·자원 제약·고객 경험을 따로 검토해야 합니다. 예측 확률을 안다는 것과 그 사람에게 무엇을 하면 결과가 좋아지는지 아는 것은 다릅니다.
이 장의 기본 분류 행동은 동일한 0–1 오류 비용 아래 최다 비율을 고르는 규칙입니다. 비용 민감 행동을 계산한 것처럼 표시하지 않습니다. 확률 성능은 Brier 점수도 봅니다. 이 장은 범주별 제곱오차 합의 절반을 사용하므로 이진 분류에서는 (p−y)²와 같습니다. 예측 p=1/2이고 실제 이탈이면 Brier는 1/4입니다. 어떤 점수 정의를 쓰는지 먼저 맞추고 모형을 비교하세요.
1−p≤4p⟺p≥51,LBrier=21c∑(pc−1{y=c})2
An estimated churn probability p does not require contacting people only above one half. Missing a churner and making an unnecessary contact may have different costs. Assume false-positive cost one, false-negative cost four and zero cost for correct actions. Expected costs are 1−p for a positive action and 4 p for a negative action, giving threshold one fifth.
Those costs are assumed, not obtained from company accounts. Nor have we observed a causal retention effect from contacting a customer. Intervention decisions require separate evidence about effects, resources, contact costs and customer experience. Predicting who will churn does not identify which action would help them.
Our default class action maximizes estimated class probability under equal 0–1 error costs. It does not implement this cost-sensitive policy. Probability evaluation also uses Brier loss, defined here as half the sum of squared class-probability errors. For binary outcomes it equals (p−y)²; p=1/2 with an actual positive gives one quarter. Match score definitions before comparing models.
1−p≤4p⟺p≥51,LBrier=21c∑(pc−1{y=c})2
학부Undergraduate
22. 가까운 이웃에 더 큰 무게를 준다22. Give closer neighbours more voting weight
가까운 행을 더 믿고 싶다면 결과를 모을 때 거리에 따라 무게를 줄 수 있습니다. 이 장의 선택지는 유클리드 거리의 제곱에 역수를 취하는 inverseSquaredEuclidean입니다. 실제 거리 1과 2의 이웃이면 무게는 1과 1/4입니다. 결과가 0과 10이라면 정규화 무게는 4/5·1/5이고 예측은 2입니다. 균등 평균 5와 비교하여 무엇이 바뀌었는지 설명할 수 있습니다.
엔진이 이미 제곱거리 s를 계산했으므로 무게는 1/s입니다. 1/s²를 다시 계산하면 거리의 네제곱 역수를 쓴 다른 규칙입니다. 맨해튼 거리의 역수도 같은 이름의 규칙이 아닙니다. 이 장은 이런 혼동을 막기 위해 이 무게를 제곱 유클리드와 함께 사용할 때만 허용합니다. 어떤 무게가 가장 좋은지는 별도의 검증 문제입니다.
선택 이웃에 거리 0이 있으면 0거리 행들만 관찰 무게로 평균합니다. x=0의 결과 2·8, x=1의 결과 20에서 새 점 0이면 기본 동률 규칙은 0거리 두 행을 함께 사용하여 5를 줍니다. 양의 거리가 화면에서 0으로 반올림되어 보여도 같은 처리를 하지 않습니다. 동률·0거리·가중치 규약을 알고 있어야 이웃 기여 표를 올바르게 읽을 수 있습니다.
To emphasize closer records, the chapter offers inverseSquaredEuclidean voting. Neighbours at Euclidean distances one and two receive raw weights one and one quarter. With outcomes zero and ten, normalized weights are four fifths and one fifth, giving prediction two instead of the uniform mean five.
Because the engine already computes squared distance s, its weight is 1/s. Using 1/s² would instead weight by inverse fourth power of distance. Inverting a Manhattan distance is another rule. To prevent that ambiguity, this voting option is accepted only with squared Euclidean dissimilarity. Its predictive usefulness still needs validation.
If selected neighbours include exact-zero distances, use only those rows with their observation weights. Two records at x=0 with outcomes two and eight predict five at zero, even if another record at x=1 has outcome twenty. A tiny positive distance rounded to zero in display does not trigger this rule. Read ties, zero distances and contributions together.
23. 평균을 빌려도 예측 곡선은 뛰어도 된다23. Averaging can still produce a discontinuous predictor
훈련 점이 x=1·3, 결과가 0·10이고 k=1이라고 합시다. 새 점이 2보다 조금 작으면 첫 점이 가깝고 예측은 0입니다. 2보다 조금 크면 둘째 점이 가깝고 예측은 10입니다. 정확히 2에서는 전체 동률 포함으로 5입니다. 이것은 평균 계산이 잘못된 것이 아니라 선택 집합이 경계에서 바뀌기 때문입니다.
균등 kNN 회귀는 한 근방 안에서 결과를 상수로 대표하는 국소 상수 방법입니다. 넓은 구간에서 하나의 기울기를 추정하는 선형 회귀와 같지 않습니다. 0에서 10으로 뛰는 표본 예측 함수를 관측 모집단의 평균도 실제로 불연속이라는 증거로 읽지 않습니다. 추정 규칙의 모양과 자료 생성 관계의 모양은 별개입니다.
k를 늘리거나 거리 무게를 쓰면 어떤 부분의 변화가 완만해질 수 있지만 언제나 전체 함수가 연속이 되거나 좋아진다고 보장되지는 않습니다. 이웃 경계·0거리·동률 처리와 훈련 분포가 함께 작용합니다. 함수의 모양을 보면서도 새 시험 사례의 오차와 비교하세요. 미분이 존재하지 않는 표본 경계에서 기울기를 무조건 계산하려 하지 않습니다.
Let training inputs one and three have outcomes zero and ten, with k=1. Queries just below two predict zero; queries just above two predict ten. Exactly at two the all-tie rule predicts five. This follows from a changing neighbour set rather than faulty averaging.
Uniform kNN regression is a local-constant method, not a global linear regression. A discontinuity in its sample prediction function does not establish a discontinuity in the population conditional mean. Separate the shape of the algorithm’s fitted rule from the shape of the data-generating relationship.
Increasing k or using distance weights can smooth some changes, but neither guarantees global continuity or improved accuracy. Boundaries, zeros, ties and training support all matter. Inspect held-out errors along with the curve, and do not assume a derivative exists at every sample-induced boundary.
학부Undergraduate
24. 실습 C · 평균·확률·기여를 함께 읽는다24. Lab C · Read means, probabilities and contributions
회귀 실습에서 가정한 훈련 점수 −3,−2,−1,1,2,3과 결과 4,6,8,12,14,16을 사용합니다. 새 점을 0.6으로 두고 k=1이면 점수 1의 결과 12가 답입니다. k=3에서는 점수 1·2·−1이 선택되어 (12+14+8)/3=34/3입니다. 새 입력을 움직여 어느 원행이 경계를 드나드는지 먼저 보고 평균 변화를 설명하세요.
역제곱 무게를 고를 때에는 각 원행의 거리 제곱·원무게·정규화 무게·예측 기여를 확인합니다. 정규화 무게 합이 1이고 기여 합이 예측과 같은지 손으로 작은 예 하나를 검산합니다. 새 점을 훈련 점과 정확히 일치시키고, 같은 입력에 다른 결과인 행도 추가하여 0거리 규약이 어떻게 작동하는지 보세요.
분류로 바꾸면 결과가 선언한 범주에 속하는지 확인하고, 확률 벡터와 최종 범주를 별도로 읽습니다. 가운데에서 1/2·1/2가 나오는 예를 만든 뒤 범주 순서를 바꾸면 확률은 같고 동률 행동만 달라지는지 살펴보세요. 출력이 1이라고 해서 현실에서 절대 실패하지 않는다고 해석하지 않습니다. 실제 사례의 시험 Brier·오류율과 기준 모형 비교는 별도로 진행합니다.
Use assumed training scores −3,−2,−1,1,2,3 and outcomes 4,6,8,12,14,16. At query 0.6, k=1 selects score one and predicts twelve. With k=3, scores one, two and −1 give prediction 34/3. Move the query and explain changes by inspecting source membership before interpreting the average.
For inverse-square voting, inspect squared distances, raw observation weights, normalized weights and prediction contributions. Verify that normalized weights sum to one and contributions sum to the prediction. Match a training input exactly, then add a different outcome at the same input to examine the exact-zero rule.
For classification, declare class labels and read the probability vector separately from the selected class. Construct equal probabilities, reverse class order and check that only the tied action changes. A reported probability one is not a guarantee of success in reality. Actual held-out Brier and error rates will be compared with baselines later.
학부 심화 · 선택Advanced undergraduate · optional
25. 작은 k와 큰 k는 다른 질문을 한다25. Small and large k ask different questions
k가 작으면 매우 가까운 몇 행의 결과에 답이 민감합니다. 그 행 하나의 측정값이 바뀌면 예측도 크게 바뀔 수 있습니다. 반대로 k가 크면 더 넓은 범위의 결과를 섞습니다. 잡음은 평균으로 줄일 여지가 있지만, 새 점과 관계가 다른 먼 대상도 함께 들어옵니다. 언제나 작을수록 좋다거나 클수록 좋다고 할 수 없습니다.
가장 가까운 한 행의 결과가 우연히 높게 관측되었다면 k=1은 그 값을 그대로 빌릴 수 있습니다. 주변 평균 관계가 빠르게 변하는 곳에서 너무 큰 k를 쓰면 다른 위치의 평균을 섞는 근사 오차가 생길 수 있습니다. 이 두 문제는 무작위 변동과 관계의 국소 근사라는 서로 다른 요인입니다. ML02의 편향·분산을 구체적인 이웃 규칙에 연결해 봅니다.
전체 동률을 포함하면 요청 k가 1이어도 여러 행을 쓰기도 합니다. 따라서 작은 k를 설명할 때 실제 이웃 수와 무게 집중도까지 읽습니다. 서로 다른 n이나 분포의 자료에서 같은 k를 썼다고 같은 반경·같은 복잡도의 비교가 되지는 않습니다. 실제 원입력 거리와 그 안에 남은 자료를 확인해야 합니다.
A small k makes the answer sensitive to a few nearby outcomes. Changing one measured outcome can substantially change the prediction. A larger k mixes information from farther away, potentially averaging noise but also combining units whose mean outcomes differ. Neither direction is universally better.
A one-neighbour prediction can inherit an unusually high noisy outcome. An overly broad neighbourhood can instead mix distinct local relationships. These are different sources of error: random variability and local approximation. This makes ML02’s bias–variance distinction concrete.
With all ties, requested k=1 can still select several rows. Inspect actual counts and weight concentration. The same k across different sample sizes and distributions need not imply the same radius or effective complexity. Read distances and support as well as k.
학부 심화 · 선택Advanced undergraduate · optional
26. 평균 관계의 차이와 잡음을 분리한다26. Separate approximation error from outcome noise
정해진 훈련 입력에서 결과를 Yᵢ=m(xᵢ)+εᵢ라고 씁니다. 설명을 위해 오차의 조건부 평균은 0이고, 오차끼리는 독립이며, 예측 무게 λ는 결과 오차가 아니라 입력으로 정해진다고 가정합시다. 그러면 예측의 조건부 평균은 Σλᵢm(xᵢ)입니다. 새 점의 평균 m(x₀)와 얼마나 다른지가 근사의 편향입니다. 평균 자체가 이웃 안에서 달라질 수 있다는 문제가 여기 남아 있습니다.
같은 가정에서 예측 분산은 Σλᵢ²σᵢ²입니다. 같은 분산 σ²인 m개 이웃을 균등하게 평균하면 σ²/m이 됩니다. 전체 동률로 실제 네 이웃이 선택되었으면 요청 k=3을 무조건 분모로 쓰지 않습니다. 특정 이웃에 무게가 몰리면 제곱 무게 합이 커져 분산 감소가 작을 수 있습니다. 원행 수만으로 독립적인 정보량을 단정하지 않습니다.
새 결과 Y₀를 예측하는 제곱오차에는 새 대상 자신의 잡음도 남습니다. 새 오차가 훈련 오차와 독립이고 평균 0이라고 더 가정하면 MSE는 편향²+예측 분산+새 결과 잡음 분산입니다. 조건부 평균 m(x₀)를 추정하는 MSE와 구별하세요. 반복 고객·같은 국가의 여러 해·같은 가구의 사람들은 오차 독립 가정을 별도로 살펴야 합니다.
At fixed training inputs, write Yᵢ=m(xᵢ)+εᵢ. Assume zero conditional error means, independent errors, and prediction weights determined by inputs rather than outcome noise. The predictor’s conditional mean is Σλᵢm(xᵢ). Its difference from m(x₀) is approximation bias: the mean relationship may vary inside the selected neighbourhood.
Under these assumptions its variance is Σλᵢ²σᵢ². Averaging m independent equal-variance neighbours uniformly gives σ²/m. If all ties turn requested k=3 into four selected neighbours, three is not automatically the denominator. Concentrated weights can reduce noise averaging, and row counts alone do not establish independent information.
Predicting a new outcome Y₀ also retains that unit’s own noise. If its zero-mean error is independent of training errors, prediction MSE includes squared bias, prediction variance and new-outcome noise variance. Estimating m(x₀) has a different target. Repeated customers, country-years or household members need separate dependence assumptions.
27. 자기 자신을 이웃으로 쓰면 쉬워지는 시험27. A point can make training prediction too easy
훈련 행의 입력이 모두 서로 다르고 결과를 완전히 기억한 1NN을 생각합시다. 각 훈련 행을 다시 질의하면 거리 0의 자기 자신을 선택하여 그 결과를 맞힐 수 있습니다. 훈련 제곱오차가 0이라는 사실은 새 사람의 결과를 잘 예측한다는 증거가 아닙니다. 같은 입력에 서로 다른 결과가 반복되면 기본 동률 규칙 때문에 이 훈련 오차조차 반드시 0인 것도 아닙니다.
leave-one-out은 한 행을 예측할 때 그 행 전체를 훈련에서 제외합니다. y만 가리고 그 입력을 전처리 학습이나 0거리 후보에 남겨 두는 것과 다릅니다. 이 장의 제외 ID 규칙을 쓰면 후보와 척도 계산에서 함께 빠집니다. 이 과정을 모든 행에 반복하면 원행마다 훈련 표가 달라집니다. 계산량도 고려해야 합니다.
같은 개인의 반복 측정이 여러 행이면 그 한 행을 뺐다고 독립적인 새 개인 시험이 되지는 않습니다. 가까운 복제·반복 행이 다른 fold에 남을 수 있습니다. 동일 단위·시간·공간의 정보를 알고 있다면 그 구조에 맞는 분할이 필요합니다. 이 장의 원행 위치는 고유한 실제 개인·고객 식별을 복원했다고 주장하는 표지가 아닙니다.
With distinct training inputs, a memorizing one-nearest-neighbour rule can select each record itself at distance zero and reproduce its outcome. Zero training error therefore need not predict performance on new units. Conflicting outcomes at identical inputs can prevent even this zero-error result under the default all-tie rule.
Leave-one-out removes the entire held-out record from training, rather than hiding y while retaining its input for preprocessing or a zero-distance match. Explicit ID exclusion here removes the row from both candidates and fitted scales. Repeating the procedure changes the training table for every query and incurs computation.
For repeated observations of one person, removing one row need not create an independent new-person test. Closely related records may remain in other folds. Use identity, time or spatial structure when known. A retained source-row position is not proof that a unique real-person identifier has been recovered.
학부 심화 · 선택Advanced undergraduate · optional
28. 검증 fold 안에서 척도부터 다시 맞춘다28. Refit preprocessing inside each validation fold
교차검증은 훈련 후보 자료를 여러 묶음(fold)으로 나누어, 한 묶음의 결과를 잠시 숨긴 채 나머지로 그 묶음을 예측하는 절차입니다. 거리 척도를 배우는 단계도 이 나머지 자료에서 해야 합니다. 전체 후보 자료로 range·분산을 한 번 계산하고 fold만 바꾸면, 숨긴 행의 입력이 이미 척도에 반영되어 같은 절차를 검증한 것이 아닙니다.
예를 들어 한 fold의 검증 값이 100이고 나머지 훈련 값이 0·2라면 그 fold의 range는 2입니다. 다음 fold에서는 훈련 구성이 달라져 range가 100이 될 수도 있습니다. 매 fold의 척도가 같아야 올바른 것이 아니라 각 fold의 훈련 자료에만 근거해야 올바른 절차입니다. 실습은 척도 표와 훈련·검증 ID를 함께 반환하여 이를 확인할 수 있게 합니다.
이 설명은 보통의 새 대상 예측 절차를 평가하는 설정입니다. 시험 입력 분포를 미리 활용하는 전이·전도 학습 같은 다른 문제를 연구할 수는 있지만 그 문제와 평가 규약을 명시해야 합니다. 시험 입력을 썼다는 사실을 숨기고 모든 전처리가 훈련 전용이라고 부르면 안 됩니다. 이 장에서는 그 더 복잡한 설정을 구현한 것으로 주장하지 않습니다.
Cross-validation splits a development training set into folds and predicts each held-out fold using its complement. Learned distance scales belong inside that training complement. Fitting ranges or variances once on all development inputs before rotating folds would evaluate a different procedure.
If a validation fold contains value one hundred while its training complement contains zero and two, that fold’s range is two. Another fold can legitimately have range one hundred because its training composition differs. Correctness requires training-only fitting, not identical scales across folds. Returned training IDs, validation IDs and scale tables expose this distinction.
This describes ordinary prediction for new units. Other settings may deliberately use unlabeled target inputs, but their learning problem and evaluation protocol must be explicit. Such use cannot be hidden behind a claim of training-only preprocessing. Our engine does not claim to implement a more general transductive setup.
학부 심화 · 선택Advanced undergraduate · optional
29. 같은 관측과 같은 fold에서 k를 비교한다29. Compare k on the same records and folds
k=1·3·5를 비교한다면 기본 관측 프레임과 fold 배정을 고정합니다. 이웃 수만 바꾸면서 검증 표본까지 바꾸면 오차 차이가 모형 때문인지 사람 구성이 달라졌기 때문인지 구분하기 어렵습니다. 이 장의 validate는 입력·결과·양의 관찰 무게가 있는 완전 프레임을 정한 뒤 모든 후보에 같은 fold를 적용합니다. 어떤 k가 한 fold의 훈련 행 수보다 크면 몰래 그 fold에서만 k를 줄이지 않고 거부합니다.
각 검증 행의 손실에 평가 무게를 곱해 모두 더하고, 평가 무게의 전체 합으로 나눕니다. fold 크기가 다르면 fold 평균들을 다시 단순 평균한 값과 다를 수 있습니다. 개인 사례는 결측 때문에 fold별 완전 행 수가 달라질 수 있으므로 실제 분모를 읽어야 합니다. 가중치 1이면 이것은 모든 평가 가능 행의 평균 손실입니다.
가장 작은 검증 손실의 k를 고르고 정확히 같은 손실이면 더 작은 k를 택한다는 규칙을 명시합니다. 이 동률 규칙은 가장 작은 k가 과학적으로 항상 낫다는 주장이 아닙니다. 비교한 후보 중 선택을 재현하기 위한 규약입니다. 검증 성능이 좋았다고 더 넓은 k 집합·다른 거리·새 모집단에서도 최적이라고 말하지 않습니다.
Comparing k=1,3,5 requires a fixed eligible frame and fold assignment. Changing validation units along with k obscures the source of performance differences. The engine applies the same folds to complete, positive-weight records for every candidate. If a candidate exceeds any fold’s available training rows, it is rejected rather than silently reduced there.
Pool weighted validation losses over all eligible validation records and divide by their total weight. Unequal fold sizes make this different from an unweighted average of fold means. Missing wages can change fold denominators in the individual case. With unit weights, the pooled score averages all evaluable records.
Select the lowest validation score, resolving exactly equal scores by smaller k. That convention makes selection reproducible; it does not establish that smaller k is always scientifically preferable. Success among declared candidates does not imply optimality over other distances, broader candidate sets or new populations.
30. 훈련 평균이라는 간단한 기준과 비교한다30. Compare with a simple training-only baseline
복잡한 이웃 규칙을 평가할 때에는 간단한 기준 모형도 필요합니다. 회귀에서는 각 fold의 훈련 결과 평균을 검증 행 모두에게 주는 기준을 쓸 수 있습니다. 분류에서는 훈련 범주 비율을 모든 검증 행의 확률로 사용합니다. 오류율 기준의 행동은 그 비율이 가장 큰 범주입니다. 어느 기준도 검증 결과 평균을 미리 보고 만들어서는 안 됩니다.
같은 평가 행에서 이웃 모형과 기준 모형의 손실을 나란히 봅니다. 임금 MSE는 (센트/시간)², 기대수명 MSE는 년²이며 직접 같은 크기를 비교할 수 없습니다. MAE는 원결과와 같은 단위입니다. 이진 Brier는 확률 오차의 제곱이고 0–1 오류율은 선택한 범주가 틀렸는지 세므로 같은 질문이 아닙니다. 다수 비이탈인 자료에서 항상 비이탈이라는 행동의 높은 정확도만으로 확률 예측이 좋다고 판단하지 않습니다.
기준 모형을 이기지 못한 결과도 학습에 의미가 있습니다. 이웃을 정한 입력·척도·k가 그 표본에서 추가 정보를 주지 못했을 수 있습니다. 하지만 그 원인을 한 번의 점수로 확정할 수는 없습니다. 표본 구성·잡음·평가 분할·기준 수준을 확인하고 결과를 그대로 보고합니다. 더 좋은 숫자가 나올 때까지 시험 자료를 바꾸는 것은 성능 개선과 다릅니다.
A simple baseline helps assess a more elaborate neighbour rule. For regression, give every validation record the corresponding fold’s training-outcome mean. For classification, use the training class proportions, selecting their largest class when evaluating 0–1 error. Neither baseline may use validation outcomes for fitting.
Compare losses on the same evaluable rows. Wage MSE has squared cents-per-hour units and life-expectancy MSE squared years, so their magnitudes are not directly comparable. MAE retains outcome units. Binary Brier evaluates probability error; 0–1 error evaluates a selected class. High majority-class accuracy alone does not establish good probability estimates.
Failure to beat a baseline is informative. The chosen predictors, scale or k may add little on this split, but one score does not identify the reason. Inspect sampling, noise and evaluation design, and report the result. Changing test records until a better number appears is not the same as improving a model.
학부 심화 · 선택Advanced undergraduate · optional
31. 시험 자료는 최종 선택 도구가 아니다31. Keep the test set out of selection
검증으로 k를 고른 뒤에는 개발 훈련 행 전체로 척도를 다시 맞추고 정한 k로 시험 입력을 예측합니다. 시험 결과는 그 후 점수를 계산할 때 사용합니다. 시험에서 k=3이 마음에 들지 않아 k=5·7을 더 시도하고 가장 좋은 값을 고르면 시험 자료도 선택에 참여한 것입니다. 그렇게 얻은 최고 점수를 처음부터 숨겨 둔 시험의 성능처럼 해석하면 낙관적일 수 있습니다.
검증 손실의 최소값도 선택의 영향을 받습니다. 많은 후보 중 가장 좋은 검증 수치를 골랐기 때문입니다. 선택까지 포함한 성능을 반복 평가하는 중첩 교차검증은 ML13에서 더 자세히 다룹니다. 이 장은 정한 훈련·검증·시험 절차를 충실히 실행하고, 그 한 번의 점수를 통계적 보장으로 부풀리지 않는 데 집중합니다.
실제 묶음의 위치 기반 분할은 계산을 재현하기 쉽게 한 교육용 규약입니다. 원래 모집단에서 독립·동일 분포로 뽑은 새 고객이나 미래 기간을 보장하지 않습니다. 특히 국가 표는 16개 보존 국가 중 앞 12개와 뒤 4개를 나누고, 개인·기업은 원행 위치를 따라 일정하게 고릅니다. 무작위 실험·무작위 전 세계 표본·미래 운영 검증이라고 이름 붙이지 않습니다.
After selecting k by validation, refit scales on the full development training set and predict held-out test inputs. Use test outcomes afterward for scoring. Trying more k values because a test result looks disappointing makes the test part of selection, potentially biasing the best reported score upward.
The minimum validation score is itself affected by choosing the best candidate. ML13 will examine nested cross-validation, which evaluates the selection process. Here we faithfully execute declared development and test roles without turning one split into a statistical guarantee.
The bundle’s position-based splits support reproducibility, not proof of IID sampling or future deployment performance. Countries use the first twelve and last four retained codes; person and business subsets follow declared source-position rules. These are not randomized interventions, random global country samples or prospective operating trials.
학부 심화 · 선택Advanced undergraduate · optional
32. 실습 D · fold 안의 계산을 손으로 따라간다32. Lab D · Follow the computation within each fold
가정한 네 행 x=0,1,2,3과 y=0,0,10,10을 쓰고 fold를 차례로 0,1,0,1로 배정합니다. k 후보는 1·2, 무게는 모두 1, 기본 전체 동률입니다. fold 0을 검증할 때 훈련은 x=1·3입니다. x=0은 결과 0을 빌리고, x=2는 두 훈련 점과 동률이어서 5를 빌립니다. 검증 제곱오차 합은 0+25=25입니다.
fold 1에서는 훈련 x=0·2로 검증 x=1·3을 예측합니다. x=1은 동률 평균 5라 오차 제곱 25, x=3은 결과 10을 빌려 오차 0입니다. 모든 검증 행을 모은 k=1의 MSE는 50/4=25/2입니다. k=2는 각 fold에서 두 훈련 결과 평균 5를 항상 주므로 MSE 25입니다. 기준 평균도 25여서 이 작은 예에서는 k=1이 선택됩니다. 실제 자료에서 같은 결과가 나온다고 미리 가정하지 않습니다.
실행 후 각 fold의 훈련 ID·검증 ID가 겹치지 않는지, range나 variance가 그 훈련 행으로 다시 계산되었는지 확인하세요. k=3을 추가하면 어느 fold에서도 훈련 행 두 개보다 커 거부되어야 합니다. 실제 사례로 바꿀 때에는 표본·원단위·결측 분모를 먼저 읽고 같은 과정을 적용합니다. 시험 점수는 k 선택이 끝난 뒤 별도 표에서 봅니다.
Use four assumed rows x=0,1,2,3 and y=0,0,10,10, assigning folds 0,1,0,1. Compare k=1 and two with unit weights and all ties. When validating fold zero, training inputs are one and three. Query zero borrows outcome zero; query two is tied and predicts five. The validation squared-error sum is twenty-five.
For fold one, training inputs zero and two predict queries one and three. Their squared errors are twenty-five and zero. Pooling all four records gives k=1 MSE 25/2. With k=2 each fold always predicts its training mean five, giving MSE twenty-five, the same as the baseline. Thus k=1 wins in this toy example, not necessarily in actual data.
Inspect disjoint training and validation IDs and refitted range or variance tables. Adding k=3 must be rejected because each training complement has only two rows. For actual cases, read sample selection, units and missing-frame denominators first, then repeat the procedure. Test scores are inspected separately after selection.
학부 심화 · 선택Advanced undergraduate · optional
33. 입력이 늘면 가까움도 더 까다로워진다33. More features make closeness more demanding
한 입력이 비슷한 대상을 찾는 것과 여러 입력이 모두 비슷한 대상을 찾는 것은 다릅니다. 나이만 비슷한 사람은 많아도 나이·교육·직업·지역·이용 시간까지 모두 비슷한 사람은 줄어들 수 있습니다. 다만 이것을 아무 조건 없이 “열이 많으면 항상 나쁘다”라고 바꾸어 말하지 않습니다. 새 입력이 유용한 정보를 담을 수도 있기 때문입니다.
이웃을 찾는 공간의 좌표 수를 p라고 부릅니다. 훈련 자료가 어떤 공간을 얼마나 채우는지도 중요합니다. 열이 열 개라도 서로 거의 같은 변수를 복제했다면 자유롭게 움직이는 방향은 적을 수 있습니다. 반대로 두 입력이라도 새 점 주변의 훈련 기록이 비어 있으면 가까운 비교가 부족할 수 있습니다. 변수 수·자료 밀도·새 점까지 거리라는 서로 다른 개념을 같이 봅니다.
이 절부터는 실제 자료의 사실과 차원을 설명하는 가정을 분리합니다. 다음의 균등 정육면체 모형은 계산을 이해하기 위한 가정입니다. 실제 국가·사람·통신 이용이 모든 방향으로 독립 균등하게 분포한다고 선언하는 것이 아닙니다. 실제 자료에서는 변수 간 연관·이산 점수·선택된 표본을 따로 확인해야 합니다.
Finding units similar on one feature differs from finding units similar on many features together. Similar age may be common while matching age, schooling, occupation, region and usage is rarer. This does not mean that adding any column is always harmful; new features can carry useful information.
The coordinate count p describes the input space, but coverage also matters. Ten nearly duplicated variables may have fewer freely varying directions. Conversely, even two features can leave a query with little nearby training support. Distinguish dimension, density and distance to available records.
We now separate observed data from assumptions used to explain dimension. The uniform-cube model is a mathematical illustration, not an assertion that countries, people or telecom usage are uniformly and independently distributed. Actual associations, discrete scores and sample selection require separate examination.
학부 심화 · 선택Advanced undergraduate · optional
34. 같은 상대 폭의 상자가 빠르게 비는 이유34. A fixed relative-width box rapidly loses mass
한 변의 길이가 1인 선분·정사각형·정육면체를 차례로 생각합시다. 그 안에 각 방향의 길이가 전체의 r배인 작은 상자를 놓습니다. 1차원에서 길이 비율은 r, 2차원에서 넓이 비율은 r², 3차원에서 부피 비율은 r³입니다. d차원에서도 각 방향의 길이를 곱해 rᵈ입니다. 여기의 r은 상자의 한 변 비율이지 유클리드 공의 반지름이 아닙니다.
점들이 단위 상자에서 균등하게 분포한다는 가정 아래 그 작은 상자에 들어갈 확률도 rᵈ입니다. r=1/2이면 1차원에서는 1/2, 10차원에서는 1/1024, 20차원에서는 1/1048576입니다. 각 방향에서 절반만큼 가까우라는 조건을 동시에 요구한 결과입니다. 표본이 같은 크기라면 가까운 영역에 남을 것으로 기대하는 수가 급격히 줄 수 있습니다.
작은 상자는 전체 지지집합 안에 완전히 들어 있어야 이 간단한 계산을 씁니다. 경계에서 잘린 상자나 상관된 분포에서는 같은 식이 곧 실제 확률이 되지 않습니다. 체비쇼프 반지름 a의 근방을 이 예와 연결하려면 상자가 잘리지 않을 때 변 길이가 2a라는 변환도 해야 합니다. 모양과 단위를 먼저 맞춘 뒤 차원을 비교합니다.
Pr(X∈B)=Vol(B)=rdfor an interior subcube under a uniform unit-cube model
Start with a unit-length segment, unit square and unit cube. An interior axis-aligned sub-box with each side a fraction r of the full side has relative length r, area r² and volume r³. In d dimensions the product is rᵈ. Here r is a side-length fraction, not the radius of a Euclidean ball.
Under a uniform unit-cube distribution, this volume fraction is also probability mass. At r=1/2 it is one half in one dimension, 1/1024 in ten and 1/1048576 in twenty. Requiring simultaneous closeness in each direction can leave very little nearby mass at fixed sample size.
The sub-box must lie wholly inside the support. Boundary clipping and correlated distributions change the calculation. To relate an untruncated Chebyshev-radius-a neighbourhood to this example, its side length is 2 a. Match geometry and units before interpreting a dimensional comparison.
Pr(X∈B)=Vol(B)=rdfor an interior subcube under a uniform unit-cube model
학부 심화 · 선택Advanced undergraduate · optional
35. 기대 이웃 한 명과 실제 한 명은 다르다35. One expected neighbour is not one observed neighbour
표본이 n개이고 각 점이 작은 상자에 들어갈 확률이 q=rᵈ라면, 들어온 수의 기대값은 nq입니다. n=1024, r=1/2, d=10이면 기대값이 1입니다. 이것은 실행할 때마다 정확히 한 점이 들어온다는 뜻이 아닙니다. 같은 가정의 표본이라도 0개·1개·2개가 나올 수 있습니다. 실습의 expectedNeighbours는 관측 자료에서 센 이웃 수와 다른 이름입니다.
독립 균등 표본이라는 가정을 더 사용하면 아무 점도 들어오지 않을 확률은 (1−q)ⁿ입니다. 위 설정에서 이 확률은 약 0.368이므로, 기대값 1만으로 상자가 비지 않는다고 보장할 수 없습니다. 적어도 한 명이 있을 확률을 원하는 수준으로 만들려면 별도의 확률 계산이 필요합니다. 이 장의 차원 실습이 출력하는 최소 n은 기대값을 1 이상으로 만드는 ⌈1/q⌉이며 신뢰수준을 보장하는 표본 수가 아닙니다.
r=0이면 상자의 확률질량은 0이라 어떤 유한 n도 이 기대값을 1로 만들지 못합니다. 이것을 n=0이라고 채우지 않습니다. r가 매우 작아 화면에서 0으로 보이더라도 정확값은 양수일 수 있습니다. 수학적 0·작은 양수의 표시 한계·실제 비어 있는 자료라는 서로 다른 상황을 구별합니다.
If n sampled points each enter a box with probability q=rᵈ, its expected count is nq. With n=1024, r=1/2 and d=10, expectation is one. A particular sample can contain zero, one or several points. The dimension API’s expectedNeighbours is not a count measured from an actual dataset.
Under an additional independent-uniform-sampling assumption, the probability of no point is (1−q)ⁿ. In this example it is about 0.368, so expected count one does not guarantee coverage. The API’s ⌈1/q⌉ is the sample size needed for expectation at least one, not a confidence-level guarantee of an occupied box.
When r=0, no finite n can make expected count one. That required sample size is undefined rather than zero. A tiny positive r may instead underflow to zero in a short display. Distinguish exact zero, a display limit for positive mass, and an actually empty observed dataset.
36. 관련 없는 열과 복제한 열은 다르게 작용한다36. Irrelevant and duplicated features act differently
새 점이 (0,1000), 후보 A=(0,0), B=(1,1000)이고 결과는 A가 0, B가 10이라고 가정합시다. 첫 입력만이 결과 관계를 담고 둘째는 설명용 불필요 특성이라고 별도로 가정합니다. 원척도 제곱거리는 A가 1000000, B가 1이어서 B를 고릅니다. 큰 숫자의 관련 없는 입력이 필요한 비교를 밀어낸 예입니다. 실제 자료에서 어떤 열이 불필요한지는 이런 숫자만 보고 미리 알 수 없습니다.
첫 좌표를 세 번 복제하면 같은 차이 제곱이 세 번 더해집니다. 정보가 세 배 생긴 것이 아니라 그 방향에 무게 3을 준 것과 같습니다. 각 복제 열을 표준화해도 여전히 같은 신호가 여러 번 셈해질 수 있습니다. 그러므로 열 수를 늘린 효과와 독립적인 방향을 추가한 효과를 구별해야 합니다. 상관된 자료를 독립 균등 상자라고 바꾸어 읽지 않습니다.
의미 없는 열을 버리거나 거리를 학습하는 방법을 사용할 수 있지만, 결과를 보고 그 열을 고르는 단계도 훈련·검증 안에 들어가야 합니다. 전체 자료로 관련성 검사를 한 뒤 시험 fold만 나누면 선택 정보를 미리 쓴 것입니다. 이 장의 featureWeights는 공개한 가정·후보 척도이며, 임의 최적의 거리를 자동 발견했다고 주장하지 않습니다.
(a−b)2+(a−b)2+(a−b)2=3(a−b)2
Assume query (0,1000), candidates A=(0,0), B=(1,1000), and outcomes zero and ten. Suppose separately that only the first feature relates to the target. Raw squared distances one million and one select B because a large irrelevant coordinate dominates. Actual irrelevance is not known merely from these numerical scales.
Duplicating a coordinate three times adds the same squared difference three times, equivalent to weighting that direction by three. It does not add three independent pieces of information. Standardizing each duplicate still can count one signal repeatedly. Correlated coordinates do not satisfy the independent uniform-cube illustration.
Feature selection or learned distances can help, but label-informed choices belong inside training and validation. Screening on the entire dataset before splitting folds would reuse evaluation information. Our featureWeights are declared assumptions or candidates, not a claim to discover an optimal metric automatically.
(a−b)2+(a−b)2+(a−b)2=3(a−b)2
학부 심화 · 선택Advanced undergraduate · optional
37. 모든 방향이 같은 정보를 담지는 않는다37. Not every direction contains the same information
거리 집중을 아주 단순한 가정으로 살펴봅시다. 모든 훈련 점의 각 좌표가 −1 또는 1이고 새 점이 원점이라고 가정합니다. 어느 훈련 점이든 원점까지 제곱 유클리드 거리는 좌표 수 d입니다. 입력 벡터가 서로 달라도 모두 같은 거리라서 k번째의 순위가 대상을 구분하지 못합니다. 기본 동률 규칙은 모두를 포함합니다. 이것은 실제 자료 전체의 법칙이 아니라 거리만으로 구별이 안 되는 한 반례입니다.
일반적인 고차원 분포에서는 최소·최대 거리의 상대적 차이가 작아지는 현상을 연구하지만, 분포·좌표 의존성·거리 선택에 따라 달라집니다. 차원이 높다는 이유만으로 모든 데이터의 거리가 반드시 같아진다고 쓰지 않습니다. 실제 사례에서는 선택된 거리가 원척도로 얼마나 큰지, 어떤 좌표가 기여하는지, 의미 있는 가까움인지 함께 봅니다.
관측이 낮은 차원의 곡선이나 평면 가까이에 모여 있다면 열 수보다 작은 내재 차원이 중요할 수 있습니다. 그렇다고 차원 축소가 언제나 목표 정보를 보존하는 것은 아닙니다. 분산이 작은 방향이 분류에 중요할 수도 있습니다. PCA·표현 학습은 뒤 장과 연결하되, 거리 계산을 줄인다는 이유만으로 모든 예측 문제가 해결된다고 말하지 않습니다.
xi∈{−1,1}d,x0=0⟹d2(xi,x0)2=j=1∑d1=d
Consider a simple assumed construction: every training coordinate is either −1 or one, while the query is the origin. Every training vector has squared distance d, its coordinate count, even when the vectors differ. The all-tie rule includes them all. This is a counterexample where distance cannot distinguish candidates, not a law about every real dataset.
More general concentration questions concern relative differences between nearest and farthest distances. Their answers depend on distributions, coordinate dependence and metric choice. High dimension alone does not force all distances to become identical. Inspect actual distances and their coordinate contributions rather than relying on the term close.
Data near a lower-dimensional curve or subspace can have smaller intrinsic dimension than its column count. Dimensionality reduction may help, but low-variance directions can still carry target information. Later PCA and representation chapters address these choices without claiming that fewer distance coordinates solve every prediction problem.
xi∈{−1,1}d,x0=0⟹d2(xi,x0)2=j=1∑d1=d
학부 심화 · 선택Advanced undergraduate · optional
38. 정확한 검색과 빠른 근사 검색을 구분한다38. Distinguish exact search from approximate search
단순한 정확 검색은 새 점마다 모든 n개 훈련 행과 p개 좌표를 비교합니다. 비교할 좌표 수의 차수는 np이고, 여러 새 점이면 그만큼 반복됩니다. 정렬이나 k번째 경계 선택에도 계산이 듭니다. 이것은 기본적인 연산 횟수의 설명이며 큰 정수·긴 분수를 다루는 실제 비트 계산 비용까지 상수라고 선언한 것은 아닙니다.
공간을 나눈 탐색 자료구조나 근사 최근접 이웃 검색이 실제 시스템에서 쓰입니다. 낮은 차원·유리한 분포에서 효율적인 구조라도 고차원에서 모든 문제에 같은 속도 향상을 보장하지는 않습니다. 근사 검색은 진짜 가장 가까운 행 일부를 놓칠 수 있습니다. 후보를 찾은 뒤 정확 거리로 다시 정렬해도 검색하지 못한 행을 자동으로 복원하지는 못합니다.
이 장의 엔진은 작은 교육용 묶음에 대해 정확한 분수 비교로 모든 후보를 검사합니다. 거리쌍 계산 예산을 넘으면 거부하고, 일부 행만 훑고도 정확 kNN이라고 표시하지 않습니다. 실제 서비스에서는 정확도·시간·메모리·개인정보·갱신 비용을 함께 비교해야 하지만, 이 실습의 제한된 검색을 대규모 운영 시스템 구현으로 부르지는 않습니다.
A straightforward exact search compares each query with n training rows across p coordinates, requiring order np coordinate comparisons, plus ranking or boundary selection. Multiple queries repeat this work. This counts elementary comparisons without pretending that arbitrary-length integer arithmetic has constant bit cost.
Spatial indexes and approximate nearest-neighbour systems can accelerate practical search. Their benefits depend on dimension and distribution. Approximate search may miss genuinely nearest records; exact reranking of retrieved candidates cannot automatically recover a candidate that was never retrieved.
Our educational engine scans every candidate with exact rational comparisons within a stated distance-pair budget. It rejects excessive work instead of scanning a subset and calling it exact. Large deployments involve additional accuracy, latency, memory and update choices not claimed by this small teaching engine.
대학원 연결Graduate bridge
39. 일치성은 표본 하나의 성능과 다르다39. Consistency differs from success on one sample
일치성은 표본 크기 n이 커지는 일련의 절차에서 어떤 목표로 가까워지는지 묻는 개념입니다. 고정된 k=1이 언제나 일치하는 것은 아닙니다. 입력과 독립인 이진 결과가 이탈 확률 0.7이라고 가정하고 동률 없는 새 점의 1NN을 생각합시다. 훈련 이웃의 결과와 새 결과가 독립이면 오류율은 0.7×0.3+0.3×0.7=0.42입니다. 항상 다수 범주를 고르는 Bayes 오류 0.3과 다릅니다. 가까운 입력 하나를 더 찾는 것만으로 결과 잡음이 사라지지 않았습니다.
왜 이웃을 점차 늘리면서 전체의 비중은 줄이는지 보겠습니다. 고정 차원의 보통 유클리드 공간에서 독립 동일 분포 표본, 새 점 근처 양의 연속 밀도, 국소 Lipschitz 평균 관계와 유계 조건부 잡음 분산을 가정하는 예를 생각합니다. 이웃 반경 R이 작아지면 편향 절댓값은 LR 이하이고, m개 같은 무게 독립 이웃의 분산은 σ²/m 이하입니다. 반경은 줄고 이웃 수는 늘어야 두 항을 함께 줄일 수 있습니다. 무작위 반경으로부터 기대손실 수렴까지 주장하려면 적분 가능성 등 필요한 조건을 더 확인합니다.
조건을 갖춘 밀도 근사에서 R은 (k/n)^(1/d) 정도로 생각할 수 있어 MSE의 근사 항은 (k/n)^(2/d)+1/k입니다. 균형은 k가 n^(2/(d+2)) 정도이고 손실 속도는 n^(−2/(d+2)) 정도가 됩니다. 차원이 커지면 느려질 수 있다는 조건부 설명이지 모든 분류·가중치·이산·의존 자료의 정리가 아닙니다. ML17에서 확률 수렴·가중치 조건·구체적 일치성 정리를 더 엄밀히 다룹니다.
∣Bias∣≤LR,Var≤mσ2;MSEheuristic≍(nk)2/d+k1
Consistency concerns a sequence of procedures as sample size grows. Fixed k=1 is not automatically consistent. Assume binary outcomes independent of features with probability 0.7 for the positive class and no distance ties. A new outcome and its neighbour’s label are independent, giving error 0.42 rather than Bayes error 0.3 from always choosing the majority class. A closer input alone did not remove outcome noise.
To see why neighbour counts can grow while their sample fraction shrinks, consider a fixed-dimensional Euclidean example with IID sampling, positive continuous density near the query, a locally Lipschitz mean and bounded conditional noise variance. Radius R bounds absolute approximation bias by LR, while m uniformly weighted independent neighbours give variance at most σ²/m. Both shrinking radius and growing effective count matter. Converting stochastic-radius behavior into expected-risk convergence requires appropriate integrability conditions.
Under regular local-density approximations, radius has scale (k/n)^(1/d), suggesting MSE terms (k/n)^(2/d)+1/k. Balancing them gives k of order n^(2/(d+2)) and risk order n^(−2/(d+2)). This conditional regression heuristic is not a theorem for every classifier, weighting scheme, discrete support or dependent sample. ML17 develops the convergence and weight conditions more precisely.
∣Bias∣≤LR,Var≤mσ2;MSEheuristic≍(nk)2/d+k1
학부 심화 · 선택Advanced undergraduate · optional
40. 실습 E · 부피·기대수·표시 한계를 구분40. Lab E · Separate volume, expectation and display limits
단위 상자의 균등 분포를 가정하고 sideFraction=1/2, observations=1024를 입력합니다. 차원이 1이면 작은 상자의 질량은 1/2·기대수 512, 10이면 1/1024·기대수 1, 20이면 1/1048576·기대수 1/1024입니다. 실행 전 두 값을 각각 계산해 보세요. 실제 1024명의 관측에서 그렇게 센 결과라고 설명하지 않습니다.
차원을 고정하고 r를 바꾸면 어느 방향의 범위를 얼마나 줄인 것인지 말로 설명합니다. r=0과 r=1의 경계도 확인하세요. 전자는 질량 0·필요 기대 표본 수 미정의, 후자는 질량 1·기대수 n입니다. “기대수 한 명 이상에 필요한 n”을 95% 보장 표본 수로 이름 붙이지 않습니다. 유클리드 반지름과 상자 한 변을 섞지 않는지도 확인합니다.
심화 입력으로 아주 작은 r와 큰 차원을 고르면 양의 정확값이 화면의 부동소수점 범위보다 작아질 수 있습니다. 기본 표는 “0 아님·아주 작음”과 같은 표시와 정확값 펼치기를 함께 제공해야 합니다. 수천 자리 분모의 앞부분만 0처럼 쏟아내기보다 계산의 뜻을 먼저 읽습니다. 실제 자료의 원행·거리 분포와 이 가정한 상자 그림을 나란히 보되 같은 자료 생성 모형이라고 단정하지 않습니다.
Assume a uniform unit cube with sideFraction=1/2 and observations=1024. Dimension one gives mass one half and expected count 512; dimension ten gives mass 1/1024 and expected count one; dimension twenty gives mass 1/1048576 and expected count 1/1024. Predict both mass and count before running. They are not measured counts from 1,024 actual people.
At fixed dimension, explain which directional widths change when r changes. Check boundaries r=0 and one: zero mass gives no finite sample size for expected count one, while unit mass gives expected count n. Do not label the expectation threshold a 95-percent coverage guarantee, or confuse box side length with Euclidean radius.
A tiny r and large dimension can produce a positive exact mass below binary64 display range. Show a concise nonzero-small indication and retain the full exact value in a disclosure. Meaning matters more than flooding the main table with a long denominator prefix. Compare the assumed diagram with actual source-distance patterns without asserting the same data-generating distribution.
학부 심화 · 선택Advanced undergraduate · optional
41. 국가 사례 · 소득·실업과 기대수명41. Country case · Income, unemployment and life expectancy
국가 사례는 보존한 World Bank 원본 응답에서 2024년 16개 국가의 세 지표를 다시 읽습니다. 입력은 1인당 GDP(2015년 고정 미국달러)와 실업률(%), 결과는 출생 시 기대수명(년)입니다. 나라별 지표의 원래 응답 위치·국가 코드·연도·수치 토큰을 함께 남깁니다. 기대수명은 그 해 태어난 모든 아이의 실제 사망 나이를 관찰한 평균이라는 뜻이 아니라 해당 지표의 인구통계학적 정의를 가진 수치입니다.
보존 순서의 앞 12개 국가를 훈련, 뒤의 Singapore·United States·Viet Nam·South Africa 네 국가를 시험으로 둡니다. 무작위 세계 표본이나 인구수 가중 세계 평균이 아닙니다. 기본 range·제곱 유클리드·균등 k=3에서 Singapore의 이웃은 Australia·Germany·United Kingdom이고 예측은 약 81.7436년입니다. 관측 지표 약 83.3463년과 별도로 비교합니다. 소득이 비슷하다는 것이 의료제도·연령 구조·역사까지 같다는 뜻은 아닙니다.
훈련 내 세 fold에서 k=1·3·5를 비교하면 k=3이 선택되고 CV MSE는 약 9.6839년²입니다. 그러나 네 시험 국가의 MSE는 약 52.9043년²로 훈련 평균 기준의 약 51.0621년²보다 나쁩니다. 검증에서 이겼다고 시험에서도 반드시 이기는 것이 아님을 보여 줍니다. 특히 South Africa 실업률 32.279%는 훈련 범위 2.5~7.4% 밖입니다. 이 수치를 실업률 정책의 기대수명 인과효과나 국가의 가치 평가로 바꾸어 읽지 않습니다.
The country case rereads three 2024 indicators for sixteen retained countries from the original World Bank response. Predictors are GDP per capita in constant 2015 US dollars and unemployment percent; the outcome is life expectancy at birth in years. Original response positions, country codes, dates and numeric tokens remain traceable. Life expectancy has its demographic indicator definition, not a directly observed eventual lifespan for every child born that year.
The first twelve retained codes train; Singapore, the United States, Viet Nam and South Africa test. This is neither a random world sample nor a population-weighted global average. With range scaling, squared Euclidean distance and uniform k=3, Singapore borrows Australia, Germany and the United Kingdom, predicting about 81.7436 years against observed 83.3463. Similar income does not establish matching healthcare systems, demographics or histories.
Three-fold development validation among k=1,3,5 selects three, with MSE about 9.6839 years². Test MSE about 52.9043 is nevertheless worse than the training-mean baseline 51.0621. Development success does not guarantee test improvement. South African unemployment 32.279 percent lies outside the training range 2.5–7.4 percent. These statistics identify neither an unemployment-policy effect nor a ranking of countries’ worth.
학부 심화 · 선택Advanced undergraduate · optional
42. 개인 사례 · 실제 임금과 정수 입력의 동률42. Individual case · Actual wages and ties in integer predictors
개인 자료는 David Card의 공개 proximity ZIP 안 nls.dat와 코드북을 직접 읽은 NLS 남성 코호트의 1976년 기록입니다. 원본 3613행·52개 고정폭 필드를 모두 CSV에 남깁니다. 이 예측의 입력은 1976년 교육 연수·나이, 결과는 원래 시간당 임금 wage76(센트/시간)입니다. 이상치를 절단한 로그 임금 lwage76, 다른 해 임금, 표본 가중치도 원본에는 있지만 이번 입력이나 결과와 바꾸어 쓰지 않습니다.
전체 원행 중 j=0,…,239에 대해 floor[j(3613−1)/239]인 서로 다른 위치를 골라 240행을 만듭니다. 네 번째마다 시험, 나머지는 훈련이며 완전한 훈련·시험 행은 145·52개입니다. 동일한 정수 교육·나이 조합이 반복되므로 요청 k와 실제 이웃 수가 크게 다를 수 있습니다. 첫 시험 원행 46의 원 ID79는 교육 11년·나이24세·임금235센트/시간입니다.
range·균등 k=3에서 그 질의의 경계 제곱거리는 1/169이고 동률 전체 포함으로 실제 13행이 선택됩니다. 교육10년 또는12년·나이24세인 행들이며 예측은 5664/13≈435.69센트/시간입니다. 이를 k=3이니 정확히 세 사람 평균이라고 보고하면 틀립니다. 이웃 검색과 임금 예측의 결측 분모도 구분합니다. 이 비교는 예측 예제이며 교육을 한 해 늘렸을 때 그 개인의 임금이 얼마 변할지나 Card의 원 IV 연구 전체를 재현한 결과가 아닙니다.
The individual source is the 1976 NLS young-men cross-section in David Card’s released proximity ZIP, read with its fixed-width codebook. All 3,613 rows and 52 source fields remain in the CSV. Predictors are schooling and age in 1976; the outcome is raw wage76 in cents per hour. Trimmed log wage, later wages and sampling weights remain preserved but are not substituted for these chosen fields.
Select 240 distinct positions floor[j(3613−1)/239], j=0,…,239. Every fourth selected row tests and the others train, leaving 145 complete training and 52 complete test rows. Integer schooling–age combinations repeat. The first test source row 46, original ID 79, has schooling 11 years, age 24 and wage 235 cents per hour.
With range scaling and uniform requested k=3, its boundary squared distance is 1/169. The full boundary tie contains 13 rows, all age 24 with schooling 10 or 12. Prediction is 5664/13≈435.69 cents per hour. Calling it an average of exactly three people would be incorrect. Pure search and labeled prediction also have different missing-frame denominators. This predicts a recorded outcome; it estimates neither an individual education intervention nor the complete original IV study.
학부 심화 · 선택Advanced undergraduate · optional
43. 기업 사례 · 실제 이용 기록과 이후 이탈43. Business case · Actual usage records and later churn
기업 사례는 UCI Iranian Churn 원본 ZIP의 3150행·14개 열을 모두 보존합니다. 공식 설명에 따르면 입력 특성은 처음9개월의 집계, 이탈 표지는 12개월 말 상태이며 사이의3개월을 계획 간격으로 둡니다. 이 장은 통화 초·통화 횟수·통화 실패 횟수 세 입력만 사용하고 결과 Churn0/1을 예측합니다. 순서형 요금 코드·상태·계산된 고객가치 등 다른 열을 연속형 금액처럼 몰래 넣지 않습니다.
원행 전체를 보존하면서 같은 명시적 위치 공식으로 240행을 고르고 180훈련·60시험으로 나눕니다. 공개 파일의 sourceRow는 보존한 행 위치이지 회복한 익명 고객 ID가 아닙니다. 비슷하거나 같은 입력이 있다고 같은 사람으로 단정하지 않습니다. 원자료 설명의 수집 방식과 이 장이 따로 정한 위치 표집·fold 배정도 같은 무작위 절차라고 부르지 않습니다.
고정 range·균등 k=3의 시험 Brier는 약0.11956, 훈련 비율 기준은 약0.12753입니다. 이 한 분할에서는 조금 작지만 그 차이만으로 운영 개선이나 연락의 이탈 방지 효과가 입증되지는 않습니다. 훈련 CV의 후보1·3·5에서는5가 선택되므로, 선택 절차를 평가할 때에는 선택한5를 훈련 전체에 다시 맞춘 시험 결과와 고정3의 결과를 구별해야 합니다. 실제 사례 표는 설정과 원행 기여·확률·관측 이탈을 함께 남깁니다.
The business case preserves all 3,150 rows and 14 columns of the original UCI Iranian Churn ZIP. Official documentation describes first-nine-month aggregated inputs and churn at the end of twelve months, with a three-month planning gap. We use only seconds of use, call frequency and failed calls to predict Churn 0/1, rather than silently treating ordinal tariff codes or derived customer value as ordinary continuous measurements.
A declared evenly spaced position rule selects 240 rows, assigning 180 to training and 60 to testing. Source-row numbers do not recover anonymous customer identities; identical feature vectors do not prove the same person. The source’s collection description also differs from our subsequent deterministic subsampling and fold convention.
Fixed range-scaled uniform k=3 gives test Brier about 0.11956 versus training-proportion baseline 0.12753. That small improvement on one split proves neither operating gains nor a causal retention effect from contact. Development validation among 1,3,5 selects five: evaluation of selection must use its refitted test predictions, distinguished from the fixed-three profile. Case tables retain settings, neighbour contributions, probabilities and observed labels.
학부 심화 · 선택Advanced undergraduate · optional
44. 단위·스케일·동률을 바꿀 때 무엇이 달라지나44. What changes with units, scaling and ties?
같은 원행을 사용하더라도 none·range·variance, 균등·역제곱 무게, 동률 전체 포함·stable은 서로 다른 예측 규칙입니다. 한 설정을 바꿀 때 다른 조건과 평가 분모를 그대로 두어 어떤 변화가 이웃 집합·가중치·예측에 전달되었는지 추적합니다. 결과 수치가 달라졌다는 사실만으로 원래 자료가 잘못되었다고 판단하지 않습니다.
국가 자료는 GDP 숫자 크기가 실업률보다 훨씬 큽니다. 원척도와 정규화 척도의 이웃이 달라지는 이유를 각 좌표 기여로 설명하세요. 개인 자료의 13개 경계 동률은 stable로 잘랐을 때 어느 원행이 빠지는지와 연결합니다. 기업 자료에서는 두 고객의 통화 초가 같아도 빈도·실패 수가 다르면 전체 입력은 같지 않다는 점을 확인합니다.
설정을 비교할 목적으로 시험 점수를 보았다면 그 시험을 최종 선택과 무관한 것으로 남겨 둘 수는 없습니다. 이 장의 여러 고정 설정 표는 민감도 학습 자료입니다. 사전에 정한 CV 선택 절차와 여러 시험 수치를 사후 비교하는 학습을 구별하여 설명합니다. 공개 표 전체를 보여 주고 유리한 설정 하나의 숫자만 연구 결과처럼 골라 쓰지 않습니다.
None, range and variance scaling; uniform and inverse-square votes; and all ties versus stable selection are different prediction rules even on the same rows. Change one component while holding the evaluation frame fixed, then trace its effects on membership, contributions and predictions. Changed output alone does not establish bad source data.
GDP numerically dominates unemployment in raw country distances, so inspect coordinate contributions when scaling changes neighbours. For the individual case, examine which of the thirteen boundary-tied records stable selection removes. In the business case, equal seconds of use do not imply equal full feature vectors if call counts or failures differ.
Inspecting test profiles for comparison makes them part of that exploratory learning. Distinguish these sensitivity tables from a prespecified CV-selection protocol. Expose complete settings instead of presenting one favorable post-hoc test number as the sole research conclusion.
학부 심화 · 선택Advanced undergraduate · optional
45. 원행에서 이웃과 평가를 다시 계산한다45. Reproduce neighbours and scores from source records
먼저 각 묶음의 전체 CSV에서 원위치·단위·결측 기호·실습 선택 규칙을 확인합니다. 원본52필드 또는14필드가 모두 입력이라는 뜻은 아닙니다. 모델 계약에 정한 입력·결과·훈련·시험·fold 열만 계산에 사용합니다. 출처의 나머지 열은 추적을 위해 보존합니다. 특히 개인 파일의 미래 임금이나 원결과를 새 예측 입력으로 섞지 않습니다.
공개 Python과 R 코드는 선택과 완전 프레임을 다시 만들고 훈련 척도·이웃 순위·동률·확률·평가 점수를 계산하도록 구성합니다. 미리 저장된 최종 점수만 불러오는 것은 재계산이 아닙니다. Python의 정확 분수와 R의 유한 정밀도 계산은 마지막 자릿수나 아주 가까운 동률에서 차이가 날 수 있으므로 거리·원행·동률 규약까지 대조합니다. 원래 정확한 동률을 임의 오차 허용치로 깨뜨리거나 다른 두 값을 무조건 같다고 하지 않습니다.
기본 표의 짧은 근삿값은 비교를 돕고, 정확값과 전체 결과 파일은 원계산을 보존합니다. 원문을 내려받지 않아도 선택 규칙과 핵심 표·그래프·원행 기여를 읽을 수 있어야 하며, 내려받으면 같은 숫자를 다시 만들 수 있어야 합니다. 공개 코드를 실행했다는 사실과 인과·일반화 주장이 타당하다는 사실은 별도로 확인합니다.
Begin with complete selected CSVs and verify positions, units, missing symbols and lab selection. Preserving all 52 or 14 source fields does not make them all predictors. Use only the contracted features, outcomes, roles and folds. Other fields remain for traceability, especially later wages that must not become inputs to the current wage exercise.
Standalone Python and R rebuild the eligible frame, fitted scales, ranked neighbours, tie sets, probabilities and scores rather than loading final stored scores. Exact fractions and finite-precision arithmetic can differ in final digits or near-tie behavior, so compare distances, source membership and conventions as well as aggregate scores. Do not silently replace mathematical equality with an arbitrary tolerance.
Concise display numbers support reading while exact disclosures and full result files preserve calculations. Readers should understand the selection and main tables, graphs and contributions without downloading a source document, and be able to reproduce them when they do download. Reproducible computation remains separate from warranted causal or generalization claims.
대학원 연결Graduate bridge
46. 대학원 연결 · 국소 지지와 외삽의 한계46. Graduate bridge · Local support and extrapolation limits
양의 정규화 무게로 결과를 평균하면 예측은 선택된 결과의 최솟값과 최댓값 사이에 있습니다. 이는 장점이기도 하고 한계이기도 합니다. 극단적인 새 소득 수준이나 나이에서도 자동으로 선형 추세를 계속 연장하지 않습니다. 훈련 범위 밖의 새 점에 가장 가까운 몇 행을 찾았다는 사실이 그 지점의 참평균을 잘 알게 되었다는 뜻은 아닙니다.
실습의 outsideTrainingRange는 각 좌표가 훈련 최솟값·최댓값 밖인지 표시합니다. 모든 좌표가 범위 안이라고 다변량 공간에서 충분한 국소 지지가 있다는 뜻은 아닙니다. 비어 있는 조합이나 훈련 점들의 볼록껍질 밖에 있을 수도 있습니다. 반대로 경계 밖이라는 표지가 곧 예측이 틀렸다는 증명도 아닙니다. 거리는 경고·해석을 돕는 관측 정보이지 자동 인과 판정 장치가 아닙니다.
통계적 결론을 넓히려면 표본 독립성·관측 선택·목표 분포·관계의 정규성과 전처리의 학습 규약을 다루어야 합니다. 원임금의 결측을 빼는 방식이나 한 회사의 행을 위치로 고른 방식이 목표 모집단을 어떻게 바꾸는지도 검토합니다. ML17의 일치성, ML15의 분포 이동, ML20의 불확실성으로 이어질 때도 정확한 유한 계산과 그 조건을 혼동하지 않습니다.
λi≥0,i∑λi=1⟹i∈Nminyi≤i∈N∑λiyi≤i∈Nmaxyi
A positive normalized weighted mean stays between the selected minimum and maximum outcomes. This is both a property and a limitation: kNN does not automatically extend a linear trend beyond observed outcomes. Finding the nearest available records for an extreme query does not establish knowledge of its true conditional mean.
outsideTrainingRange checks each coordinate’s training minimum and maximum. Being inside every marginal range does not establish multivariate local support or membership in the training convex hull. Empty combinations may remain. Conversely an outside flag is not proof of error. Distances provide evidence for interpretation, not automatic causal judgments.
Broader statistical conclusions require sampling, selection, target distributions, regularity and preprocessing conditions. Missing wages and deterministic company subsampling can change the population represented. Later consistency, distribution-shift and uncertainty chapters retain the distinction between exact finite calculations and the conditions supporting generalization.
λi≥0,i∑λi=1⟹i∈Nminyi≤i∈N∑λiyi≤i∈Nmaxyi
학부 심화 · 선택Advanced undergraduate · optional
47. 세 사례의 원행·기여·평가를 함께 읽는다47. Read original rows, contributions and evaluations together
아래 세 사례는 실제 원자료 전체와 실습에 사용한 위치·단위·역할을 연결합니다. 국가·개인·기업의 표적이 서로 다르므로 단순 점수 크기로 어느 분야의 예측이 더 쉽다고 순위를 매기지 않습니다. 실제 기록이라는 공통점과 동일한 연구 설계라는 주장은 다릅니다. 원행은 전체 내려받기로 보존하고 핵심 표와 그림은 본문에서 읽을 수 있게 합니다.
한 시험 행을 골라 원입력→훈련 전용 척도→거리→경계 동률→정규화 무게→예측→관측 결과→손실 순으로 따라갑니다. 나라 이름이나 원 ID가 같은 듯 보인다고 후보를 합치거나 원래 결과를 바꾸지 않습니다. 전체 동률 규칙에서 요청한 k보다 많은 이웃이 선택되는 표를 설명하고, 필요한 경우 stable 결과와 비교합니다.
그다음 전체 평가 가능 행과 기준 모형을 확인합니다. 고정 설정 비교와 훈련 CV로 선택한 설정을 구별하고, 좋은 결과와 실패한 결과를 함께 읽습니다. 정확값 펼치기·전체 코드·독립 Python/R·공식 출처는 숫자의 근거를 따라가기 위한 도구입니다. 같은 계산을 할 수 있다는 것과 현실의 정책·사람·기업에 행동을 권할 충분한 근거가 있다는 것은 별개입니다.
국가 제도 · 실제 국가 지표
World Bank 원응답의 2024년 16개 국가를 사용합니다. 입력은 2015년 고정 달러 1인당 GDP·실업률, 결과는 기대수명입니다. 기대수명은 해당 시기 사망률 패턴을 반영하는 기간 지표이며 태어난 모든 사람의 실제 일생을 관측한 평균이 아닙니다. 보존 국가 순서의 앞12개를 훈련, 뒤4개를 시험으로 정했습니다. 무작위 세계 표본이나 인구 가중 세계 평균이 아닙니다.
원선택·실습·완전 프레임의 다른 분모
단계
수
원본 보존 행
16
실습 선택 행
16
훈련/시험 원행
12 / 4
완전 훈련/시험 결과
12 / 4
예측에 사용한 입력 수
2
16개 전체 국가 원값
원행
원식별자
역할
1인당 GDP(2015고정US$)
실업률(%)
관측结果
1
AUS
훈련
≈61486.4정확값768579768443/12500000
≈3.942정확값1971/500
≈83.0512정확값830512195121951/10000000000000
2
BRA
훈련
≈9566.75정확값956674518687619/100000000000
≈6.801정확값6801/1000
≈76.023정확값76023/1000
3
CAN
훈련
≈45061.4정확값90122772917457/2000000000
≈6.351정확값6351/1000
≈82.108정확값410540243902439/5000000000000
4
CHN
훈련
≈13119.1정확값32797769024879/2500000000
≈4.59정확값459/100
≈78.017정확값78017/1000
5
DEU
훈련
≈44027.8정확값440277631554469/10000000000
≈3.4정확값17/5
≈80.7927정확값807926829268293/10000000000000
6
FRA
훈련
≈39683.4정확값396833953489029/10000000000
≈7.4정확값37/5
≈82.9805정확값829804878048781/10000000000000
7
GBR
훈련
≈47901정확값239504840072073/5000000000
≈4.361정확값4361/1000
≈81.3869정확값406934268292683/5000000000000
8
IDN
훈련
≈4367.95정확값218397370923969/50000000000
≈3.301정확값3301/1000
≈71.288정확값8911/125
9
IND
훈련
≈2366.83정확값23668328910323/10000000000
≈4.173정확값4173/1000
≈72.235정확값14447/200
10
JPN
훈련
≈37976.6정확값189883185894149/5000000000
≈2.5정확값5/2
≈84.0363정확값420181707317073/5000000000000
11
KOR
훈련
≈37048.4정확값46310533000187/1250000000
≈2.784정확값348/125
≈83.6293정확값836292682926829/10000000000000
12
MEX
훈련
≈10284정확값51420168462863/5000000000
≈2.678정확값1339/500
≈75.264정확값9408/125
13
SGP
시험
≈68129.7정확값42581060025143/625000000
≈2.737정확값2737/1000
≈83.3463정확값416731707317073/5000000000000
14
USA
시험
≈66856.5정확값668565131698371/10000000000
≈4.022정확값2011/500
≈78.8902정확값78890243902439/1000000000000
15
VNM
시험
≈4012.51정확값100312694980271/25000000000
≈1.602정확값801/500
≈74.736정확값9342/125
16
ZAF
시험
≈5715.48정확값142886882867287/25000000000
≈32.279정확값32279/1000
≈66.312정확값8289/125
이 미리보기는 결과가 결측인 행도 그대로 남깁니다. 전체 원행·실습 선택·원래 단위는 아래 CSV에서 추적할 수 있습니다. 새 시험 행을 훈련 척도에 넣지 않습니다.
CV 선택 행은 훈련 내부에서 1·3·5를 비교해 정한 k를 전체 완전 훈련에 재학습한 절차입니다. 다른 행은 고정 민감도 설정입니다. 여러 시험 수치를 보며 사후 선택한 것을 독립 최종 시험처럼 해석하지 않습니다. 국가 기대수명의 MSE 단위는 년², MAE 단위는 년입니다. 같은 시험 행에서 이웃 예측과 훈련 평균 기준을 비교합니다.
전체 CSV와 코드만 같은 폴더에 두고 독립 실행할 수 있습니다. Python은 정확 분수, R은 정확 정수 limb로 거리 순위를 보존하고 점수는 유한 정밀도로 계산합니다. 원조사 ZIP·JavaScript·개인 작업 파일을 불러오는 코드가 아닙니다.
개인 기록 · 원임금과 교육·나이
Card의 공개 ZIP과 원코드북을 직접 읽어 3613개 NLS 남성 코호트 기록·52개 고정폭 필드를 보존했습니다. 입력은 1976년 교육·나이이고 결과는 raw wage76, 센트/시간입니다. 절단한 로그 임금·다른 해 임금·원표본 가중치를 이 분석의 입력·결과와 바꾸어 쓰지 않습니다. 전체 원행에서 명시한 균등 간격 위치240개를 고르고180훈련·60시험으로 나눕니다. 완전한 임금 예측 분모는145훈련·52시험입니다.
원선택·실습·완전 프레임의 다른 분모
단계
수
원본 보존 행
3613
실습 선택 행
240
훈련/시험 원행
180 / 60
완전 훈련/시험 결과
145 / 52
예측에 사용한 입력 수
2
훈련 첫6행·시험 첫4행 미리보기 · 전체 원행은 CSV
원행
원식별자
역할
교육(년)
나이(년)
관측结果
1
2
훈련
7
29
548
16
17
훈련
14
24
300
31
37
훈련
18
32
1800
61
107
훈련
10
24
434
76
133
훈련
18
24
693
91
153
훈련
12
26
관측/평가 값 없음
46
79
시험
11
24
235
106
176
시험
15
28
350
167
265
시험
16
26
462
227
346
시험
13
28
278
이 미리보기는 결과가 결측인 행도 그대로 남깁니다. 전체 원행·실습 선택·원래 단위는 아래 CSV에서 추적할 수 있습니다. 새 시험 행을 훈련 척도에 넣지 않습니다.
CV 선택 행은 훈련 내부에서 1·3·5를 비교해 정한 k를 전체 완전 훈련에 재학습한 절차입니다. 다른 행은 고정 민감도 설정입니다. 여러 시험 수치를 보며 사후 선택한 것을 독립 최종 시험처럼 해석하지 않습니다. 원임금 MSE의 단위는 (센트/시간)², MAE는 센트/시간입니다. 달러 단위 오차나 이탈 확률의 손실과 섞지 않습니다.
훈련 전용 세 fold의 pooled 검증 손실
k
전체 평가 행
CV MSE
기준
선택
1
145
≈122082정확값3122615580761/25578000
≈77759.1정확값15886019000126761/204297937920
—
3
145
≈69500.2정확값395038867213/5684000
≈77759.1정확값15886019000126761/204297937920
—
5
145
≈64657.1정확값7246826115406037/112080969000
≈77759.1정확값15886019000126761/204297937920
선택
선택 후보의 fold별 훈련 척도 · 검증 입력 제외
Fold
훈련
검증
입력
최소
최대
평균
분산
0
102
43
교육(년)
5
18
≈13.3824정확값455/34
≈7.05969정확값8161/1156
0
102
43
나이(년)
24
34
≈28.2549정확값1441/51
≈10.0527정확값26147/2601
1
92
53
교육(년)
5
18
≈13.2391정확값609/46
≈7.35586정확값15565/2116
1
92
53
나이(년)
24
34
≈27.7283정확값2551/92
≈8.93703정확값75643/8464
2
96
49
교육(년)
7
18
≈13.2396정확값1271/96
≈7.43218정확값68495/9216
2
96
49
나이(년)
24
34
≈27.6771정확값2657/96
≈10.2395정확값94367/9216
아래는 고정 range·k=3 첫 시험행의 모든 선택 이웃입니다. 기하 검색은 표적 결측을 허용하지만 이 예측 표는 유효한 훈련 결과가 있는 후보만 씁니다. 원행 수와 관찰 가중치·정규화 기여를 구별합니다.
첫 시험 원행 46의 전체 이웃 기여
원행
ID
교육(년)
나이(년)
제곱거리
정규화 무게
훈련 결과
예측 기여
61
107
10
24
≈0.00591716정확값1/169
≈0.0769231정확값1/13
434
≈33.3846정확값434/13
212
325
12
24
≈0.00591716정확값1/169
≈0.0769231정확값1/13
315
≈24.2308정확값315/13
665
980
12
24
≈0.00591716정확값1/169
≈0.0769231정확값1/13
598
46
862
1258
12
24
≈0.00591716정확값1/169
≈0.0769231정확값1/13
230
≈17.6923정확값230/13
877
1277
12
24
≈0.00591716정확값1/169
≈0.0769231정확값1/13
467
≈35.9231정확값467/13
1058
1574
12
24
≈0.00591716정확값1/169
≈0.0769231정확값1/13
365
≈28.0769정확값365/13
1935
2764
12
24
≈0.00591716정확값1/169
≈0.0769231정확값1/13
397
≈30.5385정확값397/13
1995
2853
12
24
≈0.00591716정확값1/169
≈0.0769231정확값1/13
457
≈35.1538정확값457/13
2131
3047
12
24
≈0.00591716정확값1/169
≈0.0769231정확값1/13
400
≈30.7692정확값400/13
2147
3074
12
24
≈0.00591716정확값1/169
≈0.0769231정확값1/13
900
≈69.2308정확값900/13
2177
3117
10
24
≈0.00591716정확값1/169
≈0.0769231정확값1/13
301
≈23.1538정확값301/13
3295
4774
10
24
≈0.00591716정확값1/169
≈0.0769231정확값1/13
417
≈32.0769정확값417/13
3522
5084
12
24
≈0.00591716정확값1/169
≈0.0769231정확값1/13
383
≈29.4615정확값383/13
CV 선택 후 재학습한 모든 시험 입력·예측·관측·손실
원행
ID
교육(년)
나이(년)
관측结果
예측
MSE
실제 이웃
평가 프레임
46
79
11
24
235
≈435.692정확값5664/13
≈40277.4정확값6806881/169
13
평가 포함
106
176
15
28
350
≈608.5정확값1217/2
≈66822.2정확값267289/4
6
평가 포함
167
265
16
26
462
≈560.667정확값1682/3
≈9735.11정확값87616/9
6
평가 포함
227
346
13
28
278
556
77284
8
평가 포함
288
423
15
27
500
≈513.2정확값2566/5
≈174.24정확값4356/25
5
평가 포함
348
508
12
28
625
≈545.833정확값3275/6
≈6267.36정확값225625/36
6
평가 포함
409
601
12
29
344
≈635.4정확값3177/5
≈84914정확값2122849/25
5
평가 포함
469
705
15
34
2244
≈711.5정확값1423/2
≈2.34856e+06정확값9394225/4
8
평가 포함
529
802
18
32
641
≈969.4정확값4847/5
≈107847정확값2696164/25
5
평가 포함
590
888
12
27
325
≈560.6정확값2803/5
≈55507.4정확값1387684/25
5
평가 포함
650
964
16
29
관측/평가 값 없음
≈538.286정확값3768/7
관측/평가 값 없음
7
결과 결측·평가 제외
711
1041
16
26
400
≈560.667정확값1682/3
≈25813.8정확값232324/9
6
평가 포함
771
1121
14
27
712
≈454.167정확값2725/6
≈66478정확값2393209/36
6
평가 포함
832
1209
12
27
404
≈560.6정확값2803/5
≈24523.6정확값613089/25
5
평가 포함
892
1305
16
28
769
≈630.333정확값1891/3
≈19228.4정확값173056/9
6
평가 포함
953
1422
11
24
641
≈435.692정확값5664/13
≈42151.2정확값7123561/169
13
평가 포함
1013
1514
14
34
722
≈637.182정확값7009/11
≈7194.12정확값870489/121
11
평가 포함
1074
1592
12
33
관측/평가 값 없음
≈660.333정확값1981/3
관측/평가 값 없음
12
결과 결측·평가 제외
1134
1669
12
25
543
482
3721
6
평가 포함
1194
1747
12
26
697
≈497.667정확값1493/3
≈39733.8정확값357604/9
6
평가 포함
1255
1828
14
25
관측/평가 값 없음
≈492.167정확값2953/6
관측/평가 값 없음
12
결과 결측·평가 제외
1315
1904
12
27
604
≈560.6정확값2803/5
≈1883.56정확값47089/25
5
평가 포함
1376
1985
17
33
705
≈894.5정확값1789/2
≈35910.2정확값143641/4
8
평가 포함
1436
2068
18
32
관측/평가 값 없음
≈969.4정확값4847/5
관측/평가 값 없음
5
결과 결측·평가 제외
1497
2150
12
32
630
≈710.6정확값3553/5
≈6496.36정확값162409/25
5
평가 포함
1557
2231
14
33
750
≈676.6정확값3383/5
≈5387.56정확값134689/25
5
평가 포함
1618
2309
12
27
580
≈560.6정확값2803/5
≈376.36정확값9409/25
5
평가 포함
1678
2388
7
27
300
≈411.6정확값2058/5
≈12454.6정확값311364/25
5
평가 포함
1738
2480
12
31
245
639
155236
10
평가 포함
1799
2561
16
28
598
≈630.333정확값1891/3
≈1045.44정확값9409/9
6
평가 포함
1859
2642
14
32
876
≈734.111정확값6607/9
≈20132.5정확값1630729/81
9
평가 포함
1920
2744
12
25
750
482
71824
6
평가 포함
1980
2832
12
24
400
≈451.2정확값2256/5
≈2621.44정확값65536/25
10
평가 포함
2041
2922
13
27
560
520
1600
7
평가 포함
2101
2999
12
28
255
≈545.833정확값3275/6
≈84584정확값3045025/36
6
평가 포함
2162
3097
16
27
606
≈588.429정확값4119/7
≈308.755정확값15129/49
14
평가 포함
2222
3185
11
27
225
≈516.059정확값8773/17
≈84715.2정확값24482704/289
17
평가 포함
2283
3269
12
26
250
≈497.667정확값1493/3
≈61338.8정확값552049/9
6
평가 포함
2343
3356
16
31
875
754
14641
5
평가 포함
2403
3444
12
30
587
≈613.1정확값6131/10
≈681.21정확값68121/100
10
평가 포함
2464
3522
14
24
230
≈526.8정확값2634/5
≈88090.2정확값2202256/25
5
평가 포함
2524
3605
13
26
707
≈550.6정확값2753/5
≈24461정확값611524/25
5
평가 포함
2585
3717
12
25
713
482
53361
6
평가 포함
2645
3808
12
24
관측/평가 값 없음
≈451.2정확값2256/5
관측/평가 값 없음
10
결과 결측·평가 제외
2706
3902
12
24
666
≈451.2정확값2256/5
≈46139정확값1153476/25
10
평가 포함
2766
3997
16
34
577
≈706.714정확값4947/7
≈16825.8정확값824464/49
7
평가 포함
2827
4094
16
27
647
≈588.429정확값4119/7
≈3430.61정확값168100/49
14
평가 포함
2887
4177
12
32
413
≈710.6정확값3553/5
≈88565.8정확값2214144/25
5
평가 포함
2948
4263
13
32
649
≈716.333정확값2149/3
≈4533.78정확값40804/9
6
평가 포함
3008
4355
14
25
601
≈492.167정확값2953/6
≈11844.7정확값426409/36
12
평가 포함
3068
4437
13
26
450
≈550.6정확값2753/5
≈10120.4정확값253009/25
5
평가 포함
3129
4522
9
29
398
≈434.6정확값2173/5
≈1339.56정확값33489/25
5
평가 포함
3189
4623
10
24
260
≈427.429정확값2992/7
≈28032.3정확값1373584/49
7
평가 포함
3250
4712
12
25
419
482
3969
6
평가 포함
3310
4792
12
24
관측/평가 값 없음
≈451.2정확값2256/5
관측/평가 값 없음
10
결과 결측·평가 제외
3371
4881
13
26
641
≈550.6정확값2753/5
≈8172.16정확값204304/25
5
평가 포함
3431
4958
6
34
관측/평가 값 없음
356
관측/평가 값 없음
5
결과 결측·평가 제외
3492
5039
7
30
450
≈429.6정확값2148/5
≈416.16정확값10404/25
5
평가 포함
3552
5127
18
32
관측/평가 값 없음
≈969.4정확값4847/5
관측/평가 값 없음
5
결과 결측·평가 제외
3613
5225
13
26
525
≈550.6정확값2753/5
≈655.36정확값16384/25
5
평가 포함
교육·나이가 정수라 동률이 많습니다. 첫 시험 원행46·ID79에서 고정 k=3은 경계 동률13행을 사용해 5664/13센트/시간을 예측합니다. 관측235센트/시간과 차이가 크며 그 이유를 평균 분모·입력 조합·모형 한계로 살펴봅니다. 교육 한 해의 인과 수익률이나 원 IV 논문 전체 재현으로 부르지 않습니다.
그림의 y는 완전한 실습 선택 원행의 관측 결과입니다. 첫 입력 축에 투영했으므로 다른 입력을 무시한 거리 그림으로 읽지 않습니다. 시험의 예측 점도 관측과 구분하며 점들을 선으로 연결하지 않습니다. 결과가 없는 개인 시험8행의 예측은 위 표에 남기고 관측0점은 만들지 않습니다.
전체 CSV와 코드만 같은 폴더에 두고 독립 실행할 수 있습니다. Python은 정확 분수, R은 정확 정수 limb로 거리 순위를 보존하고 점수는 유한 정밀도로 계산합니다. 원조사 ZIP·JavaScript·개인 작업 파일을 불러오는 코드가 아닙니다.
기업 기록 · 실제 통화 이용과 이탈
UCI Iranian Churn 원본3150행·14개 열을 그대로 보존합니다. 공식 설명에서 입력은 처음9개월의 집계, 이탈은12개월 말 상태입니다. 여기서는 통화 초·횟수·실패 세 입력만 사용하고, 명시한 위치240개를180훈련·60시험으로 나눕니다. 실제 원행 번호는 되찾은 고유 고객 ID가 아니며 같은 입력이 같은 사람이라는 뜻도 아닙니다.
원선택·실습·완전 프레임의 다른 분모
단계
수
원본 보존 행
3150
실습 선택 행
240
훈련/시험 원행
180 / 60
완전 훈련/시험 결과
180 / 60
예측에 사용한 입력 수
3
훈련 첫6행·시험 첫4행 미리보기 · 전체 원행은 CSV
원행
원식별자
역할
통화 초
통화 횟수
실패 횟수
관측结果
1
1
훈련
4370
71
8
0
14
14
훈련
3095
27
4
0
27
27
훈련
2990
41
9
1
53
53
훈련
2513
63
13
0
66
66
훈련
6560
89
6
0
80
80
훈련
1728
28
4
0
40
40
시험
1568
39
4
0
93
93
시험
1285
35
13
0
145
145
시험
1635
23
0
0
198
198
시험
2933
47
9
0
이 미리보기는 결과가 결측인 행도 그대로 남깁니다. 전체 원행·실습 선택·원래 단위는 아래 CSV에서 추적할 수 있습니다. 새 시험 행을 훈련 척도에 넣지 않습니다.
CV 선택 행은 훈련 내부에서 1·3·5를 비교해 정한 k를 전체 완전 훈련에 재학습한 절차입니다. 다른 행은 고정 민감도 설정입니다. 여러 시험 수치를 보며 사후 선택한 것을 독립 최종 시험처럼 해석하지 않습니다. Brier는 범주별 제곱오차 합의 절반이며 여기 이진 분류에서는 (p−y)²입니다.
훈련 전용 세 fold의 pooled 검증 손실
k
전체 평가 행
CV Brier
기준
선택
1
180
≈0.22076정확값19471/88200
≈0.123889정확값223/1800
—
3
180
≈0.134488정확값533783/3969000
≈0.123889정확값223/1800
—
5
180
≈0.119511정확값57395033/480249000
≈0.123889정확값223/1800
선택
선택 후보의 fold별 훈련 척도 · 검증 입력 제외
Fold
훈련
검증
입력
최소
최대
평균
분산
0
120
60
통화 초
0
16500
≈4548.1정확값45481/10
≈1.81159e+07정확값5434778507/300
0
120
60
통화 횟수
0
244
≈70.5833정확값847/12
≈3259.93정확값2347147/720
0
120
60
실패 횟수
0
30
≈8.125정확값65/8
≈55.3927정확값53177/960
1
120
60
통화 초
0
16380
≈4456.63정확값133699/30
≈1.81631e+07정확값16346757539/900
1
120
60
통화 횟수
0
244
≈70.4917정확값8459/120
≈3306.72정확값47616719/14400
1
120
60
실패 횟수
0
30
≈7.63333정확값229/30
≈49.1656정확값44249/900
2
120
60
통화 초
0
16500
≈4005.63정확값120169/30
≈1.54902e+07정확값13941199229/900
2
120
60
통화 횟수
0
238
≈62.5917정확값7511/120
≈2887.96정확값41586599/14400
2
120
60
실패 횟수
0
29
≈7.375정확값59/8
≈47.7677정확값45857/960
아래는 고정 range·k=3 첫 시험행의 모든 선택 이웃입니다. 기하 검색은 표적 결측을 허용하지만 이 예측 표는 유효한 훈련 결과가 있는 후보만 씁니다. 원행 수와 관찰 가중치·정규화 기여를 구별합니다.
첫 시험 원행 40의 전체 이웃 기여
원행
ID
통화 초
통화 횟수
실패 횟수
제곱거리
정규화 무게
훈련 결과
이탈비율 기여
528
528
1668
34
5
≈0.00156776정확값101645/64834704
≈0.333333정확값1/3
1
≈0.333333정확값1/3
80
80
1728
28
4
≈0.00212641정확값86165929/40521690000
≈0.333333정확값1/3
0
0
607
607
2245
33
4
≈0.00228816정확값2318004709/1013042250000
≈0.333333정확값1/3
0
0
CV 선택 후 재학습한 모든 시험 입력·예측·관측·손실
원행
ID
통화 초
통화 횟수
실패 횟수
관측结果
이탈확률
Brier
실제 이웃
평가 프레임
40
40
1568
39
4
0
≈0.2정확값1/5
≈0.04정확값1/25
5
평가 포함
93
93
1285
35
13
0
≈0.2정확값1/5
≈0.04정확값1/25
5
평가 포함
145
145
1635
23
0
0
≈0.4정확값2/5
≈0.16정확값4/25
5
평가 포함
198
198
2933
47
9
0
≈0.4정확값2/5
≈0.16정확값4/25
5
평가 포함
251
251
4630
81
13
0
≈0.2정확값1/5
≈0.04정확값1/25
5
평가 포함
304
304
3938
56
5
0
0
0
5
평가 포함
356
356
3955
90
13
0
0
0
5
평가 포함
409
409
13593
161
5
0
0
0
5
평가 포함
462
462
2838
64
13
0
≈0.2정확값1/5
≈0.04정확값1/25
5
평가 포함
514
514
2495
17
0
0
≈0.2정확값1/5
≈0.04정확값1/25
5
평가 포함
567
567
990
20
0
0
≈0.2정확값1/5
≈0.04정확값1/25
5
평가 포함
620
620
7393
121
3
0
0
0
5
평가 포함
672
672
6908
76
10
0
≈0.2정확값1/5
≈0.04정확값1/25
5
평가 포함
725
725
5628
97
11
1
≈0.2정확값1/5
≈0.64정확값16/25
5
평가 포함
778
778
2268
38
7
1
0
1
5
평가 포함
831
831
6785
103
5
0
0
0
5
평가 포함
883
883
1048
15
6
0
0
0
5
평가 포함
936
936
3008
71
0
0
0
0
5
평가 포함
989
989
1315
36
4
1
≈0.2정확값1/5
≈0.64정확값16/25
5
평가 포함
1041
1041
700
25
11
0
0
0
5
평가 포함
1094
1094
2920
55
0
0
0
0
5
평가 포함
1147
1147
8688
168
10
0
0
0
5
평가 포함
1199
1199
4025
31
0
0
≈0.2정확값1/5
≈0.04정확값1/25
5
평가 포함
1252
1252
0
0
0
0
≈0.5정확값1/2
≈0.25정확값1/4
10
평가 포함
1305
1305
2348
62
3
0
0
0
5
평가 포함
1358
1358
8550
105
3
0
0
0
5
평가 포함
1410
1410
4390
85
4
0
0
0
5
평가 포함
1463
1463
14655
211
18
0
0
0
5
평가 포함
1516
1516
6795
90
2
0
0
0
5
평가 포함
1568
1568
0
0
0
0
≈0.5정확값1/2
≈0.25정확값1/4
10
평가 포함
1621
1621
11275
154
2
0
0
0
5
평가 포함
1674
1674
10015
81
16
0
0
0
5
평가 포함
1727
1727
2875
36
6
1
0
1
5
평가 포함
1779
1779
0
0
0
1
≈0.5정확값1/2
≈0.25정확값1/4
10
평가 포함
1832
1832
0
0
0
1
≈0.5정확값1/2
≈0.25정확값1/4
10
평가 포함
1885
1885
6660
116
3
0
0
0
5
평가 포함
1937
1937
2070
49
4
0
0
0
5
평가 포함
1990
1990
553
22
0
0
≈0.2정확값1/5
≈0.04정확값1/25
5
평가 포함
2043
2043
920
26
5
0
≈0.2정확값1/5
≈0.04정확값1/25
5
평가 포함
2095
2095
1390
20
0
0
≈0.2정확값1/5
≈0.04정확값1/25
5
평가 포함
2148
2148
3158
51
13
0
≈0.4정확값2/5
≈0.16정확값4/25
5
평가 포함
2201
2201
4615
74
10
0
0
0
5
평가 포함
2254
2254
4583
74
16
0
0
0
5
평가 포함
2306
2306
4000
86
15
0
0
0
5
평가 포함
2359
2359
14338
185
17
0
0
0
5
평가 포함
2412
2412
2283
50
9
0
≈0.4정확값2/5
≈0.16정확값4/25
5
평가 포함
2464
2464
3580
41
11
0
≈0.4정확값2/5
≈0.16정확값4/25
5
평가 포함
2517
2517
1000
12
5
0
≈0.2정확값1/5
≈0.04정확값1/25
5
평가 포함
2570
2570
8413
143
12
0
0
0
5
평가 포함
2622
2622
6423
71
9
0
0
0
5
평가 포함
2675
2675
6238
110
18
0
0
0
5
평가 포함
2728
2728
2458
44
14
1
≈0.2정확값1/5
≈0.64정확값16/25
5
평가 포함
2781
2781
7280
104
10
0
0
0
5
평가 포함
2833
2833
453
9
3
0
≈0.2정확값1/5
≈0.04정확값1/25
5
평가 포함
2886
2886
4023
82
5
0
0
0
5
평가 포함
2939
2939
1620
48
11
0
≈0.2정확값1/5
≈0.04정확값1/25
5
평가 포함
2991
2991
1715
42
22
1
≈0.6정확값3/5
≈0.16정확값4/25
5
평가 포함
3044
3044
2820
56
1
0
0
0
5
평가 포함
3097
3097
9237
177
17
0
0
0
5
평가 포함
3150
3150
1792
25
8
1
0
1
5
평가 포함
확률과 범주 행동을 함께 읽습니다. 첫 시험 원행40은 비이탈이고 고정 k=3의 이탈 확률1/3은 범주를 맞혀도 Brier가0은 아닙니다. 훈련 CV는5를 고르므로 고정3의 결과와 CV 선택·재학습한 결과를 구별합니다. 예측 확률이 고객에게 연락했을 때의 이탈 방지 효과를 알려 주지는 않습니다.
그림의 y는 완전한 실습 선택 원행의 관측 결과입니다. 첫 입력 축에 투영했으므로 다른 입력을 무시한 거리 그림으로 읽지 않습니다. 시험의 예측 점도 관측과 구분하며 점들을 선으로 연결하지 않습니다.
전체 CSV와 코드만 같은 폴더에 두고 독립 실행할 수 있습니다. Python은 정확 분수, R은 정확 정수 limb로 거리 순위를 보존하고 점수는 유한 정밀도로 계산합니다. 원조사 ZIP·JavaScript·개인 작업 파일을 불러오는 코드가 아닙니다.
The three cases connect complete actual source records with the selected positions, units and roles used in the lab. Their targets differ, so score magnitudes do not rank which domain is easier. Authentic records do not imply identical research designs. Full downloads preserve source rows while main tables and graphs remain readable in the chapter.
Follow one test row from original features through training-only scales, distances, boundary ties, normalized weights, prediction, observed outcome and loss. Do not merge rows or alter outcomes merely because names or identifiers appear similar. Explain selected counts larger than requested k, comparing stable selection when useful.
Then inspect the complete evaluable frame and baseline. Distinguish fixed sensitivity profiles from settings chosen by training CV, and read failures alongside improvements. Exact disclosures, standalone Python/R and official sources establish traceability, not automatic grounds for policy, personal or business interventions.
Country records · Actual national indicators
Use 2024 indicators for sixteen retained countries from the original World Bank response. Inputs are constant 2015 US-dollar GDP per capita and unemployment; the outcome is period life expectancy, not eventual lifespans observed for all newborns. The first twelve codes train and the last four test. This is not a random global sample or population-weighted world average.
Original, selected and complete-frame denominators
Stage
Count
Preserved original rows
16
Selected lab rows
16
Training/test source rows
12 / 4
Complete training/test targets
12 / 4
Predictor count
2
All sixteen original country values
Source row
Source ID
Role
GDP/person, constant 2015 US$
Unemployment (%)
Observed outcome
1
AUS
Training
≈61486.4Exact value768579768443/12500000
≈3.942Exact value1971/500
≈83.0512Exact value830512195121951/10000000000000
2
BRA
Training
≈9566.75Exact value956674518687619/100000000000
≈6.801Exact value6801/1000
≈76.023Exact value76023/1000
3
CAN
Training
≈45061.4Exact value90122772917457/2000000000
≈6.351Exact value6351/1000
≈82.108Exact value410540243902439/5000000000000
4
CHN
Training
≈13119.1Exact value32797769024879/2500000000
≈4.59Exact value459/100
≈78.017Exact value78017/1000
5
DEU
Training
≈44027.8Exact value440277631554469/10000000000
≈3.4Exact value17/5
≈80.7927Exact value807926829268293/10000000000000
6
FRA
Training
≈39683.4Exact value396833953489029/10000000000
≈7.4Exact value37/5
≈82.9805Exact value829804878048781/10000000000000
7
GBR
Training
≈47901Exact value239504840072073/5000000000
≈4.361Exact value4361/1000
≈81.3869Exact value406934268292683/5000000000000
8
IDN
Training
≈4367.95Exact value218397370923969/50000000000
≈3.301Exact value3301/1000
≈71.288Exact value8911/125
9
IND
Training
≈2366.83Exact value23668328910323/10000000000
≈4.173Exact value4173/1000
≈72.235Exact value14447/200
10
JPN
Training
≈37976.6Exact value189883185894149/5000000000
≈2.5Exact value5/2
≈84.0363Exact value420181707317073/5000000000000
11
KOR
Training
≈37048.4Exact value46310533000187/1250000000
≈2.784Exact value348/125
≈83.6293Exact value836292682926829/10000000000000
12
MEX
Training
≈10284Exact value51420168462863/5000000000
≈2.678Exact value1339/500
≈75.264Exact value9408/125
13
SGP
Test
≈68129.7Exact value42581060025143/625000000
≈2.737Exact value2737/1000
≈83.3463Exact value416731707317073/5000000000000
14
USA
Test
≈66856.5Exact value668565131698371/10000000000
≈4.022Exact value2011/500
≈78.8902Exact value78890243902439/1000000000000
15
VNM
Test
≈4012.51Exact value100312694980271/25000000000
≈1.602Exact value801/500
≈74.736Exact value9342/125
16
ZAF
Test
≈5715.48Exact value142886882867287/25000000000
≈32.279Exact value32279/1000
≈66.312Exact value8289/125
The preview retains missing targets. Complete source rows, selection and original units remain traceable in the CSVs. Test inputs are excluded from fitted training scales.
Scales fitted on complete labeled training rows only
The CV-selected row refits the training-selected k after comparing 1,3,5 within development folds; other rows are fixed sensitivity profiles. Post-hoc test-based selection is not an independent final test. For life expectancy, MSE has units of years squared and MAE years. Compare neighbour predictions and the training-mean baseline on the same test rows.
Pooled validation loss across three training-only folds
Below are all selected neighbours of the first test row under fixed range-scaled k=3. Pure geometry may use unlabeled inputs, but this prediction table uses labeled training candidates. Distinguish source counts from normalized contributions.
Complete neighbour contributions for first test source row 13
Development CV selects k=3, but four-country test MSE exceeds the training-mean baseline. Some test inputs lie outside training GDP or unemployment ranges. Retain this failure rather than claiming an income or unemployment-policy effect.
The observed y series contains complete selected lab records. Its first-feature projection is not the full multivariate distance geometry. Test predictions are distinguished from observations and points are not joined.
The code runs with public CSVs in the bundle. Python uses exact fractions; R preserves distance ranks with exact integer limbs while calculating scores in finite precision. Execution needs neither original archives, development-only helpers nor JavaScript.
Individual records · Raw wages, schooling and age
Read the released Card ZIP and original codebook, preserving 3,613 NLS young-men records and all 52 fixed-width fields. Predict 1976 raw wage76 in cents per hour from schooling and age. Trimmed log wages, later wages and original sampling weights remain preserved but are not substituted as predictors or targets. A declared evenly spaced position rule selects 240 rows, assigning 180 to training and 60 to testing; labeled complete counts are 145 and 52.
Original, selected and complete-frame denominators
Stage
Count
Preserved original rows
3613
Selected lab rows
240
Training/test source rows
180 / 60
Complete training/test targets
145 / 52
Predictor count
2
Preview: first six training and four test records; full rows in CSV
Source row
Source ID
Role
Schooling (years)
Age (years)
Observed outcome
1
2
Training
7
29
548
16
17
Training
14
24
300
31
37
Training
18
32
1800
61
107
Training
10
24
434
76
133
Training
18
24
693
91
153
Training
12
26
No observed/scored value
46
79
Test
11
24
235
106
176
Test
15
28
350
167
265
Test
16
26
462
227
346
Test
13
28
278
The preview retains missing targets. Complete source rows, selection and original units remain traceable in the CSVs. Test inputs are excluded from fitted training scales.
Scales fitted on complete labeled training rows only
The CV-selected row refits the training-selected k after comparing 1,3,5 within development folds; other rows are fixed sensitivity profiles. Post-hoc test-based selection is not an independent final test. For raw wages, MSE has units of (cents/hour) squared and MAE cents/hour. Do not confuse these with dollar-unit errors or churn-probability loss.
Pooled validation loss across three training-only folds
k
Scored rows
CV MSE
Baseline
Selection
1
145
≈122082Exact value3122615580761/25578000
≈77759.1Exact value15886019000126761/204297937920
—
3
145
≈69500.2Exact value395038867213/5684000
≈77759.1Exact value15886019000126761/204297937920
—
5
145
≈64657.1Exact value7246826115406037/112080969000
≈77759.1Exact value15886019000126761/204297937920
Selected
Fold-specific scales for the selected candidate; validation inputs excluded
Fold
Training
Validation
Feature
Minimum
Maximum
Mean
Variance
0
102
43
Schooling (years)
5
18
≈13.3824Exact value455/34
≈7.05969Exact value8161/1156
0
102
43
Age (years)
24
34
≈28.2549Exact value1441/51
≈10.0527Exact value26147/2601
1
92
53
Schooling (years)
5
18
≈13.2391Exact value609/46
≈7.35586Exact value15565/2116
1
92
53
Age (years)
24
34
≈27.7283Exact value2551/92
≈8.93703Exact value75643/8464
2
96
49
Schooling (years)
7
18
≈13.2396Exact value1271/96
≈7.43218Exact value68495/9216
2
96
49
Age (years)
24
34
≈27.6771Exact value2657/96
≈10.2395Exact value94367/9216
Below are all selected neighbours of the first test row under fixed range-scaled k=3. Pure geometry may use unlabeled inputs, but this prediction table uses labeled training candidates. Distinguish source counts from normalized contributions.
Complete neighbour contributions for first test source row 46
Source row
ID
Schooling (years)
Age (years)
Squared distance
Normalized weight
Training outcome
Prediction contribution
61
107
10
24
≈0.00591716Exact value1/169
≈0.0769231Exact value1/13
434
≈33.3846Exact value434/13
212
325
12
24
≈0.00591716Exact value1/169
≈0.0769231Exact value1/13
315
≈24.2308Exact value315/13
665
980
12
24
≈0.00591716Exact value1/169
≈0.0769231Exact value1/13
598
46
862
1258
12
24
≈0.00591716Exact value1/169
≈0.0769231Exact value1/13
230
≈17.6923Exact value230/13
877
1277
12
24
≈0.00591716Exact value1/169
≈0.0769231Exact value1/13
467
≈35.9231Exact value467/13
1058
1574
12
24
≈0.00591716Exact value1/169
≈0.0769231Exact value1/13
365
≈28.0769Exact value365/13
1935
2764
12
24
≈0.00591716Exact value1/169
≈0.0769231Exact value1/13
397
≈30.5385Exact value397/13
1995
2853
12
24
≈0.00591716Exact value1/169
≈0.0769231Exact value1/13
457
≈35.1538Exact value457/13
2131
3047
12
24
≈0.00591716Exact value1/169
≈0.0769231Exact value1/13
400
≈30.7692Exact value400/13
2147
3074
12
24
≈0.00591716Exact value1/169
≈0.0769231Exact value1/13
900
≈69.2308Exact value900/13
2177
3117
10
24
≈0.00591716Exact value1/169
≈0.0769231Exact value1/13
301
≈23.1538Exact value301/13
3295
4774
10
24
≈0.00591716Exact value1/169
≈0.0769231Exact value1/13
417
≈32.0769Exact value417/13
3522
5084
12
24
≈0.00591716Exact value1/169
≈0.0769231Exact value1/13
383
≈29.4615Exact value383/13
All test inputs, refitted CV-selected predictions, observations and losses
Source row
ID
Schooling (years)
Age (years)
Observed outcome
Prediction
MSE
Selected rows
Scoring frame
46
79
11
24
235
≈435.692Exact value5664/13
≈40277.4Exact value6806881/169
13
Scored
106
176
15
28
350
≈608.5Exact value1217/2
≈66822.2Exact value267289/4
6
Scored
167
265
16
26
462
≈560.667Exact value1682/3
≈9735.11Exact value87616/9
6
Scored
227
346
13
28
278
556
77284
8
Scored
288
423
15
27
500
≈513.2Exact value2566/5
≈174.24Exact value4356/25
5
Scored
348
508
12
28
625
≈545.833Exact value3275/6
≈6267.36Exact value225625/36
6
Scored
409
601
12
29
344
≈635.4Exact value3177/5
≈84914Exact value2122849/25
5
Scored
469
705
15
34
2244
≈711.5Exact value1423/2
≈2.34856e+06Exact value9394225/4
8
Scored
529
802
18
32
641
≈969.4Exact value4847/5
≈107847Exact value2696164/25
5
Scored
590
888
12
27
325
≈560.6Exact value2803/5
≈55507.4Exact value1387684/25
5
Scored
650
964
16
29
No observed/scored value
≈538.286Exact value3768/7
No observed/scored value
7
Missing target; unscored
711
1041
16
26
400
≈560.667Exact value1682/3
≈25813.8Exact value232324/9
6
Scored
771
1121
14
27
712
≈454.167Exact value2725/6
≈66478Exact value2393209/36
6
Scored
832
1209
12
27
404
≈560.6Exact value2803/5
≈24523.6Exact value613089/25
5
Scored
892
1305
16
28
769
≈630.333Exact value1891/3
≈19228.4Exact value173056/9
6
Scored
953
1422
11
24
641
≈435.692Exact value5664/13
≈42151.2Exact value7123561/169
13
Scored
1013
1514
14
34
722
≈637.182Exact value7009/11
≈7194.12Exact value870489/121
11
Scored
1074
1592
12
33
No observed/scored value
≈660.333Exact value1981/3
No observed/scored value
12
Missing target; unscored
1134
1669
12
25
543
482
3721
6
Scored
1194
1747
12
26
697
≈497.667Exact value1493/3
≈39733.8Exact value357604/9
6
Scored
1255
1828
14
25
No observed/scored value
≈492.167Exact value2953/6
No observed/scored value
12
Missing target; unscored
1315
1904
12
27
604
≈560.6Exact value2803/5
≈1883.56Exact value47089/25
5
Scored
1376
1985
17
33
705
≈894.5Exact value1789/2
≈35910.2Exact value143641/4
8
Scored
1436
2068
18
32
No observed/scored value
≈969.4Exact value4847/5
No observed/scored value
5
Missing target; unscored
1497
2150
12
32
630
≈710.6Exact value3553/5
≈6496.36Exact value162409/25
5
Scored
1557
2231
14
33
750
≈676.6Exact value3383/5
≈5387.56Exact value134689/25
5
Scored
1618
2309
12
27
580
≈560.6Exact value2803/5
≈376.36Exact value9409/25
5
Scored
1678
2388
7
27
300
≈411.6Exact value2058/5
≈12454.6Exact value311364/25
5
Scored
1738
2480
12
31
245
639
155236
10
Scored
1799
2561
16
28
598
≈630.333Exact value1891/3
≈1045.44Exact value9409/9
6
Scored
1859
2642
14
32
876
≈734.111Exact value6607/9
≈20132.5Exact value1630729/81
9
Scored
1920
2744
12
25
750
482
71824
6
Scored
1980
2832
12
24
400
≈451.2Exact value2256/5
≈2621.44Exact value65536/25
10
Scored
2041
2922
13
27
560
520
1600
7
Scored
2101
2999
12
28
255
≈545.833Exact value3275/6
≈84584Exact value3045025/36
6
Scored
2162
3097
16
27
606
≈588.429Exact value4119/7
≈308.755Exact value15129/49
14
Scored
2222
3185
11
27
225
≈516.059Exact value8773/17
≈84715.2Exact value24482704/289
17
Scored
2283
3269
12
26
250
≈497.667Exact value1493/3
≈61338.8Exact value552049/9
6
Scored
2343
3356
16
31
875
754
14641
5
Scored
2403
3444
12
30
587
≈613.1Exact value6131/10
≈681.21Exact value68121/100
10
Scored
2464
3522
14
24
230
≈526.8Exact value2634/5
≈88090.2Exact value2202256/25
5
Scored
2524
3605
13
26
707
≈550.6Exact value2753/5
≈24461Exact value611524/25
5
Scored
2585
3717
12
25
713
482
53361
6
Scored
2645
3808
12
24
No observed/scored value
≈451.2Exact value2256/5
No observed/scored value
10
Missing target; unscored
2706
3902
12
24
666
≈451.2Exact value2256/5
≈46139Exact value1153476/25
10
Scored
2766
3997
16
34
577
≈706.714Exact value4947/7
≈16825.8Exact value824464/49
7
Scored
2827
4094
16
27
647
≈588.429Exact value4119/7
≈3430.61Exact value168100/49
14
Scored
2887
4177
12
32
413
≈710.6Exact value3553/5
≈88565.8Exact value2214144/25
5
Scored
2948
4263
13
32
649
≈716.333Exact value2149/3
≈4533.78Exact value40804/9
6
Scored
3008
4355
14
25
601
≈492.167Exact value2953/6
≈11844.7Exact value426409/36
12
Scored
3068
4437
13
26
450
≈550.6Exact value2753/5
≈10120.4Exact value253009/25
5
Scored
3129
4522
9
29
398
≈434.6Exact value2173/5
≈1339.56Exact value33489/25
5
Scored
3189
4623
10
24
260
≈427.429Exact value2992/7
≈28032.3Exact value1373584/49
7
Scored
3250
4712
12
25
419
482
3969
6
Scored
3310
4792
12
24
No observed/scored value
≈451.2Exact value2256/5
No observed/scored value
10
Missing target; unscored
3371
4881
13
26
641
≈550.6Exact value2753/5
≈8172.16Exact value204304/25
5
Scored
3431
4958
6
34
No observed/scored value
356
No observed/scored value
5
Missing target; unscored
3492
5039
7
30
450
≈429.6Exact value2148/5
≈416.16Exact value10404/25
5
Scored
3552
5127
18
32
No observed/scored value
≈969.4Exact value4847/5
No observed/scored value
5
Missing target; unscored
3613
5225
13
26
525
≈550.6Exact value2753/5
≈655.36Exact value16384/25
5
Scored
Integer schooling and age generate many ties. For test source row 46, ID 79, fixed k=3 includes thirteen boundary-tied rows and predicts 5664/13 cents per hour against observed 235. Inspect the denominator, features and limitations rather than calling this an education return or a replication of the original IV paper.
The observed y series contains complete selected lab records. Its first-feature projection is not the full multivariate distance geometry. Test predictions are distinguished from observations and points are not joined. The eight missing individual test outcomes retain predictions in the table without fabricated observed zeros.
The code runs with public CSVs in the bundle. Python uses exact fractions; R preserves distance ranks with exact integer limbs while calculating scores in finite precision. Execution needs neither original archives, development-only helpers nor JavaScript.
Business records · Actual telecom usage and churn
Preserve all 3,150 rows and 14 fields in the original UCI Iranian Churn CSV. Documentation describes first-nine-month inputs and churn at the end of twelve months. We use seconds, frequency and failed calls, with 240 declared positions split 180/60. Source positions do not recover unique customer identities; identical features need not indicate the same person.
Original, selected and complete-frame denominators
Stage
Count
Preserved original rows
3150
Selected lab rows
240
Training/test source rows
180 / 60
Complete training/test targets
180 / 60
Predictor count
3
Preview: first six training and four test records; full rows in CSV
Source row
Source ID
Role
Seconds of use
Call frequency
Failed calls
Observed outcome
1
1
Training
4370
71
8
0
14
14
Training
3095
27
4
0
27
27
Training
2990
41
9
1
53
53
Training
2513
63
13
0
66
66
Training
6560
89
6
0
80
80
Training
1728
28
4
0
40
40
Test
1568
39
4
0
93
93
Test
1285
35
13
0
145
145
Test
1635
23
0
0
198
198
Test
2933
47
9
0
The preview retains missing targets. Complete source rows, selection and original units remain traceable in the CSVs. Test inputs are excluded from fitted training scales.
Scales fitted on complete labeled training rows only
The CV-selected row refits the training-selected k after comparing 1,3,5 within development folds; other rows are fixed sensitivity profiles. Post-hoc test-based selection is not an independent final test. Brier is half the class-wise squared-error sum, equal to (p−y)² in this binary case.
Pooled validation loss across three training-only folds
k
Scored rows
CV Brier
Baseline
Selection
1
180
≈0.22076Exact value19471/88200
≈0.123889Exact value223/1800
—
3
180
≈0.134488Exact value533783/3969000
≈0.123889Exact value223/1800
—
5
180
≈0.119511Exact value57395033/480249000
≈0.123889Exact value223/1800
Selected
Fold-specific scales for the selected candidate; validation inputs excluded
Fold
Training
Validation
Feature
Minimum
Maximum
Mean
Variance
0
120
60
Seconds of use
0
16500
≈4548.1Exact value45481/10
≈1.81159e+07Exact value5434778507/300
0
120
60
Call frequency
0
244
≈70.5833Exact value847/12
≈3259.93Exact value2347147/720
0
120
60
Failed calls
0
30
≈8.125Exact value65/8
≈55.3927Exact value53177/960
1
120
60
Seconds of use
0
16380
≈4456.63Exact value133699/30
≈1.81631e+07Exact value16346757539/900
1
120
60
Call frequency
0
244
≈70.4917Exact value8459/120
≈3306.72Exact value47616719/14400
1
120
60
Failed calls
0
30
≈7.63333Exact value229/30
≈49.1656Exact value44249/900
2
120
60
Seconds of use
0
16500
≈4005.63Exact value120169/30
≈1.54902e+07Exact value13941199229/900
2
120
60
Call frequency
0
238
≈62.5917Exact value7511/120
≈2887.96Exact value41586599/14400
2
120
60
Failed calls
0
29
≈7.375Exact value59/8
≈47.7677Exact value45857/960
Below are all selected neighbours of the first test row under fixed range-scaled k=3. Pure geometry may use unlabeled inputs, but this prediction table uses labeled training candidates. Distinguish source counts from normalized contributions.
Complete neighbour contributions for first test source row 40
Source row
ID
Seconds of use
Call frequency
Failed calls
Squared distance
Normalized weight
Training outcome
Positive-probability contribution
528
528
1668
34
5
≈0.00156776Exact value101645/64834704
≈0.333333Exact value1/3
1
≈0.333333Exact value1/3
80
80
1728
28
4
≈0.00212641Exact value86165929/40521690000
≈0.333333Exact value1/3
0
0
607
607
2245
33
4
≈0.00228816Exact value2318004709/1013042250000
≈0.333333Exact value1/3
0
0
All test inputs, refitted CV-selected predictions, observations and losses
Source row
ID
Seconds of use
Call frequency
Failed calls
Observed outcome
Positive probability
Brier
Selected rows
Scoring frame
40
40
1568
39
4
0
≈0.2Exact value1/5
≈0.04Exact value1/25
5
Scored
93
93
1285
35
13
0
≈0.2Exact value1/5
≈0.04Exact value1/25
5
Scored
145
145
1635
23
0
0
≈0.4Exact value2/5
≈0.16Exact value4/25
5
Scored
198
198
2933
47
9
0
≈0.4Exact value2/5
≈0.16Exact value4/25
5
Scored
251
251
4630
81
13
0
≈0.2Exact value1/5
≈0.04Exact value1/25
5
Scored
304
304
3938
56
5
0
0
0
5
Scored
356
356
3955
90
13
0
0
0
5
Scored
409
409
13593
161
5
0
0
0
5
Scored
462
462
2838
64
13
0
≈0.2Exact value1/5
≈0.04Exact value1/25
5
Scored
514
514
2495
17
0
0
≈0.2Exact value1/5
≈0.04Exact value1/25
5
Scored
567
567
990
20
0
0
≈0.2Exact value1/5
≈0.04Exact value1/25
5
Scored
620
620
7393
121
3
0
0
0
5
Scored
672
672
6908
76
10
0
≈0.2Exact value1/5
≈0.04Exact value1/25
5
Scored
725
725
5628
97
11
1
≈0.2Exact value1/5
≈0.64Exact value16/25
5
Scored
778
778
2268
38
7
1
0
1
5
Scored
831
831
6785
103
5
0
0
0
5
Scored
883
883
1048
15
6
0
0
0
5
Scored
936
936
3008
71
0
0
0
0
5
Scored
989
989
1315
36
4
1
≈0.2Exact value1/5
≈0.64Exact value16/25
5
Scored
1041
1041
700
25
11
0
0
0
5
Scored
1094
1094
2920
55
0
0
0
0
5
Scored
1147
1147
8688
168
10
0
0
0
5
Scored
1199
1199
4025
31
0
0
≈0.2Exact value1/5
≈0.04Exact value1/25
5
Scored
1252
1252
0
0
0
0
≈0.5Exact value1/2
≈0.25Exact value1/4
10
Scored
1305
1305
2348
62
3
0
0
0
5
Scored
1358
1358
8550
105
3
0
0
0
5
Scored
1410
1410
4390
85
4
0
0
0
5
Scored
1463
1463
14655
211
18
0
0
0
5
Scored
1516
1516
6795
90
2
0
0
0
5
Scored
1568
1568
0
0
0
0
≈0.5Exact value1/2
≈0.25Exact value1/4
10
Scored
1621
1621
11275
154
2
0
0
0
5
Scored
1674
1674
10015
81
16
0
0
0
5
Scored
1727
1727
2875
36
6
1
0
1
5
Scored
1779
1779
0
0
0
1
≈0.5Exact value1/2
≈0.25Exact value1/4
10
Scored
1832
1832
0
0
0
1
≈0.5Exact value1/2
≈0.25Exact value1/4
10
Scored
1885
1885
6660
116
3
0
0
0
5
Scored
1937
1937
2070
49
4
0
0
0
5
Scored
1990
1990
553
22
0
0
≈0.2Exact value1/5
≈0.04Exact value1/25
5
Scored
2043
2043
920
26
5
0
≈0.2Exact value1/5
≈0.04Exact value1/25
5
Scored
2095
2095
1390
20
0
0
≈0.2Exact value1/5
≈0.04Exact value1/25
5
Scored
2148
2148
3158
51
13
0
≈0.4Exact value2/5
≈0.16Exact value4/25
5
Scored
2201
2201
4615
74
10
0
0
0
5
Scored
2254
2254
4583
74
16
0
0
0
5
Scored
2306
2306
4000
86
15
0
0
0
5
Scored
2359
2359
14338
185
17
0
0
0
5
Scored
2412
2412
2283
50
9
0
≈0.4Exact value2/5
≈0.16Exact value4/25
5
Scored
2464
2464
3580
41
11
0
≈0.4Exact value2/5
≈0.16Exact value4/25
5
Scored
2517
2517
1000
12
5
0
≈0.2Exact value1/5
≈0.04Exact value1/25
5
Scored
2570
2570
8413
143
12
0
0
0
5
Scored
2622
2622
6423
71
9
0
0
0
5
Scored
2675
2675
6238
110
18
0
0
0
5
Scored
2728
2728
2458
44
14
1
≈0.2Exact value1/5
≈0.64Exact value16/25
5
Scored
2781
2781
7280
104
10
0
0
0
5
Scored
2833
2833
453
9
3
0
≈0.2Exact value1/5
≈0.04Exact value1/25
5
Scored
2886
2886
4023
82
5
0
0
0
5
Scored
2939
2939
1620
48
11
0
≈0.2Exact value1/5
≈0.04Exact value1/25
5
Scored
2991
2991
1715
42
22
1
≈0.6Exact value3/5
≈0.16Exact value4/25
5
Scored
3044
3044
2820
56
1
0
0
0
5
Scored
3097
3097
9237
177
17
0
0
0
5
Scored
3150
3150
1792
25
8
1
0
1
5
Scored
Read probabilities separately from actions. Test source row 40 is non-churn; fixed k=3 probability 1/3 gives the correct class but nonzero Brier. CV selects five, so distinguish that refitted protocol from fixed-three sensitivity. Churn probability is not the effect of a retention contact.
The observed y series contains complete selected lab records. Its first-feature projection is not the full multivariate distance geometry. Test predictions are distinguished from observations and points are not joined.
The code runs with public CSVs in the bundle. Python uses exact fractions; R preserves distance ranks with exact integer limbs while calculating scores in finite precision. Execution needs neither original archives, development-only helpers nor JavaScript.
학부 심화 · 선택Advanced undergraduate · optional
48. 공식 영상·학자·원자료와 다음 장48. Official videos, researchers, original data and the next chapter
본문의 Stanford Online 최근접 이웃 분류 영상에서는 가까운 사례를 범주 비율로 바꾸는 과정을 살펴보세요. Stanford의 공식 입문 강의와 Dennis Sun의 분류 강의 자료는 이웃 수·전처리 pipeline·분류 확률·평가를 연결할 추가 읽기입니다. 라이브러리의 기본 동률 처리가 이 장의 전체 동률 규칙과 반드시 같다고 가정하지 말고 문서·작은 예로 확인합니다. 확인하지 않은 정확한 영상 시각을 지정하지 않습니다.
Trevor Hastie·Robert Tibshirani의 통계학습 자료를 읽을 때에는 알고리즘 이름을 외우기보다 어떤 손실·표적·표본·평가를 쓰는지 먼저 찾습니다. Charles Stone의 Consistent Nonparametric Regression은 조건부 분포와 기대값을 이웃 가중치로 추정할 때 어떤 일치성 조건이 필요한지 더 공부할 원논문입니다. 이 장의 작은 실험이 그 논문의 모든 정리·전처리 변형을 증명한 것처럼 말하지 않습니다.
실제 사례에서는 World Bank 지표 정의, Card의 원코드북에서 wage76과 lwage76의 차이, UCI 설명의 9개월·12개월 시간을 다시 확인하세요. 같은 임금 자료라도 이번 목표는 예측이고 원 IV 연구의 인과 목표와 다릅니다. 다음 ML07에서는 가까운 점을 평균하는 규칙에서 벗어나 마진·SVM·커널·쌍대 문제로 넘어갑니다. 거리·내적·스케일과 검증을 제대로 익힌 것이 그 연결의 준비입니다.
Use the in-chapter Stanford Online nearest-neighbour classification video to follow how nearby records become class proportions. Official Stanford beginner notes and Dennis Sun’s classification slides connect neighbour counts, preprocessing pipelines, probabilities and evaluation. A library’s tie default need not match this chapter’s all-tie rule; verify it with documentation and a small example. No unverified exact timestamps are prescribed.
When reading statistical-learning materials by Trevor Hastie and Robert Tibshirani, identify losses, targets, samples and evaluation rather than memorizing algorithm names. Charles Stone’s Consistent Nonparametric Regression is an original research reading on conditional-distribution and expectation estimates built from neighbour weights and consistency conditions. Our finite experiments do not prove all its theorems or preprocessing variants.
Revisit World Bank definitions, Card’s distinction between raw wage76 and trimmed log lwage76, and UCI’s nine-month-input/twelve-month-outcome timing. Our wage target is predictive, distinct from the original IV causal question. ML07 moves from local averaging to margins, SVMs, kernels and dual problems, building on the distance, scaling and evaluation foundations developed here.
자료 묶음을 풀고 코드와 실제데이터 폴더를 함께 두세요. 터미널에서 코드 파일이 있는 폴더로 이동해 아래 명령을 실행합니다. 코딩이 처음이라면 손계산과 웹 실습을 먼저 하고, 데이터 사이언스 입문에서 코드를 배운 뒤 돌아와도 됩니다.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.
결과 파일은 각 코드에 지정된 결과 폴더에 저장됩니다. 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.
최근접 이웃 분류를 R로 따라가기Follow nearest-neighbour classification in R
Stanford Online · Statistical Learning 4.R.3
본문에서 재생하고 이웃·범주 비율·예측 범주를 구별합니다. 라이브러리의 동률 기본값을 이 장과 자동으로 같다고 보지 않습니다.Play within the chapter and distinguish neighbours, class proportions and actions. Check the library tie convention rather than assuming ours.
교재 안의 YouTube 플레이어에서 재생합니다. 원영상에서 제공하는 자막은 플레이어의 CC·설정에서 선택할 수 있습니다.Playback stays in this chapter’s YouTube player. Available captions can be selected through CC/settings.
보고 읽은 뒤 답하기Respond after watching/readingk가1이면 실제 사용 행도 반드시1개인가요?Does k=1 always select exactly one row?
생각을 점검하는 해설Check your reasoning
아닙니다. 기본 전체 경계 동률 규칙에서는 여러 행이 들어올 수 있습니다.No. The all-boundary-ties rule can include several records.
Hastie·Tibshirani · 예측과 평가의 언어Hastie and Tibshirani · The language of prediction and evaluation
Stanford Department of Statistics
공식 통계학습 자료와 연구자 소개를 읽고 거리·손실·평가가 서로 다른 선택인 이유를 설명합니다.Use official statistical-learning materials and researcher profiles to explain why metrics, losses and evaluation are different choices.
보고 읽은 뒤 답하기Respond after watching/reading범주를 맞혔으면 Brier도0인가요?Does a correct class imply zero Brier loss?
생각을 점검하는 해설Check your reasoning
아닙니다. 확률 추정과 하나의 범주 행동은 다릅니다.No. Probability estimates differ from a single class action.
Charles Stone · 일치성의 조건 더 읽기Charles Stone · Read further about consistency conditions
Originalpaper, Annals of Statistics 1977
조건부 기대값을 추정하는 가중치와 표본 크기가 커지는 절차의 조건을 더 공부합니다. 이 장의 유한 실험을 보편적 정리의 증명으로 읽지 않습니다.Study weighted conditional estimation and asymptotic conditions further;finite experiments are not a proof of a universal theorem.
보고 읽은 뒤 답하기Respond after watching/reading고정k=1이 언제나 Bayes 위험으로 수렴하나요?Does fixed k=1 always reach Bayes risk?
생각을 점검하는 해설Check your reasoning
아닙니다. 입력과 독립인 확률0.7 표지 예의 오류는0.42로 Bayes0.3과 다릅니다.No. Independent 0.7 positive labels give 1NN error 0.42 versus Bayes 0.3.
Card 원코드북 · 예측과 IV 표적Card source codebook · Prediction versus IV targets
David Card · originalreleasedreplicationdata
원임금·절단한 로그 임금·표본 가중치·결측 기호를 확인하고 원연구의 인과 질문과 이번 예측을 구분합니다.Check raw and trimmed-log wages, weights and missing symbols, distinguishing the original causal question from this prediction exercise.
보고 읽은 뒤 답하기Respond after watching/reading비슷한 교육·나이의 임금 평균이 개인 교육 수익률인가요?Is a wage average among similar people an individual schooling return?
생각을 점검하는 해설Check your reasoning
아닙니다. 처치 변화의 반사실을 이 예측만으로 알아내지 못합니다.No. Prediction alone does not identify that treatment counterfactual.
연습문제 · 계산에서 설명과 증명까지Exercises: calculation, explanation and proof
먼저 혼자 풀고 풀이를 여세요. 숫자와 함께 단위·포함 기준·계산 이유를 확인하세요.Attempt each problem before opening its solution. Check units, inclusion rules and the reason for the calculation.
1. 입력과 예측·관측 결과Inputs, predictions and observed outcomes
가정한 집 점수는1·2·5, 월세는10·14·26이다. 새 집 점수3.5에서 k=2인 같은 무게 최근접 이웃을 고른다. 거리·선택 행·예측을 계산하고 새 집의 실제 월세를 관측했는지 설명하라.
Assumed input scores are 1,2,5 and rents 10,14,26. At query 3.5, choose two nearest records with equal weights. Give distances, selected records and prediction. Is the new rent observed?
풀이와 확인할 이유Solution and explanation
거리는2.5·1.5·1.5다. 두 최소 거리는 점수2·5라 결과14·26을 평균하여20을 예측한다. 경계 동률 두 행이 모두 들어오므로 기본 규칙에서도 실제 두 행이다.20은 계산한 예측이며 새 집의 실제 월세는 문제에서 주어지지 않았다.
Distances are 2.5,1.5,1.5. Inputs two and five contribute outcomes 14 and 26, predicting 20. Both boundary-tied rows fit within k=2. The number 20 is a prediction; the actual new rent has not been supplied.
2. 결과 단위를 확률로 바꾸지 않기Do not turn outcome units into probabilities
어떤 이웃 모형이 임금435.69센트/시간을 예측했다. 이 수를43.569%의 취업 확률이나435.69달러/시간이라고 읽을 수 있는가? 결과가 이진 이탈0/1인 모형의 평균과 비교하라.
A neighbour model predicts wage 435.69 cents per hour. Can this be read as 43.569 percent employment probability or 435.69 dollars per hour? Compare with averaging binary churn labels.
풀이와 확인할 이유Solution and explanation
임금 예측 단위는 센트/시간이다. 달러로는4.3569달러/시간이지435.69달러가 아니며 취업 확률도 아니다.0/1 이탈 표지의 정규화 평균은 이탈의 경험 비율로 해석할 수 있지만 실제 임금의 평균을 그런 확률로 바꾸어 읽지 않는다.
The wage prediction is in cents per hour, equal to 4.3569 dollars per hour, not 435.69 dollars or a probability. A normalized mean of binary labels estimates a local empirical proportion; a numerical wage mean has a different interpretation.
3. 분수의 거리Distances between fractions
수직선의 a=1/3,b=5/6에 대해 거리와 거리 제곱을 구하라. b−a와 a−b의 부호가 다른데 거리가 같은 이유는?
For a=1/3 and b=5/6, find distance and squared distance. Why is distance symmetric although a−b and b−a differ in sign?
풀이와 확인할 이유Solution and explanation
공통 분모6으로 쓰면 a−b=2/6−5/6=−1/2이다. 절댓값 거리는1/2, 제곱거리는1/4다. 순서를 바꾸면 차이의 부호만 바뀌고 절댓값과 제곱은 유지된다.
31−65=21,d2=41
The difference a−b is−1/2 after using denominator six. Absolute distance is 1/2 and squared distance 1/4. Reversing order changes the sign of a difference but not its absolute value or square.
31−65=21,d2=41
4. 피타고라스와 세 비교값Pythagoras and three dissimilarities
수직선0·1·2에서 제곱 유클리드가 metric의 삼각부등식을 만족하는지 확인하라. 그렇지 않으면 이웃 순위에도 못 쓰는가?
At line coordinates 0,1,2, test the triangle inequality for squared Euclidean distance. Does failure make it unusable for neighbour ranking?
풀이와 확인할 이유Solution and explanation
직접 제곱거리는4, 중간1을 거친 두 제곱거리 합은1+1=2라4≤2가 성립하지 않는다. 따라서 제곱거리는 보통 metric이 아니다. 하지만 제곱근이 증가함수라 한 질의에서 유클리드와 같은 가까운 순서를 줄 수 있다.
The direct squared distance is four and the two-part sum two, violating 4≤2. Squared distance is not an ordinary metric. It still preserves Euclidean neighbour order because the square root is increasing.
6. 거리 선택으로 달라지는 첫 이웃Different metrics select different neighbours
질의(0,0), 후보A=(3,0),B=(2,2)다. 세 가지 API 거리의 값을 비교하고 첫 이웃을 정하라. 결과 y를 볼 필요가 있는가?
For query(0,0), candidates A=(3,0), B=(2,2), compare all three API distances and choose a nearest point. Are outcomes needed?
풀이와 확인할 이유Solution and explanation
제곱 유클리드는9와8이라B, 맨해튼은3과4라A, 체비쇼프는3과2라B다. 입력과 정한 거리만으로 선택한다. 원하는 결과값을 주는 후보를 사후에 고르면 공개한 이웃 규칙과 다르다.
Squared Euclidean gives 9 and 8 and chooses B; Manhattan 3 and 4 chooses A; Chebyshev 3 and 2 chooses B. Selection uses features and the declared metric, not the outcome that would give a preferred prediction.
두 점A=(1,2),B=(9,2)에 제곱거리 좌표 무게(0,1)을 쓴다. 비교값과 전체 입력 공간에서의 동일점 조건을 설명하라.
For A=(1,2), B=(9,2), use squared-distance weights(0,1). Find the dissimilarity and discuss identity of indiscernibles in the original space.
풀이와 확인할 이유Solution and explanation
0×(1−9)²+1×(2−2)²=0이다. 원입력은 다르지만 첫 좌표를 무시해 구별하지 못한다. 이 제곱 비교값은 전체 원공간의 metric이나 일반적인 준거리라고 부르지 않는다. 남긴 둘째 좌표의 제곱차도 0·1·2에서 4>1+1로 삼각부등식을 깬다. 그 비교값에 제곱근을 취한 |a₂−b₂|는 둘째 좌표 공간의 거리이고 원래 두 좌표 공간의 준거리다. 비교값0과 거리 공리는 따로 확인해야 한다.
The result is zero despite different original vectors because the first coordinate is ignored. The squared comparison is neither a metric nor, in general, a pseudometric on the full space. Even the retained second-coordinate squared difference fails the triangle inequality at 0,1,2 because four exceeds one plus one. Its square root, |a₂−b₂|, is a metric on the second-coordinate space and a pseudometric on the original two-coordinate space. A zero comparison alone does not establish the remaining distance axioms.
8. 같은 단위 변환과 같은 기하Preserving geometry under a unit change
한 입력 차이는2m, 그 척도 s는4m다. 센티미터로 바꾸었을 때 같은 정규화 제곱 기여를 유지하려면 척도는? s를 숫자4로 그대로 두면?
A feature difference is 2 metres and scale 4 metres. What scale in centimetres preserves its normalized squared contribution? What if the scale number remains 4?
풀이와 확인할 이유Solution and explanation
차이는200cm, 척도도400cm로 바꾸어 (200/400)²=1/4를 유지한다. 척도를4cm로 두면 (200/4)²=2500으로 원래1/4의10000배다. 사람·대상이 바뀐 것이 아니라 상대 비중을 바꾼 것이다.
Use difference 200 cm and scale 400 cm to preserve 1/4. Keeping scale 4 cm instead gives 2500, ten thousand times the original contribution. The unit changed, not the underlying unit being described.
9. k=3인데 네 행인 이유Why k=3 can select four rows
질의0, 훈련 점수−3,−2,−1,1,2,3, k=3이다. 전체 경계 동률 포함에서 선택 행과 실제 수를 적어라. 선택된 결과6·8·12·14의 평균은?
At query zero and scores−3,−2,−1,1,2,3, use k=3 and include all boundary ties. Identify selected scores, actual count and mean of their outcomes 6,8,12,14.
풀이와 확인할 이유Solution and explanation
세 번째 거리는2여서 거리2이하인−2,−1,1,2의 네 행이 남는다. 실제 평균은(6+8+12+14)/4=10이다. 요청k3과 사용행4를 함께 표시한다.
The third distance is two, retaining−2,−1,1,2: four rows. Their mean is ten. Report requested k=3 and actual selected count four together.
10. 원순서로 동률을 자를 때Breaking ties by source order
질의0, A의 입력−1·결과0, B의 입력1·결과10이다. k=1에서 stable과 전체 동률을 비교하고 A/B순서를 바꾸어 보라.
At query zero, A has input−1/outcome 0 and B input 1/outcome 10. Compare stable and all-tie k=1 predictions, then reverse row order.
풀이와 확인할 이유Solution and explanation
stable은 첫 행만 써A가 먼저면0, B가 먼저면10이다. 전체 동률은 둘 다 써항상5다. 입력 거리에는 차이가 없으므로 stable의 변화는 원순서 규칙에 의한 것이지 결과를 더 잘 설명하는 이웃을 발견한 것이 아니다.
Stable uses the first row, predicting zero or ten after reversal. All ties averages both to five in either order. The stable change follows file order, not improved geometric similarity.
11. 동률이 있어도 순서가 무관한 경우A tie need not cause order dependence
A·B는 질의에서 거리1, C는 거리2이며 k=2다. stable은 A/B순서에 따라 선택 집합이 달라지는가? 경계 일부가 잘리는 경우와 비교하라.
A and B have distance one, C distance two, and k=2. Does stable selection depend on the A/B order? Contrast with truncating part of a boundary group.
풀이와 확인할 이유Solution and explanation
A와B가 모두 두 자리 안에 들어오므로 선택 집합은 같다. 같은 거리라는 사실만으로 순서 민감 표지를 켜면 과장이다. k=1이면 둘 중 하나만 남아 순서가 중요해질 수 있다.
Both A and B fit within the two slots, so membership stays fixed. A tie alone is insufficient for order sensitivity. At k=1, only part of their tied group is retained, and order can matter.
12. 숫자 ID와 문자열 IDNumeric and string identifiers
원행 ID가 숫자1과 문자열“1”인 서로 다른 행이 있다. 이 장의 typed ID 규칙에서 같은 행인가? 두 행 모두 문자열“1”이면? 이 구분이 같은 입력을 가진 행과 같은가?
Two rows have numeric ID 1 and string ID "1". Are they identical under typed IDs? What if both IDs are the string "1"? Compare with equal feature vectors.
풀이와 확인할 이유Solution and explanation
숫자1과 문자열“1”은 다른 typed ID로 허용한다. 두 문자열“1”은 중복 식별자라 거부한다. 식별자의 유일성과 입력 좌표의 같음은 다른 조건이다. 같은 좌표의 서로 다른 행은 원행을 지우지 않고 동률 규칙으로 다룬다.
Numeric 1 and string "1" are distinct typed IDs; two identical string IDs are rejected. Unique identity differs from equal features. Different source rows may share coordinates and remain as tied neighbours.
13. 0거리 두 관측의 예측Prediction with two zero-distance observations
입력0의 두 행 결과는2·8이고 입력1의 결과는20이다. 질의0, k=1, 전체 동률에서 균등과 역제곱 예측을 계산하라.
Two rows at input zero have outcomes two and eight; a row at one has outcome twenty. At query zero, k=1 with all ties, compute uniform and inverse-square predictions.
풀이와 확인할 이유Solution and explanation
0거리 두 행이 모두 선택되어 균등 평균5다. 역제곱 규칙도 1/0을 만들지 않고 선택된0거리 행들의 관찰 무게를 정규화하므로5다. 다른20은 선택되지 않는다. 동일한 입력의 결과가 다르다고 한 원행을 임의 삭제하지 않는다.
Both zero-distance rows enter and average to five. Inverse-square voting uses only selected exact-zero rows with normalized observation weights, also giving five, without division by zero. Outcome twenty is not selected.
14. 표시가0인 두 양의 거리Two positive distances displayed as zero
질의0, 후보 입력1e−200와2e−200를 정확한 문자열로 입력했다. 제곱거리 두 값과 가까운 순서를 구하라. binary64표시에 둘 다0이면 같은 거리인가?
At query zero, candidate inputs are exact strings 1e−200 and 2e−200. Give squared distances and rank. If both binary64 values display zero, are they tied?
풀이와 확인할 이유Solution and explanation
제곱거리는10^(−400),4×10^(−400)이다. 첫 값이 작아 첫 후보가 가깝다. 둘 다 표시 범위 아래일 수 있지만 정확히 양수이고 서로 다르다. 비교·0거리 역제곱 규칙은 화면의0이 아니라 정확한 분자·분모로 판단한다.
(10−200)2=10−400<4⋅10−400=(2⋅10−200)2
Distances squared are 10^(−400) and 4×10^(−400), so the first is closer. Both may underflow in display but remain positive and unequal. Ranking and zero-distance handling use exact fractions, not displayed zeros.
(10−200)2=10−400<4⋅10−400=(2⋅10−200)2
15. 빈도와 다른 관찰 무게Observation weights versus neighbour count
같은 거리의 두 이웃 결과2·8, 관찰 무게1/3·2/3이다. 전체 동률에서 가중예측과 이웃 수를 구하라.
Two equally distant neighbours have outcomes two and eight and observation weights 1/3 and 2/3. Find their weighted prediction and selected row count.
풀이와 확인할 이유Solution and explanation
정규화 무게 합이1이므로(1/3)2+(2/3)8=6이다. 원행 수는2이며 무게 분수나 총합1을 사람 수와 혼동하지 않는다. 같은 무게 평균5와는 다른 계산이다.
The prediction is six, with two source rows. Fractional weights or total weight one do not turn this into one observed person. The equal-weight mean would instead be five.
16. 모든 무게의 공통 배수A common multiplier on all weights
두 이웃 결과2·8의 무게가1·3이다. 예측을 계산하고 두 무게를10·30으로 바꾸면 달라지는지 보라. 한 무게만0으로 바꾸는 경우도 같은 변경인가?
Outcomes two and eight have weights one and three. Compute the prediction, then replace weights by ten and thirty. Is setting one weight to zero equivalent?
풀이와 확인할 이유Solution and explanation
첫 예측은(2+24)/4=13/2이고, 두 번째도(20+240)/40=13/2다. 공통 양수 배는 정규화에서 상쇄된다. 한 행의 무게0은 후보 제외와 상대 비중을 바꾸므로 같은 불변성이 없다.
Both predictions equal 13/2 because the common positive multiplier cancels. A zero weight can remove a candidate and alter relative contributions; it is a different change.
17. 완전 프레임의 제외 이유Exclusion reasons in the eligible frame
네 행은 A:x0,y2,w1; B:xnull,y3,w1; C:x1,ynull,w1; D:x2,y8,w0이다. 예측에 쓸 후보 수와 각 제외 이유를 적어라. y가 필요 없는 기하 검색에서는?
Rows are A: x=0, y=2, w=1; B: x=null, y=3, w=1; C: x=1, y=null, w=1; D: x=2, y=8, w=0. Count prediction candidates and exclusions. What changes for pure geometric search?
풀이와 확인할 이유Solution and explanation
예측은 A만 유효하다. B는 입력 불완전, C는 훈련 결과 결측, D는 무게0으로 제외한다. 기하 검색은 결과가 필요 없어 A와C 두 행을 쓸 수 있다. C의 결과를0으로 채운 것이 아니라 다른 작업의 분모가 달라진 것이다.
Only A is eligible for prediction. B lacks a predictor, C lacks a training outcome and D has zero weight. Geometry can retain A and C because y is unnecessary; this does not impute a zero outcome to C.
18. 질의의 결측을0으로 바꾸지 않기An incomplete query is not a zero prediction
유효한 훈련 표가 있고 새 질의 x=(1,null)이다. 이 장의 complete-vector규칙에서 예측은? 빈 좌표를0으로 바꾸면 같은 분석인가?
Training data are valid but a query is(1, null). What does the complete-vector rule return? Is replacing its missing coordinate by zero the same analysis?
풀이와 확인할 이유Solution and explanation
질의는 입력 불완전으로 미정의이며 이전 예측을 새 답처럼 남기지 않는다.0으로 대치하면 관측된0과 결측을 합치고 새 거리·이웃을 만들어 다른 분석이 된다. 대치가 필요하면 훈련에서 배운 명시적 대치 규약과 그 검증을 추가해야 한다.
Return undefined for incomplete predictors and clear stale output. Zero imputation changes distances and confuses missingness with an observed zero. If desired, imputation needs its own explicitly trained and validated procedure.
19. 시험 입력이 바꿔 버린 척도A scale altered by a test input
훈련 입력0·2, 무게1·1이다. 평균·range·모집단식 분산을 구하라. 시험 입력100을 끼워 넣으면 각각? 왜 이 장의 전처리 규약과 다른가?
Training inputs are zero and two with unit weights. Find mean, range and population-form variance, then repeat after inserting test input 100. Why does that differ from this chapter’s protocol?
풀이와 확인할 이유Solution and explanation
훈련만 쓰면 평균1·range2·분산1이다.100을 넣으면 평균34·range100·분산[(0−34)²+(2−34)²+(100−34)²]/3=6536/3이다. 시험 y를 안 보아도 시험 x로 척도를 배웠으므로 보통의 훈련 전용 새 대상 예측 절차와 다르다.
Training-only values give mean one, range two and variance one. Adding 100 gives mean 34, range 100 and variance 6536/3. This uses test inputs for preprocessing even without seeing test outcomes, changing the ordinary training-only protocol.
20. 모든 좌표가 상수인 훈련 표A training table with only constant coordinates
두 훈련 행은 입력5, 결과8·12다. 질의7에서 variance스케일링·k=1·전체 동률을 쓴다.0분산 좌표와 예측·범위 표지는 어떻게 되는가?
Two training rows have input five and outcomes eight and twelve. At query seven, use variance scaling, k=1 and all ties. Describe the zero-variance coordinate, prediction and range flag.
풀이와 확인할 이유Solution and explanation
분산0인 좌표는 버렸다고 표시한다. 남은 공간에서는 둘 다 거리0이라 두 행이 선택되고 평균10을 예측한다. 원입력7은 훈련 최솟값·최댓값5밖이라 범위 밖 표지도 켜진다. 좌표를 버렸다는 것이 결과를0으로 만든다는 뜻은 아니다.
The zero-variance coordinate is dropped. Both rows then have dissimilarity zero, so their mean ten is predicted. Query seven also lies outside the original training range[5,5]. Dropping a coordinate does not set the outcome to zero.
21. 가중 모집단식 분산Weighted population-form variance
훈련 입력0·2의 관찰 무게는1·3이다. 가중평균·모집단식 분산을 구하고 variance정규화에서0과2의 제곱거리를 계산하라.
Training inputs zero and two have observation weights one and three. Find their weighted mean, population-form variance and variance-normalized squared distance.
풀이와 확인할 이유Solution and explanation
무게 합4, 평균(0+6)/4=3/2이다. 분산은[(0−3/2)²+3(2−3/2)²]/4=(9/4+3/4)/4=3/4다. 제곱거리는4/(3/4)=16/3이다. 분모를3으로 바꾸는 표본분산은 이 엔진의 척도와 다른 정의다.
xˉ=23,v=449+3⋅41=43,d2=3/44=316
Total weight is four and mean is 3/2. Population-form variance is (9/4+3/4)/4=3/4. The normalized squared distance is 4/(3/4)=16/3. Dividing by three instead would use a different variance definition.
xˉ=23,v=449+3⋅41=43,d2=3/44=316
22. 역제곱 무게로 계산하기Calculate inverse-square voting
실제 유클리드 거리1·2인 두 이웃의 결과가0·10이다. 관찰 무게1, k=2일 때 균등 예측과 inverseSquaredEuclidean예측을 계산하라.
Two neighbours at Euclidean distances one and two have outcomes zero and ten. With unit observation weights and k=2, compare uniform and inverse-square predictions.
풀이와 확인할 이유Solution and explanation
균등은5다. 거리 제곱1·4의 역수는1·1/4이며 합5/4로 나누면4/5·1/5다. 예측은0×4/5+10×1/5=2다. 가까운 결과0에 더 큰 무게를 주어 같은 이웃에서도 답이 달라졌다.
(λ1,λ2)=(54,51),y=54⋅0+51⋅10=2
Uniform voting predicts five. Inverting squared distances one and four gives weights one and 1/4, normalized to 4/5 and 1/5. The prediction is two. Membership stayed fixed while the nearer outcome received more weight.
(λ1,λ2)=(54,51),y=54⋅0+51⋅10=2
23. 거리 제곱을 두 번 제곱하면Squaring the squared distance again
제곱거리 s가1·4인 이웃의 결과는0·10이다. 올바른 역제곱 유클리드 무게1/s와 잘못 바꾼1/s²의 예측을 비교하라.
Neighbours with squared distances s=1 and four have outcomes zero and ten. Compare inverse-square Euclidean voting 1/s with the different rule 1/s².
풀이와 확인할 이유Solution and explanation
1/s는 무게1·1/4로 예측2다.1/s²는 무게1·1/16으로 정규화하면16/17·1/17이라 예측10/17이다. 후자는 실제 거리 네제곱의 역수이며 같은 규칙이 아니다. 작은 결과 차이로 무시하지 말고 정의를 확인한다.
The intended 1/s gives prediction two. Using 1/s² instead normalizes weights one and 1/16 to 16/17 and 1/17, predicting 10/17. That weights by inverse fourth power of Euclidean distance, a different rule.
24. 가중평균의 최소화 문제Derive a weighted mean as a minimizer
Q(a)=(2−a)²+3(8−a)²를 최소화하는 a를 도함수로 구하고 최소해가 유일한지 판단하라. 이 결과가 새 대상에게 정확함을 보증하는가?
Minimize Q(a)=(2−a)²+3(8−a)² by differentiation and assess uniqueness. Does this certify accuracy for a new unit?
풀이와 확인할 이유Solution and explanation
Q′=2(a−2)+6(a−8)=8a−52이므로 a=13/2다. Q″=8>0이라 유일한 최소이며 가중평균(2+24)/4와 같다. 정한 이웃과 손실 안의 최소화이지 새 대상의 참결과나 모집단 위험 최적성의 보증은 아니다.
Q′(a)=8a−52=0⟺a=213,Q′′(a)=8>0
The derivative 8 a−52 vanishes at 13/2; second derivative eight is positive. This matches the weighted mean. It minimizes a finite local objective without certifying the new outcome or population-optimal risk.
Q′(a)=8a−52=0⟺a=213,Q′′(a)=8>0
25. 무게 합0과 음수 무게Zero total weight and negative weights
모든 훈련 행의 관찰 무게가0이다. 예측 평균을0으로 채워도 되는가? 한 무게가−1이면 같은 빈 프레임 처리인가?
Every training observation weight is zero. May the prediction be filled with zero? Is a negative weight handled as the same empty-frame case?
풀이와 확인할 이유Solution and explanation
양의 무게 후보가 없으므로 이 엔진은 유효 훈련 행이 없다고 거부한다. 결과0을 관측한 것이 아니다. 음수 무게는 입력 정의역 밖이라 별도로 거부하며, 평균의 분모를0 또는 음수로 만든 뒤 일반적인 이웃 평균이라고 계산하지 않는다.
No positive-weight candidates remain, so the engine rejects an empty eligible training frame. It has not observed a zero outcome. Negative weights are a separate domain violation, not ordinary missing or zero-weight records.
26. 국소 이탈 비율과 BrierLocal churn proportion and Brier loss
같은 무게의 세 이웃 이탈 표지가0·1·1이다. 이탈 확률·기본 범주 예측을 구하라. 새 실제 결과가0이면 이진 Brier와0–1오류는?
Three equally weighted neighbours have labels zero, one and one. Find positive-class probability and the default class. If the new outcome is zero, calculate binary Brier and 0–1 error.
풀이와 확인할 이유Solution and explanation
이탈 비율2/3, 비이탈1/3이라 기본 범주는1이다. 실제0에서 Brier는(2/3−0)²=4/9이고 선택 범주는 틀려 오류1이다. 경험 비율2/3을 참확률이 확정되었다는 주장으로 바꾸지 않는다.
LB=(32−0)2=94
Probabilities are 2/3 and 1/3, selecting class one. At actual zero, Brier is 4/9 and class error is one. The empirical proportion is not a certified true probability.
LB=(32−0)2=94
27. 세 범주의 확률과 점수 정의Three classes and the score convention
선언 범주 순서가 a,b,c이고 같은 무게 이웃 결과도 하나씩 a,b,c다. 확률·행동을 구하라. 실제 c일 때 이 장의 ½Σ범주제곱오차 Brier는?
Declared class order is a, b, c, with one equally weighted neighbour per class. Find probabilities and action. For actual class c, compute this chapter’s half-sum Brier.
풀이와 확인할 이유Solution and explanation
각 확률1/3이고 동률 행동은 첫 범주a다. 제곱오차 합은1/9+1/9+4/9=2/3이며 절반은1/3이다. 절반을 쓰지 않는 다범주 Brier 정의와 수치를 비교할 때는 척도 차이를 먼저 맞춘다.
LB=21[91+91+94]=31
Each probability is 1/3 and the tied action is a. Squared errors sum to 2/3; half gives 1/3. Comparisons with an unhalved multiclass Brier must account for the convention.
LB=21[91+91+94]=31
28. 범주 순서를 바꿔도 확률은 같은가Class order versus probability estimates
두 범주 no·yes의 국소 비율은 각각1/2다. 선언 순서를 뒤집으면 무엇이 달라지는가? 실제 yes에서 Brier도 바뀌는가?
Local probabilities for no and yes are each one half. Reverse their declared order. What changes, and does Brier for an actual yes change?
풀이와 확인할 이유Solution and explanation
범주별 확률은 그대로다. 첫 선언 범주를 택하므로 행동이 no에서 yes로 바뀔 수 있다. Brier는 어느 순서에서도(1/2−1)²=1/4다. 행동의 동률 해소와 확률 추정을 구별한다.
Probabilities indexed by class remain unchanged. The tied action changes from no to yes because the declared first class changes. Brier stays 1/4, separating action tie-breaking from probability estimation.
29. 다른 비용의 결정 문턱A threshold under unequal costs
이탈 확률p=1/4, 거짓 양성 비용1·거짓 음성 비용4·맞는 비용0을 가정한다. 두 행동의 기대비용과 더 나은 행동을 구하라. 기본 최다 비율과 같은가?
Assume p=1/4, false-positive cost one, false-negative cost four and zero correct-action cost. Compare expected costs and the preferred action with the default majority rule.
풀이와 확인할 이유Solution and explanation
양성 비용은1−p=3/4, 음성 비용은4p=1이므로 이 비용 아래 양성이 낫다. 동일0–1비용의 최다 비율 규칙은p<1/2라 음성을 고른다. 서로 다른 목적을 계산한 것이며 엔진 기본 행동이 이 비용 정책을 자동 구현하는 것은 아니다.
R(+)=1−p=43<4p=1=R(−)
Expected positive-action cost is 3/4, versus one for a negative action, so positive is preferred here. Equal 0–1 majority voting instead selects negative because p<1/2. These optimize different objectives; the default engine action does not implement the cost policy.
R(+)=1−p=43<4p=1=R(−)
30. 잘못된 범주와 결측은 다르다An invalid class differs from a missing label
선언 범주는0·1인데 어떤 훈련 y는2이고 다른 y는null이다. 이 장의 분류 입력 규칙에서 어떻게 다르게 처리하는가? null을0으로 만들면?
Declared classes are zero and one; one training label is two and another is null. How do the input rules distinguish them? What happens if null is replaced by zero?
풀이와 확인할 이유Solution and explanation
2는 선언 범주가 아니라 입력 오류로 거부한다. null은 관측되지 않은 훈련 결과로 원행을 남기고 예측 프레임에서 제외한다. null을0으로 바꾸면 비이탈을 새로 만들어 비율과 척도 학습 프레임을 바꾸는 다른 분석이 된다.
Two is outside the declared classes and is rejected. Null preserves an unlabeled row excluded from the prediction frame. Turning null into zero fabricates a non-churn label and changes probabilities and eligible training preprocessing.
31. 자기 자신의0거리 답A self-neighbour at zero distance
서로 다른 두 훈련 입력은0·2, 결과는0·10이고 ID는 A·B다. A를 다시 질의하는 k=1훈련 예측과 A전체를 제외한 leave-one-out예측을 비교하라.
Training inputs zero and two have outcomes zero and ten and IDs A, B. Compare a k=1 query of A with the prediction after excluding the entire A record.
풀이와 확인할 이유Solution and explanation
자기 자신을 남기면 A의 거리0·결과0을 택해 오차0이다. A를 후보와 척도 학습에서 제외하면 B만 남아10을 예측하여 A의 실제0과 제곱오차100이다. 자기 y만 가리고 x를 남겨 두는 절차와도 구별한다.
With A retained, its zero-distance outcome gives zero error. Removing A from candidates and preprocessing leaves B, predicting ten and squared error 100 against A’s outcome zero. This differs from merely hiding A’s y while keeping its input.
32. 중복 입력이 만든 훈련 오차Training error with conflicting duplicate inputs
입력이 둘 다0인 훈련 결과2·8에 k=1전체 동률을 쓴다. 각 행을 다시 예측했을 때 예측값과 훈련 MSE는? 1NN훈련 오차는 무조건0인가?
Two training rows share input zero but have outcomes two and eight. Requery each using k=1 with all ties. Find predictions and training MSE. Is 1NN training error always zero?
풀이와 확인할 이유Solution and explanation
각 질의에서 두0거리 행을 모두 써예측5다. 제곱오차는각9라 MSE9다. 서로 다른 입력에서 자기 자신만0거리인 경우의0훈련 오차를 모든 동률 규약·중복 입력으로 일반화할 수 없다.
Both queries average the two zero-distance rows to five. Each squared error is nine, so MSE is nine. The zero-training-error argument for distinct inputs cannot be transferred unchanged to conflicting duplicates and all-tie handling.
33. 평균으로도 생기는 불연속A discontinuity despite averaging
입력1·3의 결과는0·10이며 k=1전체 동률이다. 새 점이2보다 작을 때·정확히2일 때·2보다 클 때를 비교하여 예측 함수가2에서 연속인지 판단하라.
Inputs one and three have outcomes zero and ten with all-tie k=1. Compare queries below, exactly at and above two. Is the predictor continuous at two?
풀이와 확인할 이유Solution and explanation
2보다 작으면 첫 점이 가깝고0, 정확히2는동률 평균5, 크면둘째가 가까워10이다. 좌우 극한이0·10이라 연속이 아니다. 이는 표본 예측 규칙의 경계이며 모집단 평균의 도약을 입증하지 않는다.
Predictions are zero below, five exactly at, and ten above two. Unequal one-sided limits make the sample rule discontinuous. This algorithmic boundary does not establish a population-mean discontinuity.
34. 무게 집중과 잡음 분산Weight concentration and noise variance
독립인 두 이웃 오차 분산이각4다. 균등 무게(1/2,1/2)와 역거리 예의 정규화 무게(4/5,1/5)의 예측 분산을 구하라. 후자가 반드시 더 좋은가?
Independent neighbour errors each have variance four. Compare prediction variances under weights (1/2,1/2) and (4/5,1/5). Must the latter predict better?
풀이와 확인할 이유Solution and explanation
균등 분산4(1/4+1/4)=2다. 집중 무게는4(16/25+1/25)=68/25로 더 크다. 더 가까운 평균 관계를 써편향이 작아질 수도 있지만 이 분산 계산만으로 전체 MSE의 우열은 정할 수 없다.
Varequal=2,Varweighted=4(2516+251)=2568
Uniform variance is two; concentrated weights give 68/25, which is larger. Closer outcomes may reduce approximation bias, but variance alone does not determine total MSE.
Varequal=2,Varweighted=4(2516+251)=2568
35. 평균 추정과 새 결과 예측Estimating a mean versus predicting a new outcome
조건부 평균 추정의 편향1·분산2이고 새 결과의 독립 잡음 분산4다. 평균 추정 MSE와 새 결과 예측 MSE를 구하라.
A conditional-mean estimator has bias one and variance two. A new outcome has independent noise variance four. Compare the two MSE targets.
풀이와 확인할 이유Solution and explanation
평균 추정 MSE는1²+2=3, 새 결과 예측은3+4=7이다. 새 오차가 평균0·훈련 오차와 독립이라는 가정을 썼다. 두 표적을 혼동하면 이웃 수를 늘려도 없애지 못하는 새 대상의 잡음을 계산에서 빠뜨린다.
MSEm=12+2=3,MSEY0=3+4=7
Mean-estimation MSE is three; new-outcome prediction MSE is seven under zero-mean independent new noise. Confusing targets omits irreducible noise that increasing neighbour count does not remove.
MSEm=12+2=3,MSEY0=3+4=7
36. 네 행 교차검증을 끝까지Complete a four-row cross-validation example
x=0,1,2,3; y=0,0,10,10; fold=0,1,0,1, 단위 무게·전체 동률이다. k=1과2의 모든 out-of-fold예측·MSE·선택k를 구하라.
Use x=0,1,2,3, y=0,0,10,10 and folds 0,1,0,1 with unit weights and all ties. Compute all out-of-fold predictions, MSEs and the selected k among one and two.
풀이와 확인할 이유Solution and explanation
k1의 원행 순서 예측은0,5,5,10이다. 가운데 질의들은 훈련 두 점의 중간이라 동률 평균5이며 제곱오차 합50, MSE25/2다. k2는모든 행에 각 fold훈련 평균5를 주어 오차합100·MSE25다. 따라서k1을 고른다.
CV(1)=40+25+25+0=225<25=CV(2)
For k=1 the source-order predictions are 0,5,5,10. The middle queries tie between their training points. Squared errors sum to fifty, giving 25/2. k=2 always predicts the fold training mean five, with MSE 25. Choose k=1.
CV(1)=40+25+25+0=225<25=CV(2)
37. fold평균의 평균이 다른 이유Why a mean of fold means can differ
첫 fold는검증1행·제곱손실0, 둘째는검증3행·각손실4다. 단위 무게에서 전체 pooled MSE와 두 fold평균의 단순 평균을 계산하라.
One validation fold has one row with squared loss zero; another has three rows each with loss four. Compare pooled unit-weight MSE with an unweighted average of fold means.
풀이와 확인할 이유Solution and explanation
pooled값은(0+4+4+4)/4=3이다. fold평균은0과4라 단순 평균2다. 후자는 한 행의 fold와세 행의 fold에 같은 무게를 주었다. 이 엔진은 모든 평가 가능 원행 손실·무게를 모은3을 보고한다.
40+4+4+4=3=20+4=2
Pooled MSE is three. Fold means zero and four average to two because folds, rather than records, received equal weight. This engine pools evaluable row losses and weights, returning three.
40+4+4+4=3=20+4=2
38. fold마다 달라지는 척도Scales legitimately differ by fold
한 fold훈련 입력은0·4, 다른 fold훈련은2·100이다. 같은 무게의 range·모집단식 분산을 각각 구하라. 전체입력range100을 모든 fold에 써도 같은 규칙인가?
One fold trains on zero and four; another on two and 100. Find each range and population-form variance. Is using full-data range 100 in both folds the same procedure?
풀이와 확인할 이유Solution and explanation
첫 range4·평균2·분산4, 둘째range98·평균51·분산2401이다. 서로 다른 훈련 구성 때문에 척도가 달라도 정상이다. 전체range100을 쓰면 각 검증 입력을 포함해 학습한 다른 전처리 규칙이다.
The first has range four, mean two and variance four. The second has range 98, mean 51 and variance 2401. Different training complements legitimately fit different scales. Reusing full-data range 100 evaluates another preprocessing procedure.
39. 일부 fold에서만 불가능한 kA k that is infeasible in one fold
후보k3인데 어떤 fold훈련에는유효2행, 다른 fold에는4행이 있다. 첫 fold에서만k2로 줄여 점수를 모아k3성능이라고 보고해도 되는가?
Candidate k=3 faces two eligible training rows in one fold and four in another. May k be clipped to two in the first fold while the pooled result is reported as k=3?
풀이와 확인할 이유Solution and explanation
아니다. 서로 다른 규칙을 한 후보 이름으로 섞는다. 이 엔진은 그런 후보를 거부한다. k후보를 모든 fold에서 가능하도록 다시 정하거나, 적응적으로k를 바꾸는 별도 알고리즘을 명시해 평가해야 한다.
No. That mixes algorithms under one candidate label. This engine rejects the infeasible candidate. Choose feasible candidates or explicitly define and evaluate a separate adaptive-k rule.
40. 훈련 비율 기준 모형A training-proportion baseline
훈련 표의0범주8행·1범주2행, 단위 무게다. 새 실제 결과1에 대한 기준 확률·범주·Brier·오류율 한 행 값을 구하라.
Training contains eight zeros and two ones with unit weights. For one new actual positive, find baseline probability, class, Brier and class error.
풀이와 확인할 이유Solution and explanation
훈련 양성 비율1/5, 음성4/5라 기준 범주는0이다. 실제1에서 Brier는(1/5−1)²=16/25, 오류는1이다. 검증·시험 결과를 넣어 이 비율을 다시 맞추지 않는다.
Positive probability is 1/5 and the chosen class zero. At an actual positive, Brier is 16/25 and class error one. Validation or test outcomes must not refit that training baseline.
41. 같은 검증 손실의 선택 규약A selection convention for equal CV losses
후보가 입력 순서 5·3·1이고 CV 손실은 각각 3/4·1/2·1/2이다. 이 장의 규약에서 고르는 k는? 작은 k가 항상 참위험도 작은가?
Candidates arrive in order 5,3,1 with CV losses 3/4,1/2,1/2. Which k is selected? Does that establish that smaller k always has lower true risk?
풀이와 확인할 이유Solution and explanation
최소 손실 1/2인 k=3·1 중 더 작은 1을 고른다. 입력 순서에서 먼저 나온 3이 아니다. 작은 k 동률 규약은 재현을 위한 선언이며 모집단 참위험의 순서를 증명하지 않는다.
Choose k=1, the smaller of the candidates tied at minimum loss 1/2, rather than the earlier input candidate three. This convention makes selection reproducible without proving an ordering of true risks.
42. 시험 결과를 보고 다시 고르면Selecting again after inspecting test results
CV로 k=3을 골랐지만 시험 결과가 마음에 들지 않아 5·7·9를 시험한 뒤 최저 시험오차를 보고했다. 최초 시험이 선택과 독립적이었다고 할 수 있는가? 편향의 크기도 이 설명만으로 계산되는가?
After CV selects k=3, an analyst tries 5,7,9 on the test set and reports its best score. Is that score independent of selection? Can the bias magnitude be computed from this description alone?
풀이와 확인할 이유Solution and explanation
시험 결과가 선택을 바꾸었으므로 그 결과를 처음부터 고정한 한 모형의 독립 시험 성능처럼 읽을 수 없다. 여러 실현 오차 중 작은 것을 고른 효과로 낙관적일 수 있다. 구체적인 공동분포·후보 의존성 없이 편향 크기는 계산할 수 없다. 선택을 포함한 새 평가나 별도 시험 자료가 필요하다.
Test outcomes influenced selection, so the reported minimum is not the independent test score of one previously fixed model. Choosing a favorable realized error can be optimistic. Its magnitude requires distributional and dependence information not supplied here; evaluate the selection process or use a separate final test.
43. 세 방향 상자의 확률질량Probability mass of a three-dimensional box
단위 정육면체의 균등 분포를 가정한다. 내부 작은 상자의 각 변은 전체의 1/3이고 표본은 54개다. 질량과 기대 관측 수를 구하라. 이것이 유클리드 반지름 1/3인 공의 부피인가?
Assume a uniform unit cube, an interior subcube with side fraction 1/3, and sample size 54. Find mass and expected count. Is this the volume of a Euclidean ball of radius 1/3?
풀이와 확인할 이유Solution and explanation
질량은 (1/3)³=1/27, 기대수는 54/27=2다. 각 방향의 변 길이를 곱한 상자이며 유클리드 공의 부피 공식이 아니다. 실제 관측에서 정확히 2개를 셌다는 뜻도 아니다.
q=(31)3=271,E[N]=54q=2
Mass is 1/27 and expected count two. This multiplies box side lengths, not a Euclidean-ball volume. It also does not assert exactly two observed records in a realization.
q=(31)3=271,E[N]=54q=2
44. 기대수 1에 필요한 올림A ceiling for expected count one
균등 3차원 단위 상자에서 sideFraction=2/3이다. 기대수 1 이상에 필요한 최소 정수 n을 구하고, 그 n에서 빈 상자 확률이 0인지 확인하라.
In a uniform three-dimensional unit cube with side fraction 2/3, find the smallest integer n giving expected count at least one. Is empty-box probability zero at that n?
풀이와 확인할 이유Solution and explanation
질량 8/27이므로 n≥27/8=3.375, 최소 정수는 4다. n=3의 기대수 8/9는 1 미만이고 n=4에서는 32/27이다. 독립 표본에서 빈 확률은 (19/27)^4=130321/531441로 양수다. 기대수 문턱은 확률 1의 보장이 아니다.
nmin=⌈827⌉=4,Pr(N=0)=(2719)4>0
Mass 8/27 requires n≥27/8, so choose four. Expected counts are 8/9 at three and 32/27 at four. Under independence the empty probability is(19/27)^4=130321/531441, which is positive. An expectation threshold is not certain coverage.
nmin=⌈827⌉=4,Pr(N=0)=(2719)4>0
45. 차원별 기대수 비교Compare expected counts by dimension
n=1024, r=1/2인 균등 내부 상자에서 d=1·10·20의 질량과 기대수를 구하라. 이를 실제 통신 데이터가 균등하다는 증거로 쓸 수 있는가?
For n=1024 and r=1/2 in an assumed uniform interior box, compute mass and expected count at d=1,10,20. Does this establish uniformity in actual telecom data?
풀이와 확인할 이유Solution and explanation
질량은 1/2·1/1024·1/1048576, 기대수는 512·1·1/1024다. 조건부 부피 계산일 뿐 실제 입력의 분포를 검정한 것이 아니다. 연관·이산성·표본 선택이 있는 실제 자료에 같은 확률을 그대로 부여할 수 없다.
Masses are 1/2,1/1024,1/1048576 and expected counts 512,1,1/1024. These follow assumed geometry rather than a test of actual feature distributions, dependence or selection.
46. 부피 0과 전체 상자Zero volume and the full box
차원 5·관측 10에서 r=0과 r=1의 질량·기대수·기대수 1에 필요한 최소 n을 비교하라.
At dimension five and observation count ten, compare r=0 and r=1 for mass, expected count and the minimum n for expected count one.
풀이와 확인할 이유Solution and explanation
r=0은 질량 0·기대수 0이며 필요한 유한 n이 없다. 필요한 n을 0으로 채우지 않는다. r=1은 질량 1·기대수 10·최소 n=1이다. 경계에서도 계산된 0과 미정의를 구별한다.
At zero, mass and expected count are zero and no finite n achieves expectation one. At one, mass is one, expected count ten and the required minimum n is one. Undefined required sample size is not filled with zero.
47. 극소 부피와 표시 한계Tiny volume and display limits
r=10^(−200), d=128, n=10^9를 가정한다. 정확한 질량·기대수·최소 기대 표본 수를 지수로 쓰고, 화면의 질량 0·필요수 표시 초과를 어떻게 읽을지 설명하라.
Assume r=10^(−200), d=128 and n=10^9. Express exact mass, expected count and minimum required n as powers of ten. Interpret a zero mass display and overflowing required-count display.
풀이와 확인할 이유Solution and explanation
질량은 10^(−25600), 기대수는 10^(−25591), 최소 n은 10^25600이다. 앞의 둘은 양수인데 binary64 표시에 0으로 underflow할 수 있고 마지막은 유한한 정확 정수지만 표시 범위를 넘는다. 수학적 0·무한대가 된 것이 아니며 원정확값은 펼치기로 보존한다.
q=10−25600,E[N]=10−25591,nmin=1025600
Mass is 10^(−25600), expected count 10^(−25591), and required n 10^25600. Positive tiny values can underflow in binary64; the large required count is a finite exact integer despite display overflow. Preserve the full values separately instead of calling them mathematical zero or infinity.
q=10−25600,E[N]=10−25591,nmin=1025600
48. 같은 좌표 세 번Repeating the same coordinate three times
두 점의 한 좌표 차이가 2다. 그 좌표를 세 열로 복제했을 때 원래와 복제 후 제곱거리를 구하라. 독립적인 정보 방향이 세 배인가?
One coordinate differs by two. Find squared distance before and after duplicating that coordinate into three columns. Are there three independent information directions?
풀이와 확인할 이유Solution and explanation
원래는 4, 복제 후는 4+4+4=12다. 그 방향의 무게 3과 같으며 독립적인 새 방향 세 개를 관측한 것이 아니다. 각 열을 따로 표준화해도 중복 셈 자체가 자동으로 없어지지 않는다.
The values are four and twelve. Duplication weights the original direction by three; it does not add independent directions. Standardizing each duplicate does not automatically remove repeated weighting.
49. 서로 다른데 모두 같은 거리Different vectors at the same distance
질의 (0,0), 훈련 점은 (−1,−1),(−1,1),(1,−1),(1,1)이고 결과는 10·12·14·16이다. 제곱거리·k=1 전체 동률 이웃 수·예측을 구하라.
Query the origin against four training vertices(−1,−1),(−1,1),(1,−1),(1,1), with outcomes 10,12,14,16. Find squared distances, all-tie k=1 count and prediction.
풀이와 확인할 이유Solution and explanation
모두 1+1=2라 네 행이 함께 선택된다. 예측은 52/4=13이다. 다른 벡터라도 이 질의까지의 거리가 같아 순위로 구별하지 못한다. 이를 모든 실제 고차원 분포에 대한 명제로 넓히지 않는다.
Every squared distance is two, selecting all four and predicting 13. Distinct vectors can be equally distant from one query. This construction is not a universal claim about high-dimensional real data.
50. 표준화가 관련성을 찾아 주는가Does scaling discover relevance?
질의 (0,1000), A=(0,0)·y=0, B=(1,1000)·y=10이다. 결과 관계는 첫 입력만으로 10x₁이라고 별도로 가정한다. 원척도 제곱거리, 훈련 range 척도, 둘째 가중치 0에서 k=1 예측을 비교하라.
Query(0,1000) against A=(0,0), y=0 and B=(1,1000), y=10. Separately assume the true relation is 10 times the first coordinate. Compare raw squared, training-range-scaled, and zero-second-weight k=1 predictions.
풀이와 확인할 이유Solution and explanation
원척도는 거리 1000000·1로 B를 골라 10이다. 훈련 range 1·1000으로 정규화하면 두 거리가 1로 동률이라 평균 5다. 둘째 무게 0이면 A가 거리 0이라 0이다. 가정한 질의 참평균 0에 마지막이 맞지만 range 표준화만으로 불필요한 열을 자동 발견한 것은 아니다. 실제 관련성 선택은 훈련·검증 문제다.
Raw distances choose B and predict ten. Training ranges one and 1000 give tied distances one, predicting five. Zero weight on the second coordinate selects A and predicts zero, matching the assumed query mean. Scaling alone did not discover irrelevance; actual feature selection requires training and validation.
51. 양의 평균의 범위The range of a positive weighted mean
선택한 결과는 2·8이고 음이 아닌 정규화 무게의 합은 1이다. kNN 평균이 12가 될 수 있는가? 새 입력이 훈련 범위 밖이고 실제 결과 12라면?
Selected outcomes are two and eight with nonnegative normalized weights summing to one. Can the kNN mean equal twelve? What if a query lies outside training support and its actual outcome is twelve?
풀이와 확인할 이유Solution and explanation
예측은 2λ+8(1−λ)=8−6λ이고 0≤λ≤1이므로 2와 8 사이다. 12로 외삽하지 못한다. 실제 새 결과 12는 가능하지만 이 규칙이 그 추세를 자동으로 연장하지 않는 한계를 드러낸다. 범위 밖 표지만으로 오차 크기나 인과관계를 확정하지 않는다.
2λ+8(1−λ)=8−6λ∈[2,8],0≤λ≤1
The mean 8−6λ for λ in[0,1] stays between two and eight. It cannot extrapolate to twelve, although that new outcome may occur. This is a limitation of the prediction rule, not proof of a specific error magnitude or causal mechanism from an outside-range flag.
2λ+8(1−λ)=8−6λ∈[2,8],0≤λ≤1
52. 잡음 때문에 남는 1NN 오류Persistent 1NN error under label noise
입력과 독립인 이진 결과는 Pr(Y=1)=0.7이고 훈련·새 결과는 독립이다. 거리 동률 없는 1NN의 새 결과 오류율과 Bayes 최다 범주 오류율을 구하라.
Labels are independent of features with positive probability 0.7; training and new labels are independent, with no distance ties. Compute 1NN test error and Bayes-majority error.
풀이와 확인할 이유Solution and explanation
1NN은 훈련 이웃 1·새 결과 0 또는 그 반대에서 틀려 0.7×0.3+0.3×0.7=0.42다. 항상 1을 고르는 Bayes 규칙은 0.3이다. 표본이 커져 더 가까운 입력을 얻어도 고정 1NN이 잡음 한 관측을 빌리는 이 설정에서는 Bayes 위험으로 자동 수렴하지 않는다.
R1NN=2(107)(103)=5021>103=R∗
1NN errs with probability 0.7×0.3+0.3×0.7=0.42. Always choosing class one gives Bayes error 0.3. Finding a closer feature point does not average away one noisy label, so fixed 1NN is not automatically Bayes-consistent here.
R1NN=2(107)(103)=5021>103=R∗
53. 가정한 오차식에서 k의 균형Balance k in a hypothetical error expression
실제 표본의 정확한 위험이 아니라 설명용 근사 F(k)=k²/16+1/k, k>0를 가정한다. 실수 최소 k와 정수 후보 1·2·3의 값을 구하라.
Assume an illustrative expression F(k)=k²/16+1/k for k>0, not an exact risk measured from a dataset. Find its real minimizer and values at integer candidates one, two and three.
풀이와 확인할 이유Solution and explanation
F′=k/8−1/k²=0이면 k³=8이라 k=2다. F″=1/8+2/k³>0이라 유일한 최소다. 후보 값은 17/16·3/4·43/48로 정수 비교도 2를 고른다. 이 가정식의 계산을 모든 4행 자료의 정확한 최적 k라고 부르지 않는다.
F′(k)=8k−k21=0⟺k3=8⟺k=2
The derivative vanishes at k³=8, giving two; the positive second derivative establishes uniqueness. Candidate values are 17/16,3/4,43/48, also favoring two. This is a hypothetical tradeoff expression, not a universal optimum for four-record data.
F′(k)=8k−k21=0⟺k3=8⟺k=2
54. 실제 동률 이웃 수의 분산Variance uses the actual tie-expanded count
요청 k=3이지만 전체 동률 포함으로 실제 4행이 균등 선택되었다. 오차는 독립이며 각 분산은 4다. 예측 분산은? 무조건 4/3을 써도 되는가?
Requested k=3 expands to four equally weighted neighbours. Errors are independent, each with variance four. Find prediction variance and assess using 4/3.
풀이와 확인할 이유Solution and explanation
정규화 무게는 각각 1/4이므로 분산은 4×4×(1/4)²=1이다. 4/3은 세 독립 이웃의 균등 평균 값으로 이번 실제 네 행과 다르다. 관찰의 독립성도 이 가정에서 별도로 주어졌다.
Variance is 4×4×(1/4)²=1, not 4/3. The latter belongs to three equally weighted independent neighbours. Independence itself was explicitly assumed, not inferred from source-row counts.
55. 실제 국가 이웃의 평균Average actual country neighbours
기본 Singapore 시험행의 선택 이웃 기대수명은 Australia 83.0512195121951, Germany 80.7926829268293, UK 81.3868536585366년이다. 균등 예측과 관측 83.3463414634146년과의 오차를 구하라.
Singapore’s selected default neighbours have life expectancies 83.0512195121951,80.7926829268293,81.3868536585366 years. Compute the equal-weight prediction and compare with observed 83.3463414634146.
풀이와 확인할 이유Solution and explanation
합은 245.230756097561이고 3으로 나누면 245230756097561/3000000000000≈81.7435853659년이다. 예측−관측은 약 −1.6027560976년이다. 이웃 평균의 예측오차이며 소득·실업률을 개입했을 때 기대수명 변화의 인과효과가 아니다.
The sum is 245.230756097561, giving exact prediction 245230756097561/3000000000000≈81.7435853659 years. Prediction minus observed is about−1.6027560976 years. This is a predictive discrepancy, not an income or unemployment intervention effect.
56. 개인 자료의 네 분모Four denominators in the individual case
원본 3613행에서 실습 240행을 골라 180훈련·60시험으로 나눈다. 완전 행은 145훈련·52시험이다. 미선택 수·훈련 불완전 수·시험 불완전 수·실습 완전 수 합을 구하라.
From 3,613 original rows select 240, assigning 180 training and 60 test. Complete counts are 145 and 52. Compute unselected rows, incomplete training/test rows and total complete selected rows.
풀이와 확인할 이유Solution and explanation
미선택 3373행, 훈련 불완전 35행, 시험 불완전 8행, 실습 완전 197행이다. 240−197=43은 선택 자료 안의 불완전 수이며 전체 원본의 결측 수라고 쓸 수 없다. 미선택과 결측을 구분하고 빠진 임금을 0으로 채우지 않는다.
Counts are 3,373 unselected,35 incomplete training, eight incomplete test and 197 complete selected records. The 43 incomplete selected rows are not the missing count of the entire original archive. Selection differs from missingness.
57. 13개 경계 동률의 실제 임금Actual wages with thirteen boundary ties
개인 첫 시험 ID79는 교육 11년·나이 24·관측 임금 235센트/시간이다. 훈련 교육 range 13에서 교육 10 또는 12·나이 24인 13행이 k=3 경계 동률로 선택되고 임금 합은 5664다. 경계 제곱거리·예측·잔차를 구하라.
Individual test ID 79 has schooling 11, age 24 and wage 235 cents/hour. Thirteen training rows at schooling 10 or 12 and age 24 tie at the k=3 boundary, with wage sum 5664 and training schooling range 13. Find squared boundary distance, prediction and residual.
풀이와 확인할 이유Solution and explanation
제곱거리는 (1/13)²=1/169이다. 전체 동률 평균은 5664/13≈435.6923센트/시간, 예측−관측은 2609/13≈200.6923이다. 제곱오차는 6806881/169다. 실제 분모 13을 3으로 바꾸거나 원래 센트를 달러로 오해하지 않는다.
y=135664,y−y=132609,(y−y)2=1696806881
Boundary squared distance is 1/169. The prediction is 5664/13≈435.6923 cents/hour, with prediction-minus-observed residual 2609/13≈200.6923 and squared error 6806881/169. Use all thirteen rows and preserve cents-per-hour units.
y=135664,y−y=132609,(y−y)2=1696806881
58. 실제 고객의 확률과 범주 오차Probability and class error for an actual customer row
기업 첫 시험 원행 40의 관측 Churn은 0이다. 고정 range·k=3의 이웃 원행 528·80·607의 표지는 1·0·0이고 무게는 같다. 이탈 확률·예측 범주·Brier·0–1 오류를 구하라.
Business test source row 40 has actual Churn 0. Its fixed range-scaled k=3 neighbours 528,80,607 have labels 1,0,0 with equal weights. Compute probability, action, Brier and class error.
풀이와 확인할 이유Solution and explanation
이탈 확률 1/3·비이탈 2/3이라 기본 예측은 0이다. 범주는 맞아 오류 0이지만 Brier는 (1/3−0)²=1/9다. 맞는 범주와 확률오차 0은 같지 않다. 이 확률만으로 연락을 하면 이탈이 줄어든다는 인과효과를 알 수도 없다.
p1=31,LB=(31−0)2=91,L01=0
Positive probability is 1/3, selecting class zero. Class error is zero but Brier is 1/9. A correct action does not imply zero probability error, and this prediction does not identify the effect of a retention contact.
p1=31,LB=(31−0)2=91,L01=0
59. 검증 성공과 시험 실패Validation improvement and test failure
국가 k=3의 훈련 CV MSE는 약 9.6839로 기준 22.4077보다 작다. 시험 MSE는 52.9043으로 기준 51.0621보다 크다. 모순인가? 시험을 보고 k를 바꾸어 CV 선택 결과라고 보고해도 되는가?
Country k=3 has CV MSE about 9.6839 versus baseline 22.4077, but test MSE 52.9043 versus 51.0621. Is this contradictory? May k be changed after viewing test scores while retaining the CV-selection label?
풀이와 확인할 이유Solution and explanation
표본과 훈련 구성·지원점이 다른 평가라 모순이 아니다. 작은 네 국가 시험에서 특이한 입력이나 예측오차가 영향을 줄 수 있지만 그 원인을 숫자 두 개만으로 확정하지 않는다. 시험을 보고 선택을 바꾸면 새 절차이며 원 CV 선택과 구별해야 한다. 실패한 시험 결과도 그대로 보존한다.
Different training compositions and evaluation units can give different results without contradiction. A four-country test can be influenced by unusual inputs, but two scores alone do not establish the cause. Changing k after inspection is a new selection procedure, which must be distinguished from the original CV protocol.
60. 원행부터 재현하는 보고서A report reproducible from original records
세 실제 사례 중 하나를 골라 이웃 예측 보고서를 쓴다. 원자료·목표·선택·스케일·동률·평가·한계를 다른 사람이 재현하도록 무엇을 기록할지 설명하라.
Choose one actual case and specify what a reproducible neighbour-prediction report must record about source, target, selection, scaling, ties, evaluation and limitations.
풀이와 확인할 이유Solution and explanation
원파일·원행 위치·연도·단위와 입력/결과 정의를 적고, 실습 위치 표집·훈련/시험/fold·결측·0무게 분모를 밝힌다. 거리·좌표 무게·훈련 전용 척도와 버린 좌표·k·경계 동률·0거리 규약을 공개한다. 한 질의를 원거리→원행→정규화 기여→예측→관측 결과→손실로 따라가고 전체 평가 행·기준 모형·Brier 정의를 대조한다. CV 선택과 고정 민감도 표를 구분하며 전체 CSV·독립 Python/R·정확값·그래프를 제공한다. 실제 자료와 정확한 산술이 인과·전 세계 대표성·미래 성능·일치성 정리를 자동 보증하지 않음을 표적과 연결해 설명한다.
Record original files, positions, dates, units and predictor/outcome definitions; disclose selection, roles, folds, missingness and zero-weight denominators. State metric, coordinate weights, training-only scales, dropped coordinates, k, boundary ties and zero-distance rules. Trace one query through distances, source rows, normalized contributions, prediction, actual outcome and loss, then compare all evaluable rows with baselines under a fixed Brier convention. Separate CV selection from sensitivity profiles and supply complete CSVs, standalone Python/R, exact values and graphs. Explain why authentic data and exact arithmetic do not automatically establish causality, representativeness, future performance or consistency.
자료별 확보일·원행 식별·단위·이용 조건은 출처 기록을 확인하세요. 학습 사본은 제공처의 현재 최신 자료와 다를 수 있습니다.Consult each source record for retrieval dates, row identifiers, units and terms. Teaching copies can differ from current provider releases.