Deep:DNN模型,提高模型的泛化能力。
Wide:简单的广义线性模型,其特征组合需要人去设计,依赖人工特征工程。注重模型的记忆能力。
- movie_feature = tf.feature_column.categorical_column_with_identity(key='movieId', num_buckets=1001)
- rated_movie_feature = tf.feature_column.categorical_column_with_identity(key='userRatedMovie1', num_buckets=1001)
- crossed_feature = tf.feature_column.crossed_column([movie_feature, rated_movie_feature], 10000)
- #deep部分
- deep = tf.keras.layers.DenseFeatures(numerical_columns + categorical_columns)(inputs)
- deep = tf.keras.layers.Dense(128, activation='relu')(deep)
- deep = tf.keras.layers.Dense(128, activation='relu')(deep)
- # wide部分
- wide = tf.keras.layers.DenseFeatures(crossed_feature)(inputs)
- # 拼接wide和deep
- both = tf.keras.layers.concatenate([deep, wide])
- output_layer = tf.keras.layers.Dense(1, activation='sigmoid')(both)
- model = tf.keras.Model(inputs, output_layer)
- def neural_cf_model_1(feature_inputs, item_feature_columns, user_feature_columns, hidden_units):
- # 物品侧特征层
- item_tower = tf.keras.layers.DenseFeatures(item_feature_columns)(feature_inputs)
- # 用户侧特征层
- user_tower = tf.keras.layers.DenseFeatures(user_feature_columns)(feature_inputs)
- # 连接层
- interact_layer = tf.keras.layers.concatenate([item_tower, user_tower])
- #多层神经网络
- for num_nodes in hidden_units:
- interact_layer = tf.keras.layers.Dense(num_nodes, activation='relu')(interact_layer)
- # sigmoid单神经元输出层
- output_layer = tf.keras.layers.Dense(1, activation='sigmoid')(interact_layer)
- # keras模型
- neural_cf_model = tf.keras.Model(feature_inputs, output_layer)
- return neural_cf_model
- #hidden_units 可以定义多层神经网络的层数和神经元
- def neural_cf_model_2(feature_inputs, item_feature_columns, user_feature_columns, hidden_units):
- # 物品侧输入特征层
- item_tower = tf.keras.layers.DenseFeatures(item_feature_columns)(feature_inputs)
- # 物品塔结构
- for num_nodes in hidden_units:
- item_tower = tf.keras.layers.Dense(num_nodes, activation='relu')(item_tower)
-
- # 用户侧输入特征层
- user_tower = tf.keras.layers.DenseFeatures(user_feature_columns)(feature_inputs)
- # 用户塔结构
- for num_nodes in hidden_units:
- user_tower = tf.keras.layers.Dense(num_nodes, activation='relu')(user_tower)
- # 内积操作交互物品塔和用户塔,最后输出
- output = tf.keras.layers.Dot(axes=1)([item_tower, user_tower])
-
- # keras模型
- neural_cf_model = tf.keras.Model(feature_inputs, output)
- return neural_cf_model