class TestMF(TestCase): mf_engine = mf.MF() test_data = mf.generate_test_data(100, 50, 1000) mf_engine.fit(test_data) def test_fit(self): print("testing fit method") TestMF.mf_engine.fit(TestMF.test_data) def test_predict(self): print("testing predict method") n = 1000 pred_data = mf.generate_test_data(100, 50, n, indices_only=True) predictions = TestMF.mf_engine.predict(pred_data) self.assertTrue(len(predictions) == n) for i in predictions.tolist(): self.assertTrue(type(i) is float) self.assertFalse(math.isnan(i)) def test_cross_val(self): print("testing cross val method") val_data = mf.generate_test_data(100, 50, 1000) TestMF.mf_engine.mf_cross_validation(val_data) def test_factorq(self): print("testing factor-q") q = TestMF.mf_engine.q_factors() self.assertEqual(q.shape, (TestMF.mf_engine.model.n, TestMF.mf_engine.model.k)) def test_factorp(self): print("testing factor-p") p = TestMF.mf_engine.p_factors() self.assertEqual(p.shape, (TestMF.mf_engine.model.m, TestMF.mf_engine.model.k))
def recommend(A, test_set): rr, cc, vv = scipy.sparse.find(A) data = [] for i in range(rr.shape[0]): data.append([rr[i], cc[i], vv[i]]) data = np.array(data) row, col, record = test_set ind = [] for i in range(row.shape[0]): ind.append([row[i], col[i]]) ind = np.array(ind) engine = mf.MF() engine.fit(data, maxiter=100) res = engine.predict(ind) flag = np.ones(row.shape[0]) print(res) return res, flag
class TestMF(TestCase): mf_engine = mf.MF() test_data = mf.generate_test_data(9000, 1000, 25000) mf_engine.mf_fit(test_data) def test_fit(self): print("testing fit method") TestMF.mf_engine.mf_fit(TestMF.test_data) def test_predict(self): print("testing predict method") n = 1000 pred_data = mf.generate_test_data(9000, 1000, n, indices_only=True) predictions = TestMF.mf_engine.mf_predict(pred_data) self.assertTrue(len(predictions) == n) for i in predictions.tolist(): self.assertTrue(type(i) is float) self.assertFalse(math.isnan(i)) def test_cross_val(self): print("testing cross val method") val_data = mf.generate_test_data(9000, 1000, 10000) TestMF.mf_engine.mf_cross_validation(val_data)
ind.append([row[i], col[i]]) ind = np.array(ind) engine = mf.MF() engine.fit(data, maxiter=100) res = engine.predict(ind) flag = np.ones(row.shape[0]) print(res) return res, flag if __name__ == '__main__': A = np.random.randn(600, 10000) A[A < 0] = 0 print(A) all = [] for i in range(600): for j in range(10000): all.append([i, j, A[i][j]]) np.random.shuffle(all) data = np.array(all[:90000]) print(data) ind = [] for i in range(100): ind.append([np.random.randint(0, 600), np.random.randint(0, 10000)]) ind = np.array(ind) engine = mf.MF() engine.fit(data) res = engine.predict(ind) print(res)