gpt4 book ai didi

Python 的 random 模块无法访问

转载 作者:行者123 更新时间:2023-12-01 05:12:06 24 4
gpt4 key购买 nike

当我调用 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

最佳答案

当您使用 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

关于Python 的 random 模块无法访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23977524/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com