【发布时间】:2020-05-20 10:13:11
【问题描述】:
对于学校项目,需要将 keras 模型训练到 Titanic 数据集。 我正在尝试将分类列编码为二进制矩阵并替换当前的字符串值,遗憾的是我无法管理它。在下面的示例中,我将“男性”和“女性”编码为二进制表示。
to_categorical 的结果:
[[0. 1.]
[1. 0.]
[1. 0.]
...
[1. 0.]
[1. 0.]
[0. 1.]]
替换当前值时的结果:
0 0.0
1 1.0
2 1.0
3 1.0
4 0.0
...
622 0.0
623 0.0
624 1.0
625 1.0
626 0.0
想要的结果:
0 [0. 1.]
1 [1. 0.]
2 [1. 0.]
3 [1. 0.]
4 [0. 1.]
...
622 [0. 1.]
623 [0. 1.]
624 [1. 0.]
625 [1. 0.]
626 [0. 1.]
我对 Python 和 Keras 非常陌生。任何帮助将不胜感激。
label_encoder = LabelEncoder()
CATEGORICAL_COLUMNS = ['sex', 'class', 'deck', 'embark_town', 'alone']
NUMERIC_COLUMNS = ['age', 'n_siblings_spouses', 'parch', 'fare']
df = pd.read_csv('https://storage.googleapis.com/tf-datasets/titanic/train.csv')
properties = list(df.columns.values)
properties.remove('survived')
def transform_fn(label):
vec = label_encoder.fit_transform(df[label])
categorical = tf.keras.utils.to_categorical(vec)
print(label + ": ", categorical)
df[label] = tf.keras.utils.to_categorical(vec)
for c in CATEGORICAL_COLUMNS:
transform_fn(c)
x = df[properties]
y = df['survived']
print(x['sex'])
【问题讨论】: