DeepFM——tensorflow代码改编
本人代码库: 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代码改编的更多相关文章
- tensorflow 代码阅读
具体实现: https://github.com/tensorflow/tensorflow/tree/master/tensorflow/core/framework 『深度长文』Tensorflo ...
- 关于使用实验室服务器的GPU以及跑上TensorFlow代码
连接服务器 Windows - XShell XFtp SSH 通过SSH来连接实验室的服务器 使用SSH连接已经不陌生了 github和OS课设都经常使用 目前使用 192.168.7.169 使用 ...
- 条件随机场(crf)及tensorflow代码实例
对于条件随机场的学习,我觉得应该结合HMM模型一起进行对比学习.首先浏览HMM模型:https://www.cnblogs.com/pinking/p/8531405.html 一.定义 条件随机场( ...
- 如何高效的学习 TensorFlow 代码? 以及TensorFlow相关的论文
https://www.zhihu.com/question/41667903 源码分析 http://www.cnblogs.com/yao62995/p/5773578.html 如何贡献Tens ...
- Transformer解析与tensorflow代码解读
本文是针对谷歌Transformer模型的解读,根据我自己的理解顺序记录的. 另外,针对Kyubyong实现的tensorflow代码进行解读,代码地址https://github.com/Kyuby ...
- 深度学习之卷积神经网络CNN及tensorflow代码实例
深度学习之卷积神经网络CNN及tensorflow代码实例 什么是卷积? 卷积的定义 从数学上讲,卷积就是一种运算,是我们学习高等数学之后,新接触的一种运算,因为涉及到积分.级数,所以看起来觉得很复杂 ...
- 深度学习之卷积神经网络CNN及tensorflow代码实现示例
深度学习之卷积神经网络CNN及tensorflow代码实现示例 2017年05月01日 13:28:21 cxmscb 阅读数 151413更多 分类专栏: 机器学习 深度学习 机器学习 版权声明 ...
- 运行TensorFlow代码时报错
运行TensorFlow代码时报错 错误信息ImportError: libcublas.so.10.0: cannot open shared object file 原因:TensorFlow版本 ...
- 利用VGG19实现火灾分类(附tensorflow代码及训练集)
源码地址 https://github.com/stephen-v/tensorflow_vgg_classify 1. VGG介绍 1.1. VGG模型结构 1.2. VGG19架构 2. 用Ten ...
随机推荐
- 基于selenium微博个人主页视频下载
# -*- coding: utf-8 -*- import selenium from selenium import webdriver import time import urllib.req ...
- http代理阅读2
向上游服务器发送请求处理 static void ngx_http_upstream_send_request(ngx_http_request_t *r, ngx_http_upstream_t * ...
- linux 异步I/O 信号
if (ioctl(ngx_processes[s].channel[0], FIOASYNC, &on) == -1) { ngx_log_error(NGX_LOG_ALERT, cycl ...
- UNP第13章——守护进程
1. 守护进程的启动方法 (1)系统初始化脚本启动,在系统启动阶段,按照如/etc目录或/etc/rc开头的目录中的某些脚本启动,这些守护进程一开始就有超级用户权限.如inetd,cron,Web服务 ...
- 七:Redis的持久化
1.RDB(Redis DataBase) 1.1 定义:在指定的时间间隔内将内存中的数据集快照写入磁盘,也就是行话讲的snapshot快照,他恢复时是将快照文件直接读到内存里 是什么:Redis会单 ...
- 限流10万QPS、跨域、过滤器、令牌桶算法-网关Gateway内容都在这儿
一.微服务网关Spring Cloud Gateway 1.1 导引 文中内容包含:微服务网关限流10万QPS.跨域.过滤器.令牌桶算法. 在构建微服务系统中,必不可少的技术就是网关了,从早期的Zuu ...
- DP中环形处理 +(POJ 1179 题解)
DP中环形处理 对于DP中存在环的情况,大致有两种处理的方法: 对于很多的区间DP来说,很常见的方法就是把原来的环从任意两点断开(注意并不是直接删掉这条边),在复制一条一模一样的链在这条链的后方,当做 ...
- java中对于浮点型数据操作
java的基本数据类型-浮点型:单精度(float)和双精度(double). float:单精度浮点数在机内占4个字节.有效数字8位.表示范围:-3.40E+38 ~ +3.40E+38; doub ...
- NPOI读写Excel组件封装Excel导入导出组件
后台管理系统多数情况会与Excel打交道,常见的就是Excel的导入导出,对于Excel的操作往往是繁琐且容易出错的,对于后台系统的导入导出交互过程往往是固定的,对于这部分操作,我们可以抽离出公共组件 ...
- Markdown的应知应会
Markdown介绍 什么是Markdown Markdown是一种纯文本.轻量级的标记语言,常用作文本编辑器使用.和记事本.notepad++相比,Markdown可以进行排版:和Word相比,Ma ...