1、在上一篇博客中我们构建度为二的因子分解机模型,这篇博客对这个模型进行实践

下图为准备的数据集:

完整代码为:

 # -*- coding: UTF-8 -*-
# date:2018/6/6
# User:WangHong
import numpy as np
from random import normalvariate # 正态分布 def loadDataSet(data):
'''导入训练数据
input: data(string)训练数据
output: dataMat(list)特征
labelMat(list)标签
'''
dataMat = []
labelMat = []
fr = open(data) # 打开文件
for line in fr.readlines():
lines = line.strip().split("\t")
lineArr = [] for i in range(len(lines) - 1):
lineArr.append(float(lines[i]))
dataMat.append(lineArr) labelMat.append(float(lines[-1]) * 2 - 1) # 转换成{-1,1}
fr.close()
return dataMat, labelMat def sigmoid(inx):
return 1.0 / (1 + np.exp(-inx)) def initialize_v(n, k):
'''初始化交叉项
input: n(int)特征的个数
k(int)FM模型的超参数
output: v(mat):交叉项的系数权重
'''
v = np.mat(np.zeros((n, k))) for i in range(n):
for j in range(k):
# 利用正态分布生成每一个权重
v[i, j] = normalvariate(0, 0.2)
return v def stocGradAscent(dataMatrix, classLabels, k, max_iter, alpha):
'''利用随机梯度下降法训练FM模型
input: dataMatrix(mat)特征
classLabels(mat)标签
k(int)v的维数
max_iter(int)最大迭代次数
alpha(float)学习率
output: w0(float),w(mat),v(mat):权重
'''
m, n = np.shape(dataMatrix)
# 1、初始化参数
w = np.zeros((n, 1)) # 其中n是特征的个数
w0 = 0 # 偏置项
v = initialize_v(n, k) # 初始化V # 2、训练
for it in range(max_iter):
for x in range(m): # 随机优化,对每一个样本而言的
inter_1 = dataMatrix[x] * v
inter_2 = np.multiply(dataMatrix[x], dataMatrix[x]) * \
np.multiply(v, v) # multiply对应元素相乘
# 完成交叉项
interaction = np.sum(np.multiply(inter_1, inter_1) - inter_2) / 2.
p = w0 + dataMatrix[x] * w + interaction # 计算预测的输出
loss = sigmoid(classLabels[x] * p[0, 0]) - 1 w0 = w0 - alpha * loss * classLabels[x]
for i in range(n):
if dataMatrix[x, i] != 0:
w[i, 0] = w[i, 0] - alpha * loss * classLabels[x] * dataMatrix[x, i] for j in range(k):
v[i, j] = v[i, j] - alpha * loss * classLabels[x] * \
(dataMatrix[x, i] * inter_1[0, j] -\
v[i, j] * dataMatrix[x, i] * dataMatrix[x, i]) # 计算损失函数的值
if it % 1000 == 0:
print ("\t------- iter: ", it, " , cost: ", \
getCost(getPrediction(np.mat(dataMatrix), w0, w, v), classLabels)) # 3、返回最终的FM模型的参数
return w0, w, v def getCost(predict, classLabels):
'''计算预测准确性
input: predict(list)预测值
classLabels(list)标签
output: error(float)计算损失函数的值
'''
m = len(predict)
error = 0.0
for i in range(m):
error -= np.log(sigmoid(predict[i] * classLabels[i] ))
return error def getPrediction(dataMatrix, w0, w, v):
'''得到预测值
input: dataMatrix(mat)特征
w(int)常数项权重
w0(int)一次项权重
v(float)交叉项权重
output: result(list)预测的结果
'''
m = np.shape(dataMatrix)[0]
result = []
for x in range(m): inter_1 = dataMatrix[x] * v
inter_2 = np.multiply(dataMatrix[x], dataMatrix[x]) * \
np.multiply(v, v) # multiply对应元素相乘
# 完成交叉项
interaction = np.sum(np.multiply(inter_1, inter_1) - inter_2) / 2.
p = w0 + dataMatrix[x] * w + interaction # 计算预测的输出
pre = sigmoid(p[0, 0])
result.append(pre)
return result def getAccuracy(predict, classLabels):
'''计算预测准确性
input: predict(list)预测值
classLabels(list)标签
output: float(error) / allItem(float)错误率
'''
m = len(predict)
allItem = 0
error = 0
for i in range(m):
allItem += 1
if float(predict[i]) < 0.5 and classLabels[i] == 1.0:
error += 1
elif float(predict[i]) >= 0.5 and classLabels[i] == -1.0:
error += 1
else:
continue
return float(error) / allItem def save_model(file_name, w0, w, v):
'''保存训练好的FM模型
input: file_name(string):保存的文件名
w0(float):偏置项
w(mat):一次项的权重
v(mat):交叉项的权重
'''
f = open(file_name, "w")
# 1、保存w0
f.write(str(w0) + "\n")
# 2、保存一次项的权重
w_array = []
m = np.shape(w)[0]
for i in range(m):
w_array.append(str(w[i, 0]))
f.write("\t".join(w_array) + "\n")
# 3、保存交叉项的权重
m1 , n1 = np.shape(v)
for i in range(m1):
v_tmp = []
for j in range(n1):
v_tmp.append(str(v[i, j]))
f.write("\t".join(v_tmp) + "\n")
f.close() if __name__ == "__main__":
# 1、导入训练数据
print ("---------- 1.load data ---------")
dataTrain, labelTrain = loadDataSet("data_1.txt")
print( "---------- 2.learning ---------")
# 2、利用随机梯度训练FM模型
w0, w, v = stocGradAscent(np.mat(dataTrain), labelTrain, 3, 10000, 0.01)
predict_result = getPrediction(np.mat(dataTrain), w0, w, v) # 得到训练的准确性
print( "----------training accuracy: %f" % (1 - getAccuracy(predict_result, labelTrain)))
print ("---------- 3.save result ---------")
# 3、保存训练好的FM模型
save_model("weights", w0, w, v)

