本人代码库: https://github.com/beathahahaha/tensorflow-DeepFM-master-original

DeepFM原作者代码库: https://github.com/ChenglongChen/tensorflow-DeepFM

解析DeepFM代码 博客推荐:https://mp.weixin.qq.com/s/QrO48ZdP483TY_EnnWFhsQ

为了熟悉该代码的使用,我在example文件夹编写了一个test_1.py文件,可以直接运行

一、定义DeepFM 输入:

  需要train.csv(59列,有连续性数值,也有离散型数值,其中多分类都用的0,1,2,3表示),test.csv是kaggle比赛时需要输出的东西,非必要

  (参考该数据格式:https://www.kaggle.com/c/porto-seguro-safe-driver-prediction/data?select=train.csv)

二、定义DeepFM 输出:

  yy = dfm.predict(Xi_valid_, Xv_valid_) 得到一维np.array,其中数值为float代表概率值

tensorflow 建议1.14 gpu版本

如果自己要DIY的话,要注意哪些地方呢?

答:

1. config.py 里面的设置,和输入数据密切相关,要定义好离散型和连续型的列

2. 喂入的数据格式必须严格统一,注意修改test_1.py 中的列标签名字相关的内容(因此建议使用test_1.py 而不是原作者的main.py)

test_1.py:

import tensorflow as tf
from sklearn.metrics import roc_auc_score
import os
import sys import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
from sklearn.metrics import make_scorer
from sklearn.model_selection import StratifiedKFold
from sklearn.metrics import accuracy_score import config
from metrics import gini_norm
from DataReader import FeatureDictionary, DataParser sys.path.append("..")
from DeepFM import DeepFM def _load_data():
dfTrain = pd.read_csv(config.TRAIN_FILE)
dfTest = pd.read_csv(config.TEST_FILE) cols = [c for c in dfTrain.columns if c not in ["id", "target"]]
cols = [c for c in cols if (not c in config.IGNORE_COLS)] X_train = dfTrain[cols].values
y_train = dfTrain["target"].values
X_test = dfTest[cols].values
ids_test = dfTest["id"].values
cat_features_indices = [i for i, c in enumerate(cols) if c in config.CATEGORICAL_COLS] return dfTrain, dfTest, X_train, y_train, X_test, ids_test, cat_features_indices def _run_base_model_dfm(dfTrain, dfTest, folds, dfm_params):
fd = FeatureDictionary(dfTrain=dfTrain, dfTest=dfTest,
numeric_cols=config.NUMERIC_COLS,
ignore_cols=config.IGNORE_COLS)
data_parser = DataParser(feat_dict=fd)
Xi_train, Xv_train, y_train = data_parser.parse(df=dfTrain, has_label=True)
Xi_test, Xv_test, ids_test = data_parser.parse(df=dfTest) dfm_params["feature_size"] = fd.feat_dim
dfm_params["field_size"] = len(Xi_train[0]) y_train_meta = np.zeros((dfTrain.shape[0], 1), dtype=float)
y_test_meta = np.zeros((dfTest.shape[0], 1), dtype=float)
_get = lambda x, l: [x[i] for i in l]
gini_results_cv = np.zeros(len(folds), dtype=float)
gini_results_epoch_train = np.zeros((len(folds), dfm_params["epoch"]), dtype=float)
gini_results_epoch_valid = np.zeros((len(folds), dfm_params["epoch"]), dtype=float)
for i, (train_idx, valid_idx) in enumerate(folds):
# k折交叉,每一折中的fit中,含有epoch轮训练,每一次epoch拆分了batch来喂入
Xi_train_, Xv_train_, y_train_ = _get(Xi_train, train_idx), _get(Xv_train, train_idx), _get(y_train, train_idx)
Xi_valid_, Xv_valid_, y_valid_ = _get(Xi_train, valid_idx), _get(Xv_train, valid_idx), _get(y_train, valid_idx) dfm = DeepFM(**dfm_params)
dfm.fit(Xi_train_, Xv_train_, y_train_, Xi_valid_, Xv_valid_, y_valid_) # fit中包含对train和valid的评估 yy = dfm.predict(Xi_valid_, Xv_valid_)
# print("type(yy):",type(yy))
# print("type(y_valid_):", type(y_valid_)) # print("yy.shape:",yy.shape) #yy : array
# print("y_valid_.shape:", y_valid_.shape) #y_valid_ : list #print("yy:", yy) # 原始的predict出来的是概率值
for index in range(len(yy)):
if (yy[index] <= 0.5):
yy[index] = 0
else:
yy[index] = 1 #print("y_valid_:", y_valid_) print("accuracy_score(y_valid_, yy):", accuracy_score(y_valid_, yy)) y_train_meta[valid_idx, 0] = yy y_test_meta[:, 0] += dfm.predict(Xi_test, Xv_test) y_test_meta /= float(len(folds)) return y_train_meta, y_test_meta # params
dfm_params = {
"use_fm": True,
"use_deep": True,
"embedding_size": 8,
"dropout_fm": [1.0, 1.0],
"deep_layers": [32, 32],
"dropout_deep": [0.5, 0.5, 0.5],
"deep_layers_activation": tf.nn.relu,
"epoch": 10,
"batch_size": 1024,
"learning_rate": 0.001,
"optimizer_type": "adam",
"batch_norm": 1,
"batch_norm_decay": 0.995,
"l2_reg": 0.01,
"verbose": True,
"eval_metric": roc_auc_score,
"random_seed": 2017
} dfTrain, dfTest, X_train, y_train, X_test, ids_test, cat_features_indices = _load_data() folds = list(StratifiedKFold(n_splits=config.NUM_SPLITS, shuffle=True,
random_state=config.RANDOM_SEED).split(X_train, y_train)) y_train_dfm, y_test_dfm = _run_base_model_dfm(dfTrain, dfTest, folds, dfm_params) print("over") # Xi_train, Xv_train, y_train = prepare(...)
# Xi_valid, Xv_valid, y_valid = prepare(...)

DeepFM——tensorflow代码改编的更多相关文章

  1. tensorflow 代码阅读

    具体实现: https://github.com/tensorflow/tensorflow/tree/master/tensorflow/core/framework 『深度长文』Tensorflo ...

  2. 关于使用实验室服务器的GPU以及跑上TensorFlow代码

    连接服务器 Windows - XShell XFtp SSH 通过SSH来连接实验室的服务器 使用SSH连接已经不陌生了 github和OS课设都经常使用 目前使用 192.168.7.169 使用 ...

  3. 条件随机场(crf)及tensorflow代码实例

    对于条件随机场的学习,我觉得应该结合HMM模型一起进行对比学习.首先浏览HMM模型:https://www.cnblogs.com/pinking/p/8531405.html 一.定义 条件随机场( ...

  4. 如何高效的学习 TensorFlow 代码? 以及TensorFlow相关的论文

    https://www.zhihu.com/question/41667903 源码分析 http://www.cnblogs.com/yao62995/p/5773578.html 如何贡献Tens ...

  5. Transformer解析与tensorflow代码解读

    本文是针对谷歌Transformer模型的解读,根据我自己的理解顺序记录的. 另外,针对Kyubyong实现的tensorflow代码进行解读,代码地址https://github.com/Kyuby ...

  6. 深度学习之卷积神经网络CNN及tensorflow代码实例

    深度学习之卷积神经网络CNN及tensorflow代码实例 什么是卷积? 卷积的定义 从数学上讲,卷积就是一种运算,是我们学习高等数学之后,新接触的一种运算,因为涉及到积分.级数,所以看起来觉得很复杂 ...

  7. 深度学习之卷积神经网络CNN及tensorflow代码实现示例

    深度学习之卷积神经网络CNN及tensorflow代码实现示例 2017年05月01日 13:28:21 cxmscb 阅读数 151413更多 分类专栏: 机器学习 深度学习 机器学习   版权声明 ...

  8. 运行TensorFlow代码时报错

    运行TensorFlow代码时报错 错误信息ImportError: libcublas.so.10.0: cannot open shared object file 原因:TensorFlow版本 ...

  9. 利用VGG19实现火灾分类(附tensorflow代码及训练集)

    源码地址 https://github.com/stephen-v/tensorflow_vgg_classify 1. VGG介绍 1.1. VGG模型结构 1.2. VGG19架构 2. 用Ten ...

随机推荐

  1. JWT基本概念

    json web token 简称 JWT,它并不是一个具体的技术实现,而更像是一种标准. JWT规定了数据传输的结构,一串完整的JWT由三段落组成,每个段落用英文句号连接(.)连接,他们分别是:He ...

  2. 【转】linux自测题

    一.填空题: 1. 在Linux系统中,以 文件 方式访问设备. 2. Linux内核引导时,从文件 /etc/fstab 中读取要加载的文件系统. 3. Linux文件系统中每个文件用 i节点 来标 ...

  3. 4. Spark在集群上运行

    *以下内容由<Spark快速大数据分析>整理所得. 读书笔记的第四部分是讲的是Spark在集群上运行的知识点. 一.Spark应用组件介绍 二.Spark在集群运行过程 三.Spark配置 ...

  4. 关于“Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.”

    Consider the following: If you want an embedded database (H2, HSQL or Derby), please put it on the c ...

  5. mysql之事物

    1.事物,在事物中的sql语句,要么全部执行成功,要么全部执行失败,不会出现一条sql执行成功了,一条sql执行失败的问题. 2.开启事物:就是关闭mysql自己的自动提交事物的方式 3.commit ...

  6. IAR设置字体

    1.IAR设置字体 第一种方法可以在IDE环境下,选择Tools -> option -> Editor - > Colors and Fonts,然后右边的Editor Font就 ...

  7. 网页中Office和pdf相关文件导出

    最近被派去维护和开发一些做了一半.年久失修的项目.有一部分内容是关于word文件导出,顺带着把excel.pdf文件的导出也调研下吧,我想未来开发我应该会遇到的,遂做了下笔记分享给需要的人. 由于项目 ...

  8. 写的太细了!Spring MVC拦截器的应用,建议收藏再看!

    Spring MVC拦截器 拦截器是Spring MVC中强大的控件,它可以在进入处理器之前做一些操作,或者在处理器完成后进行操作,甚至是在渲染视图后进行操作. 拦截器概述 对于任何优秀的MVC框架, ...

  9. FL Studio 插件使用技巧——Fruity Reeverb 2(下)

    了解大教堂声场的特点 上节教程中我们说到,混响具有营造空间感的作用.当我们想要在FL Studio软件中用Fruity Reeverb 2 插件有目标地模仿一个特定空间的环境时,我们需要充分了解该空间 ...

  10. css3系列之@font-face

    @font-face 这个属性呢,必须设置在 css的根下,也就是说,不能设置在任何元素里面. @font-face: 参数: font-family:  给这个文字库 起个名字. src: url( ...