我正在处理“Programming collective intelligence ”。在第 4 章中,Toby Segaran 构建了一个人工神经网络。以下函数出现在书的页面上:
def generatehiddennode(self,wordids,urls):
if len(wordids)>3: return None
# Check if we already created a node for this set of words
sorted_words=[str(id) for id in wordids]
sorted_words.sort()
createkey='_'.join(sorted_words)
res=self.con.execute(
"select rowid from hiddennode where create_key='%s'" % createkey).fetchone()
# If not, create it
if res==None:
cur=self.con.execute(
"insert into hiddennode (create_key) values ('%s')" % createkey)
hiddenid=cur.lastrowid
# Put in some default weights
for wordid in wordids:
self.setstrength(wordid,hiddenid,0,1.0/len(wordids))
for urlid in urls:
self.setstrength(hiddenid,urlid,1,0.1)
self.con.commit()
我无法理解的是这个函数中第一行的原因:'if len(wordids>3): return None`。是不是以后需要删除的调试代码?
附言这不是作业
最佳答案
对于出版的书来说,这是非常糟糕的代码! (您可以下载 from here 一书的所有示例;相关文件是 chapter4/nn.py
。)
wordids
和 urls
扮演什么角色? wordids
可能来自用户查询,因此可能不受信任 - 但是,也许它们是 id 而不是字,所以在实践中是可以的,但仍然是一个非常糟糕的习惯)。 SELECT EXISTS(...)
而不是要求数据库向您发送一堆记录然后打算无视。 createkey
的记录,则函数不执行任何操作。没有错误。那是对的吗?谁能说? 0.1
(也许总是有 10 个 URL,但在这里按 len(urls)
缩放会更好)。 我可以继续,但我最好不要。
无论如何,为了回答您的问题,该函数似乎正在为 neural network 的隐藏层中的节点添加数据库条目。我认为,这个神经网络在输入层有词,在输出层有 URL。该应用程序的想法是尝试训练神经网络,以根据查询中的单词找到好的搜索结果 (URL)。请参阅函数
trainquery
,它采用参数 (wordids, urlids, selectedurl)
。大概(因为没有我必须猜测的文档字符串)wordids
是用户搜索的词,urlids
是搜索引擎提供给用户的 URL,而 selectedurl
是用户选择的。其想法是训练神经网络以更好地预测用户会选择哪些 URL,从而将这些 URL 在 future 的搜索结果中放在更高的位置。所以神秘的代码行阻止在隐藏层中创建节点,这些节点链接到输入层中的三个以上节点。在搜索应用程序的上下文中,这是有道理的:在过于特化的查询上训练网络是没有意义的,因为这些查询不会经常重复出现,因此训练是值得的。