Hacker News排名算法工作原理
這篇文章我要向大家介紹Hacker News網(wǎng)站的文章排名算法工作原理,以及如何在自己的應(yīng)用里使用這種算法。這個算法非常的簡單,但卻在突出熱門文章和遴選新文章上表現(xiàn)的異常優(yōu)秀。
深入news.arc 程序代碼
Hacker News是用Arc語言開發(fā)的,這是一種Lisp方言,由Y Combinator投資公司創(chuàng)始人Paul Graham創(chuàng)造。Hacker News的開源的,你可以在arclanguage.org找到它的源代碼。深入發(fā)掘 news.arc 程序,你會找到這段排名算法代碼,就是下面這段:
- ; Votes divided by the age in hours to the gravityth power.
 - ; Would be interesting to scale gravity in a slider.
 - (= gravity* 1.8 timebase* 120 front-threshold* 1
 - nourl-factor* .4 lightweight-factor* .3 )
 - (def frontpage-rank (s (o scorefn realscore) (o gravity gravity*))
 - (* (/ (let base (- (scorefn s) 1)
 - (if (> base 0) (expt base .8) base))
 - (expt (/ (+ (item-age s) timebase*) 60) gravity))
 - (if (no (in s!type 'story 'poll)) 1
 - (blank s!url) nourl-factor*
 - (lightweight s) (min lightweight-factor*
 - (contro-factor s))
 - (contro-factor s))))
 
本質(zhì)上,這段 Hacker News采用的排名算法的工作原理看起來大概是這個樣子:
- Score = (P-1) / (T+2)^G
 - 其中,
 - P = 文章獲得的票數(shù)( -1 是去掉文章提交人的票)
 - T = 從文章提交至今的時間(小時)
 - G = 比重,news.arc里缺省值是1.8
 
正如你看到的,這個算法很容易實現(xiàn)。在下面的內(nèi)容里,我們將會看到這個算法是如何工作的。
比重(G)和時間(T)對排名的影響
比重和時間在文章的排名得分上有重大的影響。正常情況下如下面所述:
- 當T增加時文章得分會下降,這就是說越老的文章分數(shù)會越底。
 - 當比重加大時,老的文章的得分會減的更快
 
為了能視覺呈現(xiàn)這個算法,我們可以把它繪制到Wolfram Alpha。
得分隨著時間是如何變化的

你可以看到,隨著時間的流逝,得分驟然下降,例如,24小時前的文章的分數(shù)變的非常低——不管它獲得了如何多的票數(shù)。
- plot(
 - (30 - 1) / (t + 2)^1.8,
 - (60 - 1) / (t + 2)^1.8,
 - (200 - 1) / (t + 2)^1.8
 - ) where t=0..24
 
比重參數(shù)是如何影響排名的

圖中你可以看到,比重越大,得分下降的越快。
- plot(
 - (p - 1) / (t + 2)^1.8,
 - (p - 1) / (t + 2)^0.5,
 - (p - 1) / (t + 2)^2.0
 - ) where t=0..24, p=10
 
Python語言實現(xiàn)
之前已經(jīng)說了,這個評分算法很容易實現(xiàn):
- def calculate_score(votes, item_hour_age, gravity=1.8):
 - return (votes - 1) / pow((item_hour_age+2), gravity)
 
關(guān)鍵是要理解算法中的各個因素對評分的影響,這樣你可以在你的應(yīng)用中進行定制。我希望這篇文章已經(jīng)向你說明了這些。
祝編程快樂!
編輯:
Paul Graham 分享了修正后的HN 排名算法:
- (= gravity* 1.8 timebase* 120 front-threshold* 1
 - nourl-factor* .4 lightweight-factor* .17 gag-factor* .1)
 - (def frontpage-rank (s (o scorefn realscore) (o gravity gravity*))
 - (* (/ (let base (- (scorefn s) 1)
 - (if (> base 0) (expt base .8) base))
 - (expt (/ (+ (item-age s) timebase*) 60) gravity))
 - (if (no (in s!type 'story 'poll)) .8
 - (blank s!url) nourl-factor*
 - (mem 'bury s!keys) .001
 - (* (contro-factor s)
 - (if (mem 'gag s!keys)
 - gag-factor*
 - (lightweight s)
 - lightweight-factor*
 - 1)))))
 
英文原文:How Hacker News ranking algorithm works
譯文鏈接:http://www.aqee.net/how-hacker-news-ranking-algorithm-works/















 
 
 



 
 
 
 