【发布时间】:2015-12-19 15:34:37
【问题描述】:
我正在使用此函数来获取地图中存在的键的分数。哈希图有大约 80,000 个项目。键都是字符串的向量。作为键传递给 score 函数的向量约为 22,但在调用函数的单次迭代中,该函数被调用了 64000 次。每次迭代大约需要 1282.044314 毫秒。
这非常慢,因为调用算法(用于标记的全局线性模型)需要进行数百万次迭代。如何解决这个瓶颈?
1. (defn score[map keys]
2. (loop [acc 0 keys (seq keys)]
3. (if keys
4. (recur
5. (+ (map (first keys) 0)
6. acc)
7. (next keys))
8. acc)))
9. (defn yy1
10. "Where 'model' is a hash-map of vectors
11. e.g ["BIGRAM:POS-1:WORD:POS", "DT", "Man", "NNP"],
12. 'sent' is a vector of strings e.g ["The", "man", "came"],
13. 'i' an integer,
14. 't' a string e.g "NNP",
15. 't1' also a string e.g "VBD",
16. 'null' is a string "NULL",
17. 'f's e.g 'f9' are strings like "BIGRAM:POS-2:WORD:POS""
18.
19. [model sent i t t1]
20. (let [word-1 (get sent (- i 1) null)
21. word (sent i)
22. word+1 (get sent (+ i 1) null)
23. word+2 (get sent (+ i 2) null)
24. word-2 (get sent (- i 2) null)
25. features [[f9 t1 word t]
26. [f10 t1 t]
27. [f11 word-1 t1 word]
28. [f12 word-1 t1 word t]
29. [f13 word-2 t1 word t]
30. [f14 word-2 t1 t]
31. [f15 word t]
32. [f16 word-1 word t]
33. [f17 word-1 t]
34. [f18 word-2 word]
35. [f19 t word+1]
36. [f20 word t word+1]
37. [f21 word-2 word-1 t]
38. [f22 word-2 word-1 word t]
39. [f23 word t word+1 word+2]
40. ]]
41. (score model features)
42. ))
43. (defn yy1y2[model sent i t t1 t2]
44. (let [word-1 (get sent (- i 1) null)
45. word-2 (get sent (- i 2) null)
46. word (sent i)
47. features [[ f1 t2 word t]
48. [ f2 t2 t]
49. [ f3 t2 t1 t]
50. [ f4 t2 t1 word t]
51. [ f5 t2 t1 word-1 word t]
52. [ f6 t2 word-2 t1 word-1 word t]
53. [ f7 t2 word-1 word t]
54. [ f8 t2 word-1 t]]]
55. (score model features)
56. ))
57. (defn viterbi
58. "'model' is a hash-map e.g {["UNIGRAM:WORD:POS" "John" "NNP"] 1}
59. 'tags' is a hash-map, with keys :U :V :T e.g {:U ["NNP" "NN"]}
60. 'sent' is a vector of strings e.g ["Jonh" "is" "tall"]"
61.
62. [model tags sent]
63. (let [pi (atom {[-1 * *] 1})]
64. (let [{:keys [U V T]} tags
65. N (range (count sent))
66. ]
67. (doall (for [k N u U v V]
68. (let [const (yy1 model sent k v u)
69. g #(yy1y2 model sent k v u %)
70. k-1 (- k 1)
71. [score t] (apply max-key first
72. (map
73. (fn[t] [(+ (@pi [k-1 t u] ep) const (g t)) t])
74. T))
75. ]
76. (swap! pi assoc (with-meta [k u v] {:t t}) score)))))
77. @pi))
【问题讨论】:
-
我想codereview.stackexchange.com 会更适合这个问题。
-
@RomanMakhlin 在 Stack Overflow 上提出这个问题并没有错。毕竟这是一个特定的编程问题。
-
好吧,这不是索赔,只是建议。我们有很多 *exchange,有时会有点混乱。
-
@user3234550 将同一个问题交叉发布到多个站点是不受欢迎的。将它放在一个站点上就足够了。
-
当你拨打
score64000次时:64000从哪里来?你使用相同的map和不同的keys?
标签: performance clojure hashmap