鱼C论坛

 找回密码
 立即注册
查看: 2534|回复: 4

[技术交流] Python实现FM【tensorflow2.0】

[复制链接]
发表于 2020-12-25 20:07:42 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
本帖最后由 糖逗 于 2021-1-7 11:56 编辑

  1. import tensorflow as tf
  2. import numpy as np
  3. from sklearn.preprocessing import LabelEncoder
  4. from sklearn.model_selection import train_test_split

  5. #将数据划分为测试集和训练集
  6. def preprocess(x, y):
  7.     x = tf.cast(x, dtype = tf.float64)
  8.     #x = x / tf.reduce_max(x)
  9.     y = tf.cast(y, dtype = tf.int64)
  10.     return x, y

  11. from sklearn.datasets import load_breast_cancer
  12. from sklearn.model_selection import train_test_split
  13. data = load_breast_cancer()
  14. x_train, x_test, y_train, y_test = train_test_split(data.data, data.target, test_size=0.2,
  15.                                                         random_state = 11, stratify = data.target)
  16. print(x_train.shape, y_train.shape, x_test.shape, y_test.shape)

  17. train_db = tf.data.Dataset.from_tensor_slices((np.array(x_train), y_train))
  18. train_db = train_db.shuffle(123).map(preprocess).batch(20)

  19. test_db = tf.data.Dataset.from_tensor_slices((np.array(x_test), y_test))
  20. test_db = test_db.map(preprocess).batch(20)

  21. sample = next(iter(train_db))
  22. print('sample:', sample[0].shape, sample[1].shape,
  23.       tf.reduce_min(sample[0]), tf.reduce_max(sample[0]))
复制代码


  1. from tensorflow.keras import layers, optimizers
  2. from tensorflow import keras

  3. class FM(keras.Model):
  4.     def __init__(self, k = 4):
  5.         super(FM, self).__init__()
  6.         self.k = k
  7.         
  8.     def build(self,input_shape):
  9.         self.fc = tf.keras.layers.Dense(units = 1,
  10.                                   bias_regularizer = tf.keras.regularizers.l2(0.01),
  11.                                   kernel_regularizer = tf.keras.regularizers.l1(0.02))

  12.         self.v = self.add_weight(shape = (input_shape[-1], self.k),
  13.                                       initializer = 'glorot_uniform',
  14.                                       trainable = True)
  15.         super(FM, self).build(input_shape)
  16.         
  17.     def call(self, x, training=True):
  18.         #[1, dim]@[dim, k] = [1, k]
  19.         a = tf.pow(tf.matmul(x, self.v), 2)
  20.         #[1, dim] @[dim, k] = [1, k]
  21.         b = tf.matmul(tf.pow(x, 2), tf.pow(self.v, 2))
  22.         #[1, dim] @[dim, 1] + reduce_mean([1, k] - [1, k])
  23.         linear = self.fc(x)
  24.         add = tf.keras.layers.Add()([linear, tf.reduce_sum(a - b, axis = 1, keepdims = True)*0.5])
  25.         return tf.sigmoid(add)
  26.    

  27. model = FM()
  28. model.build((None, 30))
  29. model.summary()
复制代码


  1. def main():
  2.     model = FM()
  3.     model.compile(optimizer = keras.optimizers.Adam(1e-3),
  4.                   loss = tf.keras.losses.binary_crossentropy,
  5.                   metrics = [tf.keras.metrics.binary_accuracy])
  6.     model.fit(train_db, epochs = 200, validation_data = test_db)

  7.     model.evaluate(test_db)

  8. if __name__ == '__main__':
  9.     main()
复制代码



注意事项:
1.“super(FM, self).build(input_shape)”必须写,且要写在def的最后一行。

本帖被以下淘专辑推荐:

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2020-12-25 20:10:46 | 显示全部楼层
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2020-12-26 13:31:38 | 显示全部楼层
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2021-1-7 11:57:02 | 显示全部楼层
论文:http://citeseerx.ist.psu.edu/vie ... p=rep1&type=pdf

代码由网络资源整合学习后写成,感谢网络中乐于进行学习分享的大家
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 1 反对 0

使用道具 举报

发表于 2021-4-19 14:22:36 | 显示全部楼层
糖逗 发表于 2021-1-7 11:57
论文:http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.393.8529&rep=rep1&type=pdf

代码由 ...

感谢感谢
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-4-27 16:51

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表