Exercise question Python collaborative filtering ALS model implementation: product recommendation + user population enlargement

Understanding oneself 2020-11-13 10:09:13
exercise question python collaborative filtering

The previous exercise : Exercises ︱ Recommendation and search of Douban books 、 Simple knowledge engine construction (neo4j) Several simple ways to recommend are mentioned .
But on very large-scale sparse data , Generally, some large-scale models will be adopted , for example spark-ALS It's one of them .
here , I also want to investigate the operability of this model , All with the stand-alone version of the test ; Corresponding spark.mlib There are distributed versions .

The exercise code is visible :mattzheng/pyALS

1 ALS Algorithm - Alternating Least Square - Alternating least squares

1.1 The theory is introduced

Reference resources :
The implementation of online book recommendation system includes source code ( Collaborative filtering )
How to explain spark mllib in ALS Principle of algorithm ?

It's a kind of collaborative filtering , And integrated into Spark Of Mllib In the library .
For one users-products-rating The score data set of ,ALS Will create a userproduct Of mn Where ,m by users The number of ,n by products But in this dataset , Not every user has scored every product , So the matrix is often sparse ,
user i For products j The score is often empty ALS What we do is to fill the sparse matrix with some rules , So you can get any one of these from the matrix user To any one product The score ,ALS The filled rating items are also called users i For products j That's why ,ALS The core of the algorithm is what kind of rules to fill in .

 Insert picture description here
Matrix factorization ( Such as singular value decomposition , Singular value decomposition + +) Convert both the item and the user into the same potential space , It represents the potential interaction between users and items . The principle behind matrix decomposition is that latent features represent how users rate items . A potential description of a given user and item , We can predict how much users will rate items that have not yet been evaluated .
 Insert picture description here

advantage :

  • Support training
  • You don't have to input a super large matrix matrix

Inferiority :

  • New content input is not supported , user ID It can only be the existing
  • Incremental training does not support

Input training :

# [[1, 1, 4.0], [1, 3, 4.0], [1, 6, 4.0], [1, 47, 5.0], [1, 50, 5.0]]
# ( user ID, shopping ID, score )

All application users ID/ shopping ID that will do .

About incremental training :
In the article The implementation of online book recommendation system includes source code ( Collaborative filtering ) Medium is , We borrow Spark Of ALS Training and prediction functions of the algorithm , Every time new data is received , Update it to the training dataset , And then update ALS The training model .
It feels like a total retraining ?

1.2 58 The recommended scene in the same city

relatively speaking , In some recommendation scenarios, this method still has some effect 【 Reference resources :Embedding The application of technology in real estate recommendation 】:
 Insert picture description here
In these recommendation scenarios, two kinds of similarity calculation are indispensable :

  • One is the correlation between the user and the listing
  • The other is the correlation between the two houses .

How to calculate these two kinds of correlations ? First of all, we need to represent the source with these two vectors , And then by calculating the difference between the vectors , Measure users and homes 、 Whether the house supply is similar to the house supply .

Both the user matrix and the rating matrix have “ Luxury index ” and “ Just need index ” These two dimensions . Of course, the expression of these two dimensions is after the completion of matrix decomposition , Artificially summed up . Actually , The user matrix and the item matrix can be understood as for the user and the source Embedding. You can see from the user matrix that ,User1 They have a high preference for luxury houses , So he's talking to Yaohua Road 550 I'm not very interested in . meanwhile , You can see from the item matrix that , The similarity between Tangchen Yipin and Shanghai Kangcheng should be greater than that between Tomson Yipin and Yaohua Road 550 Make the similarity .
 Insert picture description here

2 pyALS

This way, thank you Collaborative filtering (ALS) The principle and Python Realization Handwritten a version , It's easy to do small-scale tests als.py
On this basis, the author has done some testing work .
Training steps :

  • Data preprocessing
  • Variable k Legality check
  • Generate random matrix U
  • Alternate matrix U And matrices I, And print RMSE Information , Until the number of iterations reaches max_iter
  • Save the final RMSE

2.1 recommendation

The data used is 【 user ID, The movie ID, Rating data 】
 Insert picture description here
First, training :

# Load data
path = 'data/movie_ratings.csv'
X = load_movie_ratings(path) # 100836
# [[1, 1, 4.0], [1, 3, 4.0], [1, 6, 4.0], [1, 47, 5.0], [1, 50, 5.0]]
# ( user ID, shopping ID, score )
# Training models
from ALS.pyALS import ALS
model = ALS()
model.fit(X, k=20, max_iter=2)
>>> Iterations: 1, RMSE: 3.207636
>>> Iterations: 2, RMSE: 0.353680

among X The format of is an ordered list ,K Represents the dimension of representation ,max_iter Represents the number of iterations .
k / max_iter The larger the iteration time is .

Then there's prediction :

# recommendation
print("Showing the predictions of users...")
# Predictions
user_ids = range(1, 5)
predictions = model.predict(user_ids, n_items=2)
for user_id, prediction in zip(user_ids, predictions):
_prediction = [format_prediction(item_id, score)
for item_id, score in prediction]
print("User id:%d recommedation: %s" % (user_id, _prediction))

 Insert picture description here

2.2 Crowd enlargement

This module is actually experimented with the help of user Of embedding As a user vector to solve people with high similarity .
The general procedure is :

  • We will train the users first user_embedding And merchandise item_embedding both .txt preservation
  • gensim load
  • Ask the crowd to be similar

I'm lazy here , Directly with the help of gensim To solve the similarity problem .

# The user matrix + Commodity matrix , image word2vec Keep it the same way
user_matrix = np.array(model.user_matrix.data)
item_matrix = np.array(model.item_matrix.data)
print(user_matrix.shape,item_matrix.shape) # ((20, 610), (20, 9724))
user_embedding = {model.user_ids[n]:user_matrix.T[n] for n in range(len(model.user_ids))}
item_embedding = {model.item_ids[n]:item_matrix.T[n] for n in range(len(model.user_ids))}
wordvec_save2txt(user_embedding,save_path = 'w2v/user_embedding_10w_50k_10i.txt',encoding = 'utf-8-sig')
wordvec_save2txt(item_embedding,save_path = 'w2v/item_embedding_10w_50k_10i.txt',encoding = 'utf-8-sig')

Then according to this user vector, similar users are solved

embedding = gensim.models.KeyedVectors.load_word2vec_format('w2v/user_embedding_10w_50k_10i.txt',binary=False)
embedding.init_sims(replace=True) # magical , It saves memory , Can operation most_similar
# Vector similarity
item_a = 1
simi = embedding.most_similar(str(item_a), topn=50)
#[('79', 0.9031778573989868),
# ('27', 0.882379412651062)]

Of course, single person solution is not feasible in practical use , Because the seed crowd / The size of the total population is relatively large , So clustering is needed in the beginning .
About Look - Like There's still a lot to pay attention to .
 Insert picture description here

本文为[Understanding oneself]所创,转载请带上原文链接,感谢

  1. 利用Python爬虫获取招聘网站职位信息
  2. Using Python crawler to obtain job information of recruitment website
  3. Several highly rated Python libraries arrow, jsonpath, psutil and tenacity are recommended
  4. Python装饰器
  5. Python实现LDAP认证
  6. Python decorator
  7. Implementing LDAP authentication with Python
  8. Vscode configures Python development environment!
  9. In Python, how dare you say you can't log module? ️
  10. 我收藏的有关Python的电子书和资料
  11. python 中 lambda的一些tips
  12. python中字典的一些tips
  13. python 用生成器生成斐波那契数列
  14. python脚本转pyc踩了个坑。。。
  15. My collection of e-books and materials about Python
  16. Some tips of lambda in Python
  17. Some tips of dictionary in Python
  18. Using Python generator to generate Fibonacci sequence
  19. The conversion of Python script to PyC stepped on a pit...
  20. Python游戏开发,pygame模块,Python实现扫雷小游戏
  21. Python game development, pyGame module, python implementation of minesweeping games
  22. Python实用工具,email模块,Python实现邮件远程控制自己电脑
  23. Python utility, email module, python realizes mail remote control of its own computer
  24. 毫无头绪的自学Python,你可能连门槛都摸不到!【最佳学习路线】
  25. Python读取二进制文件代码方法解析
  26. Python字典的实现原理
  27. Without a clue, you may not even touch the threshold【 Best learning route]
  28. Parsing method of Python reading binary file code
  29. Implementation principle of Python dictionary
  30. You must know the function of pandas to parse JSON data - JSON_ normalize()
  31. Python实用案例,私人定制,Python自动化生成爱豆专属2021日历
  32. Python practical case, private customization, python automatic generation of Adu exclusive 2021 calendar
  33. 《Python实例》震惊了,用Python这么简单实现了聊天系统的脏话,广告检测
  34. "Python instance" was shocked and realized the dirty words and advertisement detection of the chat system in Python
  35. Convolutional neural network processing sequence for Python deep learning
  36. Python data structure and algorithm (1) -- enum type enum
  37. 超全大厂算法岗百问百答(推荐系统/机器学习/深度学习/C++/Spark/python)
  38. 【Python进阶】你真的明白NumPy中的ndarray吗?
  39. All questions and answers for algorithm posts of super large factories (recommended system / machine learning / deep learning / C + + / spark / Python)
  40. [advanced Python] do you really understand ndarray in numpy?
  41. 【Python进阶】Python进阶专栏栏主自述:不忘初心,砥砺前行
  42. [advanced Python] Python advanced column main readme: never forget the original intention and forge ahead
  43. python垃圾回收和缓存管理
  44. java调用Python程序
  45. java调用Python程序
  46. Python常用函数有哪些?Python基础入门课程
  47. Python garbage collection and cache management
  48. Java calling Python program
  49. Java calling Python program
  50. What functions are commonly used in Python? Introduction to Python Basics
  51. Python basic knowledge
  52. Anaconda5.2 安装 Python 库(MySQLdb)的方法
  53. Python实现对脑电数据情绪分析
  54. Anaconda 5.2 method of installing Python Library (mysqldb)
  55. Python implements emotion analysis of EEG data
  56. Master some advanced usage of Python in 30 seconds, which makes others envy it
  57. python爬取百度图片并对图片做一系列处理
  58. Python crawls Baidu pictures and does a series of processing on them
  59. python链接mysql数据库
  60. Python link MySQL database