最终训练过程为:

训练的过程比较慢,我用来将近有一分半

得到的权值文件为:

最终分隔得到的超平面为:

2、对新的数据进行预测:

预测的全部代码为:

 # -*- coding: UTF-8 -*-
# date:2018/6/6
# User:WangHong import numpy as np from FM_train import getPrediction def loadDataSet(data):
'''导入测试数据集
input: data(string)测试数据
output: dataMat(list)特征
'''
dataMat = []
fr = open(data) # 打开文件
for line in fr.readlines():
lines = line.strip().split("\t")
lineArr = [] for i in range(len(lines)):
lineArr.append(float(lines[i]))
dataMat.append(lineArr) fr.close()
return dataMat def loadModel(model_file):
'''导入FM模型
input: model_file(string)FM模型
output: w0, np.mat(w).T, np.mat(v)FM模型的参数
'''
f = open(model_file)
line_index = 0
w0 = 0.0
w = []
v = []
for line in f.readlines():
lines = line.strip().split("\t")
if line_index == 0: # w0
w0 = float(lines[0].strip())
elif line_index == 1: # w
for x in lines:
w.append(float(x.strip()))
else:
v_tmp = []
for x in lines:
v_tmp.append(float(x.strip()))
v.append(v_tmp)
line_index += 1
f.close()
return w0, np.mat(w).T, np.mat(v) def save_result(file_name, result):
'''保存最终的预测结果
input: file_name(string)需要保存的文件名
result(mat):对测试数据的预测结果
'''
f = open(file_name, "w")
f.write("\n".join(str(x) for x in result))
f.close() if __name__ == "__main__":
# 1、导入测试数据
dataTest = loadDataSet("test_data.txt")
# 2、导入FM模型
w0, w , v = loadModel("weights")
# 3、预测
result = getPrediction(dataTest, w0, w, v)
# 4、保存最终的预测结果
save_result("predict_result", result)

最终测试结果得到一个predict_result.txt文件

