non-negative-matrix-factorization

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 3

non-negative-matrix-factorization

June 24, 2024

[1]: from surprise import Dataset, Reader, accuracy, NMF


from surprise.model_selection import cross_validate, train_test_split
import pickle
import pandas as pd

0.1 huấn luyện và đánh giá mô hình


[2]: def train_nmf_model(df):
"""Huấn luyện mô hình NMF và trả về nó."""
reader = Reader(rating_scale=(0.5, 5))
data = Dataset.load_from_df(df[['userId', 'id', 'rating']], reader)
trainset, testset = train_test_split(data, test_size=0.25)

algo = NMF()
algo.fit(trainset)
predictions = algo.test(testset)
accuracy.rmse(predictions, verbose=True)

cross_validate(algo, data, measures=['RMSE', 'MAE'], cv=5, verbose=True)


return algo

1 Lưu trữ và tải mô hình


[3]: def save_model(model, filename):
"""Lưu trữ mô hình đã huấn luyện vào tệp."""
with open(filename, 'wb') as file:
pickle.dump(model, file)
print(f"Mô hình đã được lưu trữ vào {filename}")

def load_model(filename):
"""Tải mô hình đã huấn luyện từ tệp."""
with open(filename, 'rb') as file:
model = pickle.load(file)
return model

1
1.1 Tạo gợi ý cho người dùng
[4]: def generate_recommendations(user_id, algo, df):
"""Tạo và in ra 10 gợi ý phim hàng đầu cho một người dùng."""
reader = Reader(rating_scale=(0.5, 5))
data = Dataset.load_from_df(df[['userId', 'id', 'rating']], reader)
trainset = data.build_full_trainset()
testset = trainset.build_anti_testset()
predictions = algo.test(testset)

user_predictions = [pred for pred in predictions if pred.uid == user_id]


user_predictions.sort(key=lambda x: x.est, reverse=True)
top_10_recommendations = user_predictions[:10]

print(f"10 gợi ý hàng đầu cho người dùng {user_id}:")


for pred in top_10_recommendations:
movie_title = df.loc[df['id'] == pred.iid, 'title'].values[0]
print(f"Tên phim: {movie_title}, Xếp hạng ước tính: {pred.est:.2f}")

[5]: if __name__ == "__main__":


# Giả sử df đã được chuẩn bị và chứa dữ liệu 'userId', 'movieId', 'rating'
df = pd.read_csv("/kaggle/input/hehotro-processingdata/ratings_movies.csv")

# Huấn luyện, đánh giá và lưu trữ mô hình NMF


print("Đánh giá và lưu trữ mô hình NMF:")
nmf_model = train_nmf_model(df)
save_model(nmf_model, 'nmf_model.pkl')

# Tải mô hình và tạo gợi ý


nmf_model = load_model('nmf_model.pkl')
user_id = 1
print()
print("NMF")
generate_recommendations(user_id, nmf_model, df)

Đánh giá và lưu trữ mô hình NMF:


RMSE: 0.9494
Evaluating RMSE, MAE of algorithm NMF on 5 split(s).

Fold 1 Fold 2 Fold 3 Fold 4 Fold 5 Mean Std


RMSE (testset) 0.9450 0.9491 0.9562 0.9436 0.9414 0.9470 0.0052
MAE (testset) 0.7253 0.7305 0.7373 0.7293 0.7221 0.7289 0.0051
Fit time 0.92 0.98 0.95 0.94 1.00 0.96 0.03
Test time 0.04 0.12 0.04 0.04 0.04 0.06 0.03
Mô hình đã được lưu trữ vào nmf_model.pkl

NMF
10 gợi ý hàng đầu cho người dùng 1:

2
Tên phim: Elizabeth, Xếp hạng ước tính: 4.19
Tên phim: The Story of a Cheat, Xếp hạng ước tính: 4.06
Tên phim: Malcolm X, Xếp hạng ước tính: 4.04
Tên phim: Birdman of Alcatraz, Xếp hạng ước tính: 3.98
Tên phim: Crank, Xếp hạng ước tính: 3.98
Tên phim: Frankenstein, Xếp hạng ước tính: 3.96
Tên phim: Rio Bravo, Xếp hạng ước tính: 3.93
Tên phim: House of Cards, Xếp hạng ước tính: 3.92
Tên phim: The Lord of the Rings, Xếp hạng ước tính: 3.85
Tên phim: The Ring, Xếp hạng ước tính: 3.83

You might also like