本人代码库: 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. Spider_实践_beautifulsoup静态网页爬取所有网页链接

    # 获取百度网站首页上的所有a标签里的 href属性值: # import requests # from bs4 import BeautifulSoup # # html = requests.g ...

  2. 利用 Github Actions 的 service container 进行集成测试

    Github Action 中 Service Container 的使用 Intro 之前写过一个 StackExchange.Redis 的一个扩展,测试项目依赖 redis,所以之前测试一直只是 ...

  3. fashion数据集训练

    下载数据集 fashion数据集总共有7万张28*28像素点的灰度图片和标签,涵盖十个分类:T恤.裤子.套头衫.连衣裙.外套.凉鞋.衬衫.运动鞋.包.靴子. 其中6万张用于训练,1万张用于测试. im ...

  4. 浅析TCP协议---转载

    https://cloud.tencent.com/developer/article/1150971 前言 说到TCP协议,相信大家都比较熟悉了,对于TCP协议总能说个一二三来,但是TCP协议又是一 ...

  5. linux 图解笔记

  6. hmac检验客户端合法性

    1.服务端 # 验证客户端是否合法 # 不依靠登陆认证 # 当有一个客户端访问你的时候,建立了tcp后,server端主动发起一个数据,数据为想加密的bytes类型的数据. # 客户端拿到要加密的by ...

  7. python编码规范以及推导式的编写

    一.python 的编码规范

  8. linux执行cmd之一

    执行方法: 1.手动执行 2.程序执行 涉及到的权限问题: 1.应用程序的权限 2.被执行文件的权限

  9. Mate 40系列发布 搭载华为运动健康服务带来健康数字生活

    10月30日,HUAWEI Mate 40系列国内发布会如期而至.Mate 40系列除了拥有强悍的性能.全能记录影像和突破性的交互之外,还搭载了全新升级的HMS Core,其中,Health Kit( ...

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

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