3.2、Factorization Machine实践的更多相关文章

  1. Factorization Machine因子分解机

    隐因子分解机Factorization Machine[http://www. w2bc. com/article/113916] https://my.oschina.net/keyven/blog ...

  2. Factorization Machine

    Factorization Machine Model 如果仅考虑两个样本间的交互, 则factorization machine的公式为: $\hat{y}(\mathbf{x}):=w_0 + \ ...

  3. 3.1、Factorization Machine模型

    Factorization Machine模型 在Logistics Regression算法的模型中使用的是特征的线性组合,最终得到的分隔超平面属于线性模型,其只能处理线性可分的二分类问题,现实生活 ...

  4. Factorization Machine算法

    参考: http://stackbox.cn/2018-12-factorization-machine/ https://baijiahao.baidu.com/s?id=1641085157432 ...

  5. AI Factorization Machine(FM)算法

    FM算法 参考链接: https://www.csie.ntu.edu.tw/~b97053/paper/Rendle2010FM.pdf

  6. CTR预估算法之FM, FFM, DeepFM及实践

    https://blog.csdn.net/john_xyz/article/details/78933253 目录目录CTR预估综述Factorization Machines(FM)算法原理代码实 ...

  7. 深入理解FFM原理与实践

    原文:http://tech.meituan.com/deep-understanding-of-ffm-principles-and-practices.html 深入理解FFM原理与实践 del2 ...

  8. zz深度学习在美团配送 ETA 预估中的探索与实践

    深度学习在美团配送 ETA 预估中的探索与实践 比前一版本有改进:   基泽 周越 显杰 阅读数:32952019 年 4 月 20 日   1. 背景 ETA(Estimated Time of A ...

  9. 个性化排序算法实践(二)——FFM算法

    场感知分解机(Field-aware Factorization Machine ,简称FFM)在FM的基础上进一步改进,在模型中引入类别的概念,即field.将同一个field的特征单独进行one- ...

随机推荐

  1. php static 变量声明

    <?phpfunction test($key){ static $array = array();  /* 静态变量是只存在于函数作用域中的变量,注释:执行后这种变量不会丢失(下次调用这个函数 ...

  2. 数字图像处理实验(总计23个)汇总 标签: 图像处理MATLAB 2017-05-31 10:30 175人阅读 评论(0)

    以下这些实验中的代码全部是我自己编写调试通过的,到此,最后进行一下汇总. 数字图像处理实验(1):PROJECT 02-01, Image Printing Program Based on Half ...

  3. [SoapUI] 通过Groovy调用批处理文件.bat

    import com.eviware.soapui.support.GroovyUtils def groovyUtils = new GroovyUtils( context ) def proje ...

  4. 使用shell命令操作数据库

    使用mysql的-e参数可以执行各种sql的(创建,删除,增,删,改.查)等各种操作 用法 mysql  -uxxx    –pxxx   -e  "mysql 命令" 当然还可以 ...

  5. html 图片拖动不出来的脚本

    function imgdragstart() { return false; } $(function(){ for (i in document.images) document.images[i ...

  6. JDBC 连接 MySQL 时碰到的小坑

    最近从MS SQL Server换到了MySQL,已经是8.11版本了,安装的时候似乎还用了新的身份认证方式之类的,连接过程中也是磕磕绊绊,碰到很多奇奇怪怪的问题,在此记录下来. 驱动加载: 以前使用 ...

  7. Oracle——分页查询

    查询员工表中,工资排名在10-20之间的员工信息. select * from( select rownum rn ,employee_id,salary from ( select employee ...

  8. VS中ashx文件关键字没有高亮标记的解决办法

    VS --- 工具 --- 选项 --- 文本编辑器 --- 文件扩展名,只要在右侧添加 ashx ,选中MS-VS c# 保存后

  9. FileInputStream和FileOutStream的使用——文件字节输入/输出流

    最近又退回到java EE的学习,这篇博客就来讲解一下字节流中最重要的两个类FileInputStream和FileOutputStream的用法: FileInputStream:全称是文件字节输入 ...

  10. php中this、self、parent解析

    概述: this:指向类当前对象的指针:self:指向类本身,一般指向类中的静态变量:parent:指向父类的指针,一般使用parent来调用父类的构造函数. 下面通过程序详细介绍: 1.this & ...