【问题标题】:Python's random module made inaccessiblePython 的随机模块无法访问
【发布时间】:2014-06-01 07:05:25
【问题描述】:

当我调用 random.sample(arr,length) 时,错误返回 random_sample() 最多接受 1 个位置参数(给定 2 个)。我尝试以不同的名称导入 numpy,但这不能解决问题。有什么想法吗?谢谢

import numpy.random
import random
import numpy as np
from numpy import *


points = [[1,1],[1.5,2],[3,4],[5,7],[3.5,5],[4.5,5], [3.5,4]]


def cluster(X,center):
  clusters = {}

  for x in X:

    z= min([(i[0], np.linalg.norm(x-center[i[0]]))  for i in enumerate(center)], key=lambda t:t[1])

    try:
      clusters[z].append(x)
    except KeyError:
      clusters[z]=[x]

  return clusters

def update(oldcenter,clusters):

 d=[]
 r=[]
 newcenter=[]

 for k in clusters:
  if k[0]==0: 
   d.append(clusters[(k[0],k[1])])

  else:
   r.append(clusters[(k[0],k[1])])

 c=np.mean(d, axis=0)
 u=np.mean(r,axis=0)
 newcenter.append(c)
 newcenter.append(u)


 return newcenter

def shouldStop(oldcenter,center, iterations):
    MAX_ITERATIONS=0
    if iterations > MAX_ITERATIONS: return True
    u=np.array_equal(center,oldcenter)
    return u

def init_board(N):
    X = np.array([(random.uniform(1,4), random.uniform(1, 4)) for i in range(4)])
    return X

def kmeans(X,k):    

  clusters={}
  iterations = 0
  oldcenter=([[],[]])
  center = random.sample(X,k)                       

  while not shouldStop(oldcenter, center, iterations):
        # Save old centroids for convergence test. Book keeping.
        oldcenter=center

        iterations += 1
        clusters=cluster(X,center)  
        center=update(oldcenter,clusters)

  return (center,clusters)

X=init_board(4)
(center,clusters)=kmeans(X,2)
print "center:",center
#print "clusters:", clusters

【问题讨论】:

  • 请发布实际的、完整的错误信息。
  • 看最后一个import
  • 不要import *。这就是原因。
  • 谢谢大家,成功了,我是python的初学者。那么,你能解释一下我什么时候应该使用 import * 吗?
  • import * 的唯一目的是使将来对模块中对象的引用更短。但它会影响可读性,正如你所经历的那样

标签: python


【解决方案1】:

当您使用from numpy import * 时,会将numpy 命名空间中的所有项目导入您的脚本命名空间。当您这样做时,任何具有相同名称的函数/变量/等都将被 numpy 命名空间中的项目覆盖。

numpy 有一个名为 numpy.random 的子包,然后它会覆盖您的 random 导入,如下面的代码所示:

import random

# Here random is the Python stdlib random package.

from numpy import *

# As numpy has a random package, numpy.random, 
# random is now the numpy.random package as it has been overwritten.

在这种情况下,您应该改用import numpy as np,这将允许您访问两者:

import random

# random now contains the stdlib random package

import numpy as np

# np.random now contains the numpy.random package

【讨论】:

    【解决方案2】:

    你的积分是List类型,所以你应该把它转换成一个数组

    points = np.asarray(point)
    

    另外,你应该使用import random

    【讨论】:

    • 您的答案非常难以阅读,我强烈建议您阅读stackoverflow.com/help/how-to-answer,使用该链接作为参考可以极大地提高您的答案的可见性和清晰度。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-16
    • 2011-12-20
    • 1970-01-01
    • 2015-04-26
    • 1970-01-01
    • 1970-01-01
    • 2016-10-13
    相关资源
    最近更新 更多