7.3 案例:神经网络分类
学习目标
- 目标
- 掌握tf.dataset使用
- 掌握tf.feature_column使用
- 应用
- 应用tf.estimator进行神经网络分类案例
7.3.1 美国普查数据神经网络分类
将tf.estimator原来为线性模型替换成神经网络模型, 当使用神经网络进行分类的时候,注意输入的特征列
- 连续型特征列不需要处理
- 离散型特征列需要进行embedding_column或者indicator column处理,不能直接输入DNN模型中以categorical类别
- embedding columns 不能直接作用在原始特征上,而是作用在categorical columns
- Embedding column与indicator column之间的区别可以用下图表示
- 使用indicator_column来把原始数据转换为神经网络的输入就变得非常不灵活,这时通常使用embedding column把原始特征映射为一个低维稠密的实数向量。同一类别的embedding向量间的距离通常可以用来度量类别直接的相似性。
特征列处理
def get_feature_column_v2():
"""对于普查数据,进行特征列指定
:return:
"""
# 连续型特征
age = tf.feature_column.numeric_column('age')
education_num = tf.feature_column.numeric_column('education_num')
capital_gain = tf.feature_column.numeric_column('capital_gain')
capital_loss = tf.feature_column.numeric_column('capital_loss')
hours_per_week = tf.feature_column.numeric_column('hours_per_week')
numeric_columns = [age, education_num, capital_gain, capital_loss, hours_per_week]
# 离散特征列指定
relationship = tf.feature_column.categorical_column_with_vocabulary_list(
'relationship',
['Husband', 'Not-in-family', 'Wife', 'Own-child', 'Unmarried', 'Other-relative'])
occupation = tf.feature_column.categorical_column_with_hash_bucket(
'occupation', hash_bucket_size=1000)
education = tf.feature_column.categorical_column_with_vocabulary_list(
'education', [
'Bachelors', 'HS-grad', '11th', 'Masters', '9th', 'Some-college',
'Assoc-acdm', 'Assoc-voc', '7th-8th', 'Doctorate', 'Prof-school',
'5th-6th', '10th', '1st-4th', 'Preschool', '12th'])
marital_status = tf.feature_column.categorical_column_with_vocabulary_list(
'marital_status', [
'Married-civ-spouse', 'Divorced', 'Married-spouse-absent',
'Never-married', 'Separated', 'Married-AF-spouse', 'Widowed'])
workclass = tf.feature_column.categorical_column_with_vocabulary_list