具體分析稍後再介紹。
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Author : Peidong # @Site : # @File : MFRecommendSystem.py # @Software: PyCharm import numpy as np import pandas as pd # 讀取u.data文件 header = ['user_id', 'item_id', 'rating', 'timestamp'] df = pd.read_csv('ml-100k/u.data', sep='\t', names=header) # 計算唯一用戶和電影的數量 n_users = df.user_id.unique().shape[0] n_items = df.item_id.unique().shape[0] print('Number of users = ' + str(n_users) + ' | Number of movies = ' + str(n_items)) # 使用scikit-learn庫將數據集分割成測試和訓練。Cross_validation.train_test_split根據測試樣本的比例(test_size),本例中是0.25,來將數據混洗並分割成兩個數據集 from sklearn import cross_validation as cv train_data, test_data = cv.train_test_split(df, test_size=0.25) # 計算數據集的稀疏度 sparsity = round(1.0 - len(df)/float(n_users*n_items), 3) print('The sparsity level of MovieLens100K is ' + str(sparsity*100) + '%') # 創建uesr-item矩陣,此處需創建訓練和測試兩個UI矩陣 train_data_matrix = np.zeros((n_users, n_items)) for line in train_data.itertuples(): train_data_matrix[line[1] - 1, line[2] - 1] = line[3] test_data_matrix = np.zeros((n_users, n_items)) for line in test_data.itertuples(): test_data_matrix[line[1] - 1, line[2] - 1] = line[3] # 使用SVD進行矩陣分解 import scipy.sparse as sp from scipy.sparse.linalg import svds u, s, vt = svds(train_data_matrix, k=20) s_diag_matrix = np.diag(s) X_pred = np.dot(np.dot(u, s_diag_matrix), vt) # 利用均方根誤差進行評估 from sklearn.metrics import mean_squared_error from math import sqrt def rmse(prediction, ground_truth): prediction = prediction[ground_truth.nonzero()].flatten() ground_truth = ground_truth[ground_truth.nonzero()].flatten() return sqrt(mean_squared_error(prediction, ground_truth)) print('User-based CF MSE: ' + str(rmse(X_pred, test_data_matrix)))