forked from yixuan/recosystem
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpredict.cpp
More file actions
124 lines (98 loc) · 2.61 KB
/
Copy pathpredict.cpp
File metadata and controls
124 lines (98 loc) · 2.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
#include <iomanip>
#include <cmath>
#include <cstring>
#include "mf.h"
#include <Rcpp.h>
namespace
{
/*
struct PredictOption
{
std::string test_path, model_path, out_path;
};
void predict_help()
{
printf("usage: libmf predict binary_test_file model [output]\n");
}
std::shared_ptr<PredictOption> parse_predict_option(
const int argc, const char * const * const argv)
{
if((argc != 2) && (argc != 3))
{
// predict_help();
return std::shared_ptr<PredictOption>(nullptr);
}
std::shared_ptr<PredictOption> option(new PredictOption);
option->test_path = std::string(argv[0]);
option->model_path = std::string(argv[1]);
if(argc == 3)
{
option->out_path = std::string(argv[2]);
}
else
{
const char *p = strrchr(argv[0], '/');
if(!p)
p = argv[0];
else
++p;
option->out_path = std::string(p) + ".out";
}
return option;
}
*/
bool predict(std::string const test_path, std::string const model_path,
std::string const output_path)
{
FILE *f = fopen(output_path.c_str(), "w");
if(!f)
{
// fprintf(stderr, "\nError: Cannot open %s.", output_path.c_str());
Rcpp::stop("Cannot open %s", output_path.c_str());
return false;
}
std::shared_ptr<Model> model = read_model(model_path);
if(!model)
return false;
std::shared_ptr<Matrix> Te = read_matrix(test_path);
if(!Te)
return false;
Timer timer;
timer.tic("Predicting...");
double loss = 0;
for(long r = 0; r < Te->nr_ratings; r++)
{
float const rate = calc_rate(*model, Te->R[r]);
fprintf(f, "%f\n", rate);
float const e = Te->R[r].rate - rate;
loss += e*e;
}
timer.toc("done.");
// printf("RMSE: %.3f\n", sqrt(loss/Te->nr_ratings));
Rprintf("RMSE: %.3f\n", sqrt(loss/Te->nr_ratings));
fclose(f);
return true;
}
} //namespace
/*
int predict(int const argc, char const * const * const argv)
{
std::shared_ptr<PredictOption> option = parse_predict_option(argc, argv);
if(!option)
return EXIT_FAILURE;
if(!predict(option->test_path, option->model_path, option->out_path))
return EXIT_FAILURE;
return EXIT_SUCCESS;
}
*/
using namespace Rcpp;
extern "C" SEXP predict_wrapper(SEXP testset, SEXP model, SEXP out)
{
BEGIN_RCPP
std::string test_file = as<std::string>(testset);
std::string model_file = as<std::string>(model);
std::string out_file = as<std::string>(out);
bool res = predict(test_file, model_file, out_file);
return wrap(res);
END_RCPP
}