【问题标题】:Issue with Python data-mining code from "Programming Collective Intelligence" to count crossed lines来自“编程集体智能”的 Python 数据挖掘代码问题以计算交叉线
【发布时间】:2011-07-31 09:14:26
【问题描述】:

我目前正在研究 Toby Segaran 的 Programming Collective Intelligence 并尝试完成优化章节中的一些代码,特别是计数行代码。但是,我在代码中遇到了两个我不太理解的问题。 代码

def crosscount(v):


loc = dict([(people[i],(v[i*2],v[i*2+1])) for i in range(0, len(people))])
total = 0

for i in range(len(links)):
    for j in range(i+1, len(links)):
        (x1,y1), (x2,y2) = loc[links[i][0]],loc[links[i][1]]
        (x3,y3), (x4, y4)= loc[links[j][0]],loc[links[j][1]]

        den = (y4-y3)*(x2-x1)-(x4-x3)*(y2-y1)

        if den == 0: continue

最初,对于定义 loc 字典的行,我在定义 v[i*2] 的地方收到错误“列表索引超出范围”,我认为这是因为 v 是生成的随机数而不是列表。

为了让它正常工作以便我可以尝试遵循逻辑,我将其更改为 v*2 以生成整数对,但在使用“不支持的操作数类型(s ) for -: 'list' 和 'list''。我尝试将 (x1, y1) 等作为列表,然后对其进行切片,但我仍然得到相同的结果,并且除非我先将值转换为字符串,否则转换为 int() 无效(这似乎非常不蟒蛇)。我将不胜感激有关如何使此代码正常工作的一些建议,以便我可以看到在计算交叉线时应该发生什么。

【问题讨论】:

  • 缩进被破坏了,这段代码肯定不会像写的那样编译。此外,当我们不知道 linkspeople 是什么数据类型时,很难回答这个问题。
  • 两个范围...为什么不for link in links

标签: python data-mining


【解决方案1】:

好吧,我读了这本书,我搜索了我的测试代码,发现它对我有用,图表得分函数如下:

def graphscore(v, proxlimit = 50):
loc = dict([(people[i], (v[i*2], v[i*2+1])) for i in range(0, len(people))])
total = 0.0

#penalize crosscount
for i in range(len(links)):
    for j in range(i+1, len(links)):
        (x1, y1), (x2, y2) = loc[links[i][0]], loc[links[i][1]]
        (x3, y3), (x4, y4) = loc[links[j][0]], loc[links[j][1]]

        den = (y4-y3)*(x2-x1)-(x4-x3)*(y2-y1)
        if den==0: continue #lines parallel

        ua = ((x4-x3)*(y1-y3)-(y4-y3)*(x1-x3))/float(den)
        ub = ((x2-x1)*(y1-y3)-(y2-y1)*(x1-x3))/float(den)
        if ua > 0 and ua < 1 and ub > 0 and ub < 1:
            total += 1.0

#penalize tightened nodes
for i in range(len(people)):
    for j in range(i+1, len(people)):
        (x1, y1), (x2, y2) = loc[people[i]], loc[people[j]]
        dist = math.sqrt(math.pow(x1-x2, 2) + math.pow(y1-y2, 2))
        if dist < proxlimit:
            total += (1.0-(dist/proxlimit))
return total

在文件开头声明了以下全局变量(当然):

people = ['Charlie', 'Augustus', 'Veruca', 'Violet',
         'Mike', 'Joe', 'Willy', 'Miranda']
links = [('Augustus', 'Willy'),
        ('Mike', 'Joe'),
        ('Miranda', 'Mike'),
        ('Violet', 'Augustus'),
        ('Miranda', 'Willy'),
        ('Charlie', 'Mike'),
        ('Veruca', 'Joe'),
        ('Miranda', 'Augustus'),
        ('Willy', 'Augustus'),
        ('Joe', 'Charlie'),
        ('Veruca', 'Augustus'),
        ('Miranda', 'Joe')]

【讨论】:

    猜你喜欢
    • 2010-11-16
    • 2017-06-04
    • 2012-08-04
    • 2011-01-24
    • 1970-01-01
    • 2011-07-28
    • 2011-07-25
    • 2015-09-12
    • 2011-05-04
    相关资源
    最近更新 更多