Kaggle Intermediate ML Part Two

98 篇文章 0 订阅
66 篇文章 0 订阅
本文介绍了类别变量,包括它们的定义、类型(名义和序数)、在数据分析中的重要性以及处理方法,如Ordinal编码和One-Hot编码。还讨论了数据的卡方特性和独立/依赖变量的概念,以及如何使用散点图展示两者的关系。
摘要由CSDN通过智能技术生成

Categorical Variables

Categorical variables, also known as qualitative variables, are a fundamental concept in statistics and data analysis. Here's a breakdown to help you understand them:

What are they?

  • Categorical variables represent qualities or groups rather than quantities. They classify data points based on certain characteristics, like "color," "fruit type," or "customer satisfaction level."
  • Unlike numerical variables that have measurable values (e.g., height, weight, price), categorical variables don't have inherent numerical order. You can't say "blue" is "bigger" than "red."

Types of Categorical Variables:

  • Nominal: These have distinct categories with no inherent order. Examples: hair color (blonde, brown, black), blood type (A, B, AB, O), country of origin.
  • Ordinal: These have categories with a natural order, but the distances between categories may not be equal. Examples: customer satisfaction (very satisfied, satisfied, neutral, dissatisfied, very dissatisfied), movie rating (1-5 stars), education level (high school diploma, bachelor's degree, master's degree).

Why are they important?

  • Categorical variables are crucial for understanding group differences, relationships between variables, and patterns in qualitative data.
  • They are used in various analyses, like chi-square tests, ANOVA, and logistic regression.

Things to remember:

  • Sometimes, categorical variables are encoded numerically for analysis. However, the numbers assigned don't represent inherent order or magnitude.
  • Be cautious when interpreting results involving categorical variables, especially when comparing groups. Focus on group differences and proportions, not the specific numerical values assigned.

Ordinal Encoding

In machine learning, categorical data often needs to be converted into numerical representations for algorithms to process them effectively. Ordinal encoding is a technique that assigns integer values to categories based on their inherent order or ranking. This is suitable for variables where the order between categories matters, such as:

  • T-shirt sizes (Small, Medium, Large)
  • Customer satisfaction ratings (Poor, Fair, Good, Excellent)
  • Education levels (Primary, Secondary, Bachelor's, Master's)

Key Points:

  • Preserves ordinal relationships: Categories with higher rankings get higher encoded values.
  • Simple and efficient for limited number of categories.
  • Not suitable for nominal data (categories without intrinsic order, e.g., shirt colors).
  • Can introduce artificial distance between categories, impacting algorithms reliant on distances (e.g., Euclidean distance).

Example in Python:

import pandas as pd

# Sample data
data = {
    'Color': ['Red', 'Blue', 'Green', 'Red', 'Green', 'Blue'],
    'Size': ['S', 'L', 'M', 'M', 'M', 'L']
}
df = pd.DataFrame(data)

# Ordinal encode 'Color' (assuming Red < Blue < Green)
from sklearn.preprocessing import OrdinalEncoder

encoder = OrdinalEncoder(categories=[['Red', 'Blue', 'Green']])
encoded_color = encoder.fit_transform(df[['Color']])

# Show results
print(df)
print("\nEncoded 'Color':")
print(encoded_color)

# Ordinal encode 'Size' (assuming S < M < L)
encoded_size = encoder.fit_transform(df[['Size']])
print("\nEncoded 'Size':")
print(encoded_size)

One-Hot Encoding

In machine learning, one-hot encoding is a technique used to represent categorical variables as numerical vectors suitable for use in algorithms that expect numerical inputs. It works by creating a new binary vector, with one position for each category in the original variable. The position corresponding to the actual category value is set to 1, while all other positions are set to 0.

Illustration:

Imagine you have a categorical variable representing eye color with three possible values: "blue", "brown", and "green". Here's how one-hot encoding would work:

Original ValueOne-Hot Encoded Vector
"blue"[1, 0, 0]
"brown"[0, 1, 0]
"green"[0, 0, 1]

drive_spreadsheet导出到 Google 表格

You can see that each vector has a length equal to the number of categories (3 in this case), and only one value in the vector is 1, indicating the actual category.

Advantages:

  • Makes categorical data understandable by numerical algorithms.
  • Allows machine learning models to treat different categories equally, without assuming an inherent order between them.

Disadvantages:

  • Can increase the dimensionality of the data, potentially leading to overfitting or computational challenges.
  • Not suitable for features with many categories, as it can create very sparse data representations.

Python Example:

# Import libraries
import pandas as pd
from sklearn.preprocessing import OneHotEncoder

# Create sample data
data = {'color': ['blue', 'brown', 'green', 'blue', 'brown']}
df = pd.DataFrame(data)

# One-hot encode the 'color' column
encoder = OneHotEncoder(sparse=False)  # Specify 'sparse=False' for a dense array
encoded_df = pd.DataFrame(encoder.fit_transform(df[['color']]), columns=['blue', 'brown', 'green'])

# Combine original and encoded data
df_combined = pd.concat([df, encoded_df], axis=1)

print(df_combined)

Investigating cardinality

Cardinality refers to the number of unique elements in a set. Think of it as the size of a bucket containing unique items. In different contexts, cardinality can refer to:

1. Set Cardinality:

  • Sets in Python are collections of unique elements.
  • The len() function tells you the cardinality of a set.
my_set = {1, 2, 3, 2, 4}  # Duplicate values are removed
print(len(my_set))  # Output: 4 (unique elements: 1, 2, 3, 4)

2. Cardinality in Relations (Databases):

  • In databases, Cardinality describes the relationship between tables.
  • One-to-One: Each element in one table relates to one element in another (e.g., UserID to ProfileID).
  • One-to-Many: One element in one table relates to many elements in another (e.g., Author to Books).
  • Many-to-One: Many elements in one table relate to one element in another (e.g., Orders to Customer).
  • Many-to-Many: Many elements in one table relate to many elements in another (e.g., Users to Courses).

3. Cardinality in Statistics:

  • Cardinality describes the number of possible values a variable can take.
  • Low Cardinality: Variable has few unique values (e.g., Gender: Male/Female).
  • High Cardinality: Variable has many unique values (e.g., Usernames).

Independent variable

An independent variable is a variable that is changed by the experimenter in a scientific experiment. It is the variable that is tested to see how it affects the dependent variable. The independent variable is also called the "controlled variable" or the "manipulated variable."

Dependent variable

A dependent variable is a variable that is affected by the independent variable. It is the variable that is measured in a scientific experiment. The dependent variable is also called the "responding variable" or the "measured variable."

Scatter plot

A scatter plot is a type of graph that shows the relationship between two variables. The independent variable is plotted on the x-axis, and the dependent variable is plotted on the y-axis. Each data point is represented by a dot on the graph. The dots are then connected with a line to show the trend of the data.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

P("Struggler") ?

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值