import tensorflow as tf
from tensorflow import keras
from utils import *
EPOCH = 10
BATCH_SIZE = 32
VEC_DIM = 10
DROPOUT_RATE = 0.5
HEAD_NUM = 4
HIDE_SIZE = 128
LAYER_NUM = 3
DNN_LAYERS = [200, 80]
data, max_user_id, max_item_id = load_data()
# 行为特征个数
BEHAVIOR_FEAT_NUM = 32
K = tf.keras.backend
def run():
train_user_id_data, train_now_item_id_data, train_item_ids_data, train_rating_ids_data, train_y_data,\
test_user_id_data, test_now_item_id_data, test_item_ids_data, test_rating_ids_data, test_y_data = get_all_data(data)
user_id = keras.Input((1,))
now_item_id = keras.Input((1,))
items_ids = keras.Input((BEHAVIOR_FEAT_NUM,))
ratings_ids = keras.Input((BEHAVIOR_FEAT_NUM,))
usr_emb = keras.layers.Embedding(max_user_id + 1, VEC_DIM, input_length=1)(user_id) # [-1,1,vec_dim]
usr_emb = keras.layers.Flatten()(usr_emb) # [-1,vec_dim]
now_item_emb = keras.layers.Embedding(max_item_id + 1, VEC_DIM, input_length=1)(now_item_id) # [-1,1,vec_dim]
now_item_emb = keras.layers.Flatten()(now_item_emb) # [-1,vec_dim]
items_emb = keras.layers.Embedding(max_item_id + 1, VEC_DIM, input_length=BEHAVIOR_FEAT_NUM)(
items_ids) # [-1,BEA_FEAT_NUM,vec_dim]
ratings_emb = keras.layers.Embedding(6, VEC_DIM, input_length=BEHAVIOR_FEAT_NUM)(
ratings_ids) # [-1,BEA_FEAT_NUM,vec_dim]
behavior_emb = keras.layers.concatenate([items_emb, ratings_emb]) # [-1,BEA_FEAT_NUM, 2 * vec_dim]
behavior_emb = tf.reduce_sum(behavior_emb, axis=1) # [-1, 2 * vec_dim]
deep = keras.layers.concatenate([usr_emb, now_item_emb, behavior_emb])
for units in DNN_LAYERS:
deep = keras.layers.Dense(units)(deep)
deep = keras.layers.PReLU()(deep)
deep = keras.layers.Dropout(DROPOUT_RATE)(deep)
outputs = keras.layers.Dense(1, activation='sigmoid')(deep)
model = keras.Model(inputs=[user_id, now_item_id, items_ids, ratings_ids], outputs=outputs)
model.compile(loss='binary_crossentropy', optimizer=tf.train.AdamOptimizer(0.001), metrics=[keras.metrics.AUC()])
tbCallBack = keras.callbacks.TensorBoard(log_dir='./logs',
histogram_freq=0,
write_graph=True,
write_grads=True,
write_images=True,
embeddings_freq=0,
embeddings_layer_names=None,
embeddings_metadata=None)
model.fit([train_user_id_data, train_now_item_id_data, train_item_ids_data, train_rating_ids_data], train_y_data,
batch_size=BATCH_SIZE, epochs=EPOCH, verbose=2,
validation_data=(
[test_user_id_data, test_now_item_id_data, test_item_ids_data, test_rating_ids_data], test_y_data),
callbacks=[tbCallBack])
run()