python-3.x - 分类数据的响应编码
问题描述
响应编码是一种矢量化分类数据的技术。假设我们有一个名为“grade_category”的分类特征,它具有以下唯一标签 - ['grades_3_5'、'grades_prek_2'、'grades_9_12'、'grades_6_8']。假设我们正在处理目标类标签为 0 和 1 的分类问题
在响应编码中,您必须为我们的特征中的每个标签输出概率值,该标签与特定的类标签一起出现,例如,grades_prek_2 = [它出现在 class_0 中的概率,它出现在类 1 中的概率]
解决方案
def response_coding(xtrain, ytrain, feature):
""" this method will encode the categorical features
using response_coding technique.
args:
xtrain, ytrain, feature (all are ndarray)
returns:
dictionary (dict)
"""
dictionary = dict()
x = PrettyTable()
x = PrettyTable([feature, 'class 1', 'class 0'])
unique_cat_labels = xtrain[feature].unique()
for i in tqdm(range(len(unique_cat_labels))):
total_count = xtrain.loc[:,feature][(xtrain[feature] == unique_cat_labels[i])].count()
p_0 = xtrain.loc[:, feature][((xtrain[feature] == unique_cat_labels[i]) & (ytrain==0))].count()
p_1 = xtrain.loc[:, feature][((xtrain[feature] == unique_cat_labels[i]) & (ytrain==1))].count()
dictionary[unique_cat_labels[i]] = [p_1/total_count, p_0/total_count]
row = []
row.append(unique_cat_labels[i])
row.append(p_1/total_count)
row.append(p_0/total_count)
x.add_row(row)
print()
print(x)[![enter image description here][1]][1]
return dictionary
推荐阅读
- c++ - C++ lambda 中的可选/忽略参数,或基于 lambda 签名的重载解析
- vue.js - Vue 模式避免循环依赖:在 Vuex 存储和组件中使用模型(类模块)并存储在模型中?
- c# - 如何对使用 LINQ 表达式返回的各个行的特定列属性的值求和?(C#)
- python - Python 3.9 中的张量流问题
- java - AspectJ:建议不适用于数组类型
- javascript - Javascript窗口对象,window+'',这段代码是做什么的
- node.js - 现在显示 URL 图片 discord.js
- haskell - 如何从 SomeException (或任何其他自定义异常)中获取堆栈跟踪?
- html - Blazor Telerik Grid 从数据中设置单元格颜色
- php - Laravel - 发送邮件后无法重定向