Pandas Dataframe¶
设置¶
输入 [ ]
已复制!
pip install ydf pandas -U
pip install ydf pandas -U
输入 [8]
已复制!
import ydf
import pandas as pd
import numpy as np
# Create a small dataframe with different column types.
df = pd.DataFrame(
{"feature_1": [1, 2, 3, 1] * 20, # A numerical feature
"feature_2": ["X", "X", "Y", "Y"] * 20, # A categorical feature
"feature_3": [True, False, True, False ] * 20, # A boolean feature
"label": [True, True, False, False ] * 20, # The labels
})
df.head()
import ydf import pandas as pd import numpy as np # 创建一个包含不同列类型的小型 dataframe。 df = pd.DataFrame( {"feature_1": [1, 2, 3, 1] * 20, # 一个数值型特征 "feature_2": ["X", "X", "Y", "Y"] * 20, # 一个类别型特征 "feature_3": [True, False, True, False ] * 20, # 一个布尔型特征 "label": [True, True, False, False ] * 20, # 标签 }) df.head()
输出 [8]
feature_1 | feature_2 | feature_3 | label | |
---|---|---|---|---|
0 | 1 | X | True | True |
1 | 2 | X | False | True |
2 | 3 | Y | True | False |
3 | 1 | Y | False | False |
4 | 1 | X | True | True |
我们可以直接在这个 dataframe 上训练模型。
输入 [4]
已复制!
# Train a model.
model = ydf.RandomForestLearner(label="label").train(df)
# 训练一个模型。 model = ydf.RandomForestLearner(label="label").train(df)
Train model on 80 examples Model trained in 0:00:00.003959
输入 [5]
已复制!
model.describe()
model.describe()
输出 [5]
名称 : RANDOM_FOREST
任务 : CLASSIFICATION
标签 : label
特征 (3) : feature_1 feature_2 feature_3
权重 : None
使用调优器训练 : No
模型大小 : 257 kB
任务 : CLASSIFICATION
标签 : label
特征 (3) : feature_1 feature_2 feature_3
权重 : None
使用调优器训练 : No
模型大小 : 257 kB
Number of records: 80 Number of columns: 4 Number of columns by type: CATEGORICAL: 2 (50%) BOOLEAN: 1 (25%) NUMERICAL: 1 (25%) Columns: CATEGORICAL: 2 (50%) 0: "label" CATEGORICAL has-dict vocab-size:3 zero-ood-items most-frequent:"false" 40 (50%) dtype:DTYPE_BOOL 2: "feature_2" CATEGORICAL has-dict vocab-size:3 zero-ood-items most-frequent:"X" 40 (50%) dtype:DTYPE_BYTES BOOLEAN: 1 (25%) 3: "feature_3" BOOLEAN true_count:40 false_count:40 dtype:DTYPE_BOOL NUMERICAL: 1 (25%) 1: "feature_1" NUMERICAL mean:1.75 min:1 max:3 sd:0.829156 dtype:DTYPE_FLOAT64 Terminology: nas: Number of non-available (i.e. missing) values. ood: Out of dictionary. manually-defined: Attribute whose type is manually defined by the user, i.e., the type was not automatically inferred. tokenized: The attribute value is obtained through tokenization. has-dict: The attribute is attached to a string dictionary e.g. a categorical attribute stored as a string. vocab-size: Number of unique values.
以下评估是在验证集或袋外数据集上计算的。
Number of predictions (without weights): 80 Number of predictions (with weights): 80 Task: CLASSIFICATION Label: label Accuracy: 1 CI95[W][0.963246 1] LogLoss: : 0 ErrorRate: : 0 Default Accuracy: : 0.5 Default LogLoss: : 0.693147 Default ErrorRate: : 0.5 Confusion Table: truth\prediction false true false 40 0 true 0 40 Total: 80
变量重要性衡量输入特征对模型的重要性。
1. "feature_2" 1.000000
1. "feature_2" 300.000000
1. "feature_2" 300.000000
1. "feature_2" 16479.940276
这些变量重要性是在训练期间计算的。在测试数据集上分析模型时,可以获得更多(可能也更有信息量)的变量重要性。
树的数量 : 300
只打印第一棵树。
Tree #0: "feature_2" is in [BITMAP] {X} [s:0.692835 n:80 np:39 miss:0] ; val:"false" prob:[0.5125, 0.4875] ├─(pos)─ val:"true" prob:[0, 1] └─(neg)─ val:"false" prob:[1, 0]
输入 [7]
已复制!
model = ydf.RandomForestLearner(
label="label",
features=["feature_1", "feature_2"]
).train(df)
print("Model input features:", model.input_feature_names())
model = ydf.RandomForestLearner( label="label", features=["feature_1", "feature_2"] ).train(df) print("模型输入特征:", model.input_feature_names())
Train model on 80 examples Model trained in 0:00:00.003908 Model input features: ['feature_1', 'feature_2']
覆盖特征语义¶
为了使用一个特征,模型需要知道如何解释这个特征。这被称为特征“语义”。YDF 支持四种特征语义类型:
- 数值型: 用于表示数量或度量。
- 类别型: 用于表示类别或枚举。
- 布尔型: 一种特殊的类别型,只有 True 和 False 两个类别。
- 类别集: 用于表示类别集合、标签或词袋。
YDF 会根据特征的表示自动确定其语义。例如,浮点数和整数值会被自动检测为数值型。
例如,以下是上面训练的模型的语义:
输入 [9]
已复制!
model.input_features()
model.input_features()
输出 [9]
[InputFeature(name='feature_1', semantic=<Semantic.NUMERICAL: 1>, column_idx=0), InputFeature(name='feature_2', semantic=<Semantic.CATEGORICAL: 2>, column_idx=1)]
在某些情况下,强制使用特定的语义很有趣。例如,如果枚举值用整数表示,则强制将特征设为类别型很重要。
输入 [11]
已复制!
model = ydf.RandomForestLearner(
label="label",
features=[ydf.Feature("feature_1", ydf.Semantic.CATEGORICAL)],
include_all_columns=True # Use all the features; not just the ones in "features".
).train(df)
model.input_features()
model = ydf.RandomForestLearner( label="label", features=[ydf.Feature("feature_1", ydf.Semantic.CATEGORICAL)], include_all_columns=True # 使用所有特征;而不仅仅是 "features" 中的特征。 ).train(df) model.input_features()
Train model on 80 examples Model trained in 0:00:00.004236
输出 [11]
[InputFeature(name='feature_1', semantic=<Semantic.CATEGORICAL: 2>, column_idx=0), InputFeature(name='feature_2', semantic=<Semantic.CATEGORICAL: 2>, column_idx=2), InputFeature(name='feature_3', semantic=<Semantic.BOOLEAN: 5>, column_idx=3)]