차원이라는 용어는 특징 벡터의 요소 수와 동의어입니다.
일부 범주형 특성은 차원이 낮습니다. 예를 들면 다음과 같습니다.
기능 이름
카테고리 수
샘플 카테고리
snowed_today
2
True, False
skill_level
3
초급, 실무자, 전문가
season
4
겨울, 봄, 여름, 가을
day_of_week
7
월요일, 화요일, 수요일
행성
8
수성, 금성, 지구
범주형 특성에 가능한 카테고리 수가 적은 경우 어휘로 인코딩할 수 있습니다. 어휘 인코딩을 사용하면 모델에서 가능한 각 범주형 값을 별도의 특성으로 처리합니다. 학습 중에 모델은 카테고리별로 다른 가중치를 학습합니다.
예를 들어 car_color이라는 범주형 특성을 기반으로 자동차 가격을 예측하는 모델을 만든다고 가정해 보겠습니다.
빨간색 자동차가 녹색 자동차보다 가치가 더 높을 수도 있습니다.
제조업체에서 제공하는 외장 색상은 제한적이므로 car_color는 저차원 범주형 특성입니다.
다음 그림은 car_color의 어휘 (가능한 값)를 보여줍니다.
그림 1. 카테고리별 고유한 기능
연습: 학습 내용 점검하기
참 또는 거짓: 머신러닝 모델은 이러한 값을 숫자 벡터로 변환하지 않고 'Red' 및 'Black'과 같은 원시 문자열 값에 대해 직접 학습할 수 있습니다.
참
학습 중에 모델은 부동 소수점 숫자만 조작할 수 있습니다.
"Red" 문자열은 부동 소수점 숫자가 아닙니다. "Red"과 같은 문자열을 부동 소수점 숫자로 변환해야 합니다.
거짓
머신러닝 모델은 부동 소수점 값이 있는 특성에서만 학습할 수 있으므로 학습 전에 이러한 문자열을 부동 소수점 값으로 변환해야 합니다.
색인 번호
머신러닝 모델은 부동 소수점 숫자만 조작할 수 있습니다.
따라서 다음 그림과 같이 각 문자열을 고유한 색인 번호로 변환해야 합니다.
그림 2. 색인이 생성된 특성입니다.
문자열을 고유한 색인 번호로 변환한 후 모델이 값 간의 의미 있는 관계를 학습하는 데 도움이 되는 방식으로 데이터를 추가로 처리해야 합니다. 범주형 특성 데이터가 색인이 생성된 정수로 남아 모델에 로드되면 모델은 색인이 생성된 값을 연속 부동 소수점 숫자로 처리합니다. 그러면 모델은 '주황색'보다 '보라색'이 6배 더 가능하다고 간주합니다.
원-핫 인코딩
어휘를 빌드하는 다음 단계는 각 색인 번호를 원-핫 인코딩으로 변환하는 것입니다.
원-핫 인코딩에서
각 카테고리는 N개의 요소로 구성된 벡터 (배열)로 표시됩니다. 여기서 N은 카테고리 수입니다. 예를 들어 car_color에 가능한 카테고리가 8개 있으면 이를 나타내는 원-핫 벡터에는 8개의 요소가 있습니다.
원핫 벡터의 요소 중 하나만 값 1.0을 갖고 나머지 요소는 모두 값 0.0을 갖습니다.
예를 들어 다음 표는 car_color의 각 색상에 대한 원-핫 인코딩을 보여줍니다.
기능
빨간색
주황색
파란색
노란색
초록색
검은색
보라색
갈색
"Red"
1
0
0
0
0
0
0
0
"Orange"
0
1
0
0
0
0
0
0
"Blue"
0
0
1
0
0
0
0
0
'노란색'
0
0
0
1
0
0
0
0
"Green"
0
0
0
0
1
0
0
0
'Black'
0
0
0
0
0
1
0
0
"보라색"
0
0
0
0
0
0
1
0
'Brown'
0
0
0
0
0
0
0
1
문자열이나 인덱스 번호가 아닌 원-핫 벡터가 특성 벡터에 전달됩니다. 모델은 특성 벡터의 각 요소에 대해 별도의 가중치를 학습합니다.
다음 그림은 어휘 표현의 다양한 변환을 보여줍니다.
그림 3. 카테고리를 특징 벡터에 매핑하는 엔드 투 엔드 프로세스
희소 표현
값이 대부분 0 (또는 비어 있음)인 특징을 희소 특징이라고 합니다. car_color와 같은 많은 범주형 특성은 희소 특성인 경향이 있습니다.
희소 표현은 희소 벡터에 1.0의 위치를 저장하는 것을 의미합니다. 예를 들어 "Blue"의 원-핫 벡터는 다음과 같습니다.
[0, 0, 1, 0, 0, 0, 0, 0]
1은 2번 위치에 있으므로 (0부터 계산) 앞의 원-핫 벡터의 희소 표현은 다음과 같습니다.
2
희소 표현은 8개 요소의 원-핫 벡터보다 훨씬 적은 메모리를 사용합니다. 중요한 점은 모델이 희소 표현이 아닌 원-핫 벡터로 학습해야 한다는 것입니다.
범주형 데이터의 이상치
숫자 데이터와 마찬가지로 범주형 데이터에도 이상치가 포함됩니다. car_color에는 인기 있는 색상뿐만 아니라 "Mauve" 또는 "Avocado"와 같이 거의 사용되지 않는 이상치 색상도 포함되어 있다고 가정해 보겠습니다.
이러한 이상치 색상에 각각 별도의 카테고리를 부여하는 대신 어휘 외(OOV)라는 단일 '기타' 카테고리로 묶을 수 있습니다. 즉, 모든 이상치 색상이 하나의 이상치 버킷으로 분류됩니다. 시스템은 이상치 버킷에 대해 단일 가중치를 학습합니다.
고차원 범주형 특성 인코딩
일부 범주형 특성에는 다음 표와 같이 차원 수가 많습니다.
기능 이름
카테고리 수
샘플 카테고리
words_in_english
~500,000
'happy', 'walking'
US_postal_codes
~42,000
'02114', '90301'
last_names_in_Germany
~850,000
'Schmidt', 'Schneider'
카테고리 수가 많은 경우 일반적으로 원-핫 인코딩은 좋지 않습니다.
별도의 임베딩 모듈에 자세히 설명된 임베딩이 훨씬 더 나은 선택인 경우가 많습니다. 임베딩은 차원 수를 크게 줄여 모델에 다음과 같은 두 가지 중요한 이점을 제공합니다.
일반적으로 모델이 더 빠르게 학습합니다.
빌드된 모델은 일반적으로 더 빠르게 예측을 추론합니다. 즉, 모델의 지연 시간이 짧습니다.
[[["이해하기 쉬움","easyToUnderstand","thumb-up"],["문제가 해결됨","solvedMyProblem","thumb-up"],["기타","otherUp","thumb-up"]],[["필요한 정보가 없음","missingTheInformationINeed","thumb-down"],["너무 복잡함/단계 수가 너무 많음","tooComplicatedTooManySteps","thumb-down"],["오래됨","outOfDate","thumb-down"],["번역 문제","translationIssue","thumb-down"],["샘플/코드 문제","samplesCodeIssue","thumb-down"],["기타","otherDown","thumb-down"]],["최종 업데이트: 2025-08-06(UTC)"],[[["\u003cp\u003eDimension refers to the number of elements in a feature vector, and some categorical features have low dimensionality.\u003c/p\u003e\n"],["\u003cp\u003eMachine learning models require numerical input; therefore, categorical data like strings must be converted to numerical representations.\u003c/p\u003e\n"],["\u003cp\u003eOne-hot encoding transforms categorical values into numerical vectors where each category is represented by a unique element with a value of 1.\u003c/p\u003e\n"],["\u003cp\u003eFor high-dimensional categorical features with numerous categories, one-hot encoding might be inefficient, and embeddings or hashing are recommended.\u003c/p\u003e\n"],["\u003cp\u003eSparse representation efficiently stores one-hot encoded data by only recording the position of the '1' value to reduce memory usage.\u003c/p\u003e\n"]]],[],null,["The term **dimension** is a synonym for the number of elements in a\n[**feature vector**](/machine-learning/glossary#feature_vector).\nSome categorical features are low dimensional. For example:\n\n| Feature name | # of categories | Sample categories |\n|--------------|-----------------|--------------------------------|\n| snowed_today | 2 | True, False |\n| skill_level | 3 | Beginner, Practitioner, Expert |\n| season | 4 | Winter, Spring, Summer, Autumn |\n| day_of_week | 7 | Monday, Tuesday, Wednesday |\n| planet | 8 | Mercury, Venus, Earth |\n\nWhen a categorical feature has a low number of possible categories, you can\nencode it as a **vocabulary** . With a vocabulary encoding, the model treats each\npossible categorical value as a *separate feature*. During training, the\nmodel learns different weights for each category.\n\nFor example, suppose you are creating a model to predict a car's price based,\nin part, on a categorical feature named `car_color`.\nPerhaps red cars are worth more than green cars.\nSince manufacturers offer a limited number of exterior colors, `car_color` is\na low-dimensional categorical feature.\nThe following illustration suggests a vocabulary (possible values) for\n`car_color`:\n**Figure 1.** A unique feature for each category.\n\nExercise: Check your understanding \nTrue or False: A machine learning model can train *directly* on raw string values, like \"Red\" and \"Black\", without converting these values to numerical vectors. \nTrue \nDuring training, a model can only manipulate floating-point numbers. The string `\"Red\"` is not a floating-point number. You must convert strings like `\"Red\"` to floating-point numbers. \nFalse \nA machine learning model can only train on features with floating-point values, so you'll need to convert those strings to floating-point values before training.\n\nIndex numbers\n\nMachine learning models can only manipulate floating-point numbers.\nTherefore, you must convert each string to a unique index number, as in\nthe following illustration:\n**Figure 2.** Indexed features.\n\nAfter converting strings to unique index numbers, you'll need to process the\ndata further to represent it in ways that help the model learn meaningful\nrelationships between the values. If the categorical feature data is left as\nindexed integers and loaded into a model, the model would treat the indexed\nvalues as continuous floating-point numbers. The model would then consider\n\"purple\" six times more likely than \"orange.\"\n\nOne-hot encoding\n\nThe next step in building a vocabulary is to convert each index number to\nits [**one-hot encoding**](/machine-learning/glossary#one-hot_encoding).\nIn a one-hot encoding:\n\n- Each category is represented by a vector (array) of N elements, where N is the number of categories. For example, if `car_color` has eight possible categories, then the one-hot vector representing will have eight elements.\n- Exactly *one* of the elements in a one-hot vector has the value 1.0; all the remaining elements have the value 0.0.\n\nFor example, the following table shows the one-hot encoding for each in\n`car_color`:\n\n| Feature | Red | Orange | Blue | Yellow | Green | Black | Purple | Brown |\n|----------|-----|--------|------|--------|-------|-------|--------|-------|\n| \"Red\" | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |\n| \"Orange\" | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 |\n| \"Blue\" | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 |\n| \"Yellow\" | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 |\n| \"Green\" | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 |\n| \"Black\" | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 |\n| \"Purple\" | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 |\n| \"Brown\" | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 |\n\nIt is the one-hot vector, not the string or the index number, that gets passed\nto the feature vector. The model learns a separate weight for each element of\nthe feature vector.\n| **Note:** In a true one-hot encoding, only one element has the value 1.0. In a variant known as **multi-hot encoding**, multiple values can be 1.0.\n\nThe following illustration suggests the various transformations in the\nvocabulary representation:\n**Figure 3.** The end-to-end process to map categories to feature vectors.\n\nSparse representation\n\nA feature whose values are predominately zero (or empty) is termed a\n[**sparse feature**](/machine-learning/glossary#sparse-feature). Many\ncategorical features, such as `car_color`, tend to be sparse features.\n[**Sparse representation**](/machine-learning/glossary#sparse-representation)\nmeans storing the *position* of the 1.0\nin a sparse vector. For example, the one-hot vector for `\"Blue\"` is:\n\u003e \\[0, 0, 1, 0, 0, 0, 0, 0\\]\n\nSince the `1` is in position 2 (when starting the count at 0), the\nsparse representation for the preceding one-hot vector is:\n\u003e 2\n\nNotice that the sparse representation consumes far less memory than the\neight-element one-hot vector. Importantly, the model must *train* on the\none-hot vector, not the sparse representation.\n| **Note:** The sparse representation of a multi-hot encoding stores the positions of *all* the nonzero elements. For example, the sparse representation of a car that is both `\"Blue\"` and `\"Black\"` is `2, 5`.\n\nOutliers in categorical data\n\nLike numerical data, categorical data also contains outliers. Suppose\n`car_color` contains not only the popular colors, but also some rarely used\noutlier colors, such as `\"Mauve\"` or `\"Avocado\"`.\nRather than giving each of these outlier colors a separate category, you\ncan lump them into a single \"catch-all\" category called *out-of-vocabulary\n(OOV)*. In other words, all the outlier colors are binned into a single\noutlier bucket. The system learns a single weight for that outlier bucket.\n\nEncoding high-dimensional categorical features\n\nSome categorical features have a high number of dimensions, such as\nthose in the following table:\n\n| Feature name | # of categories | Sample categories |\n|-----------------------|-----------------|------------------------|\n| words_in_english | \\~500,000 | \"happy\", \"walking\" |\n| US_postal_codes | \\~42,000 | \"02114\", \"90301\" |\n| last_names_in_Germany | \\~850,000 | \"Schmidt\", \"Schneider\" |\n\nWhen the number of categories is high, one-hot encoding is usually a bad choice.\n*Embeddings* , detailed in a separate\n[Embeddings module](/machine-learning/crash-course/embeddings), are usually\na much better choice. Embeddings substantially reduce the number of\ndimensions, which benefits models in two important ways:\n\n- The model typically trains faster.\n- The built model typically infers predictions more quickly. That is, the model has lower latency.\n\n[**Hashing**](/machine-learning/glossary#hashing) (also called the *hashing\ntrick*) is a less common way to reduce the number of dimensions.\n**Click here to learn about hashing** \nIn brief, hashing maps a category (for example, a color) to a small\ninteger---the number of the \"bucket\" that will hold that category.\n\nIn detail, you implement a hashing algorithm as follows:\n\n1. Set the number of bins in the vector of categories to N, where N is less than the total number of remaining categories. As an arbitrary example, say N = 100.\n2. Choose a hash function. (Often, you will choose the range of hash values as well.)\n3. Pass each category (for example, a particular color) through that hash function, generating a hash value, say 89237.\n4. Assign each bin an index number of the output hash value modulo N. In this case, where N is 100 and the hash value is 89237, the modulo result is 37 because 89237 % 100 is 37.\n5. Create a one-hot encoding for each bin with these new index numbers.\n\nFor more details about hashing data, see the\n[Randomization](/machine-learning/crash-course/production-ml-systems/monitoring#randomization)\nsection of the\n[Production machine learning systems](/machine-learning/crash-course/production-ml-systems/monitoring)\nmodule.\n| **Key terms:**\n|\n| - [Categorical data](/machine-learning/glossary#categorical_data)\n| - [Dimensions](/machine-learning/glossary#dimensions)\n| - [Discrete feature](/machine-learning/glossary#discrete_feature)\n| - [Feature cross](/machine-learning/glossary#feature_cross)\n| - [Feature vector](/machine-learning/glossary#feature_vector)\n| - [Hashing](/machine-learning/glossary#hashing)\n| - [One-hot encoding](/machine-learning/glossary#one-hot_encoding)\n| - [Sparse feature](/machine-learning/glossary#sparse-feature)\n- [Sparse representation](/machine-learning/glossary#sparse-representation) \n[Help Center](https://support.google.com/machinelearningeducation)"]]