- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
在上面的代码中,当我将 print 函数放在函数和方法之外时,它可以工作,但是当我将 print、sys.stdout.write 和 os.write 函数放在函数和方法内部时,终端中不会打印任何内容?我在stackoverflow和互联网上搜索过,但没有找到原因。而且,包含打印功能的方法是在main中调用的。
# Copyright Anne M. Archibald 2008
# Released under the scipy license
from __future__ import division, print_function, absolute_import
from scipy import spatial
from sklearn.datasets.samples_generator import make_blobs,make_classification
import sys
import numpy as np
from heapq import heappush, heappop
import scipy.sparse
import os
__all__ = ['minkowski_distance_p', 'minkowski_distance',
'Rectangle', 'KDTree']
print("I am outside functions")
def minkowski_distance_p(x, y, p=2):
sys.stdout.write(" i am in minkowski_distance_p")
print("i am in minkowski_distance_p")
os.write(" i am in minkowski_distance_p")
"""
Compute the p-th power of the L**p distance between two arrays.
For efficiency, this function computes the L**p distance but does
not extract the pth root. If `p` is 1 or infinity, this is equal to
the actual L**p distance.
Parameters
----------
x : (M, K) array_like
Input array.
y : (N, K) array_like
Input array.
p : float, 1 <= p <= infinity
Which Minkowski p-norm to use.
Examples
--------
>>> minkowski_distance_p([[0,0],[0,0]], [[1,1],[0,1]])
array([2, 1])
"""
x = np.asarray(x)
y = np.asarray(y)
if p == np.inf:
return np.amax(np.abs(y-x), axis=-1)
elif p == 1:
return np.sum(np.abs(y-x), axis=-1)
else:
return np.sum(np.abs(y-x)**p, axis=-1)
def minkowski_distance(x, y, p=2):
"""
Compute the L**p distance between two arrays.
Parameters
----------
x : (M, K) array_like
Input array.
y : (N, K) array_like
Input array.
p : float, 1 <= p <= infinity
Which Minkowski p-norm to use.
Examples
--------
>>> minkowski_distance([[0,0],[0,0]], [[1,1],[0,1]])
array([ 1.41421356, 1. ])
"""
x = np.asarray(x)
y = np.asarray(y)
if p == np.inf or p == 1:
return minkowski_distance_p(x, y, p)
else:
return minkowski_distance_p(x, y, p)**(1./p)
class Rectangle(object):
"""Hyperrectangle class.
Represents a Cartesian product of intervals.
"""
def __init__(self, maxes, mins):
"""Construct a hyperrectangle."""
self.maxes = np.maximum(maxes,mins).astype(np.float)
self.mins = np.minimum(maxes,mins).astype(np.float)
self.m, = self.maxes.shape
def __repr__(self):
return "<Rectangle %s>" % list(zip(self.mins, self.maxes))
def volume(self):
"""Total volume."""
return np.prod(self.maxes-self.mins)
def split(self, d, split):
"""
Produce two hyperrectangles by splitting.
In general, if you need to compute maximum and minimum
distances to the children, it can be done more efficiently
by updating the maximum and minimum distances to the parent.
Parameters
----------
d : int
Axis to split hyperrectangle along.
split :
Input.
"""
mid = np.copy(self.maxes)
mid[d] = split
less = Rectangle(self.mins, mid)
mid = np.copy(self.mins)
mid[d] = split
greater = Rectangle(mid, self.maxes)
return less, greater
def min_distance_point(self, x, p=2.):
"""
Return the minimum distance between input and points in the hyperrectangle.
Parameters
----------
x : array_like
Input.
p : float, optional
Input.
"""
return minkowski_distance(0, np.maximum(0,np.maximum(self.mins-x,x-self.maxes)),p)
def max_distance_point(self, x, p=2.):
"""
Return the maximum distance between input and points in the hyperrectangle.
Parameters
----------
x : array_like
Input array.
p : float, optional
Input.
"""
return minkowski_distance(0, np.maximum(self.maxes-x,x-self.mins),p)
def min_distance_rectangle(self, other, p=2.):
"""
Compute the minimum distance between points in the two hyperrectangles.
Parameters
----------
other : hyperrectangle
Input.
p : float
Input.
"""
return minkowski_distance(0, np.maximum(0,np.maximum(self.mins-other.maxes,other.mins-self.maxes)),p)
def max_distance_rectangle(self, other, p=2.):
"""
Compute the maximum distance between points in the two hyperrectangles.
Parameters
----------
other : hyperrectangle
Input.
p : float, optional
Input.
"""
return minkowski_distance(0, np.maximum(self.maxes-other.mins,other.maxes-self.mins),p)
class KDTree(object):
"""
kd-tree for quick nearest-neighbor lookup
This class provides an index into a set of k-dimensional points which
can be used to rapidly look up the nearest neighbors of any point.
Parameters
----------
data : (N,K) array_like
The data points to be indexed. This array is not copied, and
so modifying this data will result in bogus results.
leafsize : int, optional
The number of points at which the algorithm switches over to
brute-force. Has to be positive.
Raises
------
RuntimeError
The maximum recursion limit can be exceeded for large data
sets. If this happens, either increase the value for the `leafsize`
parameter or increase the recursion limit by::
>>> import sys
>>> sys.setrecursionlimit(10000)
Notes
-----
The algorithm used is described in Maneewongvatana and Mount 1999.
The general idea is that the kd-tree is a binary tree, each of whose
nodes represents an axis-aligned hyperrectangle. Each node specifies
an axis and splits the set of points based on whether their coordinate
along that axis is greater than or less than a particular value.
During construction, the axis and splitting point are chosen by the
"sliding midpoint" rule, which ensures that the cells do not all
become long and thin.
The tree can be queried for the r closest neighbors of any given point
(optionally returning only those within some maximum distance of the
point). It can also be queried, with a substantial gain in efficiency,
for the r approximate closest neighbors.
For large dimensions (20 is already large) do not expect this to run
significantly faster than brute force. High-dimensional nearest-neighbor
queries are a substantial open problem in computer science.
The tree also supports all-neighbors queries, both with arrays of points
and with other kd-trees. These do use a reasonably efficient algorithm,
but the kd-tree is not necessarily the best data structure for this
sort of calculation.
"""
def __init__(self, data, leafsize=10):
print("aaa")
self.data = np.asarray(data)
self.n, self.m = np.shape(self.data)
self.leafsize = int(leafsize)
if self.leafsize < 1:
raise ValueError("leafsize must be at least 1")
self.maxes = np.amax(self.data,axis=0)
self.mins = np.amin(self.data,axis=0)
self.tree = self.__build(np.arange(self.n), self.maxes, self.mins)
class node(object):
if sys.version_info[0] >= 3:
def __lt__(self, other):
return id(self) < id(other)
def __gt__(self, other):
return id(self) > id(other)
def __le__(self, other):
return id(self) <= id(other)
def __ge__(self, other):
return id(self) >= id(other)
def __eq__(self, other):
return id(self) == id(other)
class leafnode(node):
def __init__(self, idx):
self.idx = idx
self.children = len(idx)
class innernode(node):
def __init__(self, split_dim, split, less, greater):
self.split_dim = split_dim
self.split = split
self.less = less
self.greater = greater
self.children = less.children+greater.children
def __build(self, idx, maxes, mins):
if len(idx) <= self.leafsize:
return KDTree.leafnode(idx)
else:
data = self.data[idx]
# maxes = np.amax(data,axis=0)
# mins = np.amin(data,axis=0)
d = np.argmax(maxes-mins)
maxval = maxes[d]
minval = mins[d]
if maxval == minval:
# all points are identical; warn user?
return KDTree.leafnode(idx)
data = data[:,d]
# sliding midpoint rule; see Maneewongvatana and Mount 1999
# for arguments that this is a good idea.
split = (maxval+minval)/2
less_idx = np.nonzero(data <= split)[0]
greater_idx = np.nonzero(data > split)[0]
if len(less_idx) == 0:
split = np.amin(data)
less_idx = np.nonzero(data <= split)[0]
greater_idx = np.nonzero(data > split)[0]
if len(greater_idx) == 0:
split = np.amax(data)
less_idx = np.nonzero(data < split)[0]
greater_idx = np.nonzero(data >= split)[0]
if len(less_idx) == 0:
# _still_ zero? all must have the same value
if not np.all(data == data[0]):
raise ValueError("Troublesome data array: %s" % data)
split = data[0]
less_idx = np.arange(len(data)-1)
greater_idx = np.array([len(data)-1])
lessmaxes = np.copy(maxes)
lessmaxes[d] = split
greatermins = np.copy(mins)
greatermins[d] = split
return KDTree.innernode(d, split,
self.__build(idx[less_idx],lessmaxes,mins),
self.__build(idx[greater_idx],maxes,greatermins))
def __query(self, x, k=1, eps=0, p=2, distance_upper_bound=np.inf):
side_distances = np.maximum(0,np.maximum(x-self.maxes,self.mins-x))
if p != np.inf:
side_distances **= p
min_distance = np.sum(side_distances)
else:
min_distance = np.amax(side_distances)
# priority queue for chasing nodes
# entries are:
# minimum distance between the cell and the target
# distances between the nearest side of the cell and the target
# the head node of the cell
q = [(min_distance,
tuple(side_distances),
self.tree)]
# priority queue for the nearest neighbors
# furthest known neighbor first
# entries are (-distance**p, i)
neighbors = []
if eps == 0:
epsfac = 1
elif p == np.inf:
epsfac = 1/(1+eps)
else:
epsfac = 1/(1+eps)**p
if p != np.inf and distance_upper_bound != np.inf:
distance_upper_bound = distance_upper_bound**p
while q:
min_distance, side_distances, node = heappop(q)
if isinstance(node, KDTree.leafnode):
# brute-force
data = self.data[node.idx]
ds = minkowski_distance_p(data,x[np.newaxis,:],p)
for i in range(len(ds)):
if ds[i] < distance_upper_bound:
if len(neighbors) == k:
heappop(neighbors)
heappush(neighbors, (-ds[i], node.idx[i]))
if len(neighbors) == k:
distance_upper_bound = -neighbors[0][0]
else:
# we don't push cells that are too far onto the queue at all,
# but since the distance_upper_bound decreases, we might get
# here even if the cell's too far
if min_distance > distance_upper_bound*epsfac:
# since this is the nearest cell, we're done, bail out
break
# compute minimum distances to the children and push them on
if x[node.split_dim] < node.split:
near, far = node.less, node.greater
else:
near, far = node.greater, node.less
# near child is at the same distance as the current node
heappush(q,(min_distance, side_distances, near))
# far child is further by an amount depending only
# on the split value
sd = list(side_distances)
if p == np.inf:
min_distance = max(min_distance, abs(node.split-x[node.split_dim]))
elif p == 1:
sd[node.split_dim] = np.abs(node.split-x[node.split_dim])
min_distance = min_distance - side_distances[node.split_dim] + sd[node.split_dim]
else:
sd[node.split_dim] = np.abs(node.split-x[node.split_dim])**p
min_distance = min_distance - side_distances[node.split_dim] + sd[node.split_dim]
# far child might be too far, if so, don't bother pushing it
if min_distance <= distance_upper_bound*epsfac:
heappush(q,(min_distance, tuple(sd), far))
if p == np.inf:
return sorted([(-d,i) for (d,i) in neighbors])
else:
return sorted([((-d)**(1./p),i) for (d,i) in neighbors])
def query(self, x, k=1, eps=0, p=2, distance_upper_bound=np.inf):
print("I am in the query method")
sys.stdout.write("I am in the query method")
os.write("I am in the query method")
x = np.asarray(x)
if np.shape(x)[-1] != self.m:
raise ValueError("x must consist of vectors of length %d but has shape %s" % (self.m, np.shape(x)))
if p < 1:
raise ValueError("Only p-norms with 1<=p<=infinity permitted")
retshape = np.shape(x)[:-1]
if retshape != ():
if k is None:
dd = np.empty(retshape,dtype=np.object)
ii = np.empty(retshape,dtype=np.object)
elif k > 1:
dd = np.empty(retshape+(k,),dtype=np.float)
dd.fill(np.inf)
ii = np.empty(retshape+(k,),dtype=np.int)
ii.fill(self.n)
elif k == 1:
dd = np.empty(retshape,dtype=np.float)
dd.fill(np.inf)
ii = np.empty(retshape,dtype=np.int)
ii.fill(self.n)
else:
raise ValueError("Requested %s nearest neighbors; acceptable numbers are integers greater than or equal to one, or None")
for c in np.ndindex(retshape):
hits = self.__query(x[c], k=k, eps=eps, p=p, distance_upper_bound=distance_upper_bound)
if k is None:
dd[c] = [d for (d,i) in hits]
ii[c] = [i for (d,i) in hits]
elif k > 1:
for j in range(len(hits)):
dd[c+(j,)], ii[c+(j,)] = hits[j]
elif k == 1:
if len(hits) > 0:
dd[c], ii[c] = hits[0]
else:
dd[c] = np.inf
ii[c] = self.n
return dd, ii
else:
hits = self.__query(x, k=k, eps=eps, p=p, distance_upper_bound=distance_upper_bound)
if k is None:
return [d for (d,i) in hits], [i for (d,i) in hits]
elif k == 1:
if len(hits) > 0:
return hits[0]
else:
return np.inf, self.n
elif k > 1:
dd = np.empty(k,dtype=np.float)
dd.fill(np.inf)
ii = np.empty(k,dtype=np.int)
ii.fill(self.n)
for j in range(len(hits)):
dd[j], ii[j] = hits[j]
return dd, ii
else:
raise ValueError("Requested %s nearest neighbors; acceptable numbers are integers greater than or equal to one, or None")
if __name__ == "__main__":
print("I am the main")
x, y = make_blobs(
n_samples=10000,
centers=4,
n_features=2,
center_box=(-50.0, 50.0),
cluster_std=3,
)
tree = spatial.KDTree(data=x)
pts = np.array([[0, 0], [2.1, 2.9]])
tree.query(pts)
输出:
I am outside functions
I am the main
“查询”方法中用于打印的三个函数不打印任何内容。
最佳答案
在我看来,您从 main 中调用的 query
方法不是您定义的查询方法。您正在导入 spatial
并定义 KDTree
类,但在主代码中您正在创建 spatial.KDTree
对象。您绝对确定这是正确的对象吗?尝试删除 spatial
部分。我的建议:
if __name__ == "__main__":
print("I am the main")
x, y = make_blobs(
n_samples=10000,
centers=4,
n_features=2,
center_box=(-50.0, 50.0),
cluster_std=3,
)
tree = KDTree(data=x)
pts = np.array([[0, 0], [2.1, 2.9]])
tree.query(pts)
关于python - 为什么 print、sys.stdout.write 和 os.write 不在终端中打印任何内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54590292/
使用 Guake 终端这个可自定义且强大的适合各种用户的工具快速访问你的终端。 Guake 终端:GNOME 桌面中自上而下终端 Guake 是一款为 GNOME
我是 python 的新手,正在尝试运行 python 2.7 script .获得了 python 2.7 的 pip 并从 mac 终端 shell 安装了 pyCrypto 的依赖项。 我想尝试
我正在寻找一种在 Swift (macOS) 中运行终端命令的方法。我遇到了this发布,但我似乎无法获得任何解决方案。我正在尝试从我的应用程序关闭我的 mac,就像您可以从终端执行的那样(osasc
我在 macOS 上使用 bash 终端。 用户名、计算机名和文件路径占据了大部分行,所以如果我写一个长命令,我会从一行开始,然后在下一行继续。 相反,我希望行光标从用户名和计算机名下方的下一行开始。
是否有一个变量或函数可以告诉我光标的实际位置? #!/usr/bin/env perl use warnings; use 5.012; use Term::ReadKey; use Term::Ca
如何在 Mac Os X(10.6.8) 上的 gnuplot 中启用 tikz 终端? 我有工作 tikz 的 latex 。现在我从 http://www.lua.org/ 安装了 lua并下载g
我正在学习一个名为 Starting a Django 1.4 Project the Right Way 的教程,其中提供了有关如何使用 virtualenv 和 virtualenvwrapper
我正在尝试用java编写一个unix终端模拟器。我有很多麻烦。我似乎无法更改程序的工作目录,因此“cd”等命令无法正常工作。我的问题是,如果我运行一个需要用户输入的命令,有什么方法可以将该输入发送到正
我在这方面完全是个新手(Mac leopard 中的终端),我希望能从网络上获得生命线,因为我确实碰壁了。 我想在终端中以 root 身份运行脚本。该脚本保存为扩展名为 .rtf 的文本文件。我已经插
尝试在我的 osascript 命令中包含引号 ' ' 时遇到了一个奇怪的问题。 如果我尝试转义一个正常的可转义字符,它就可以正常工作。示例: osascript -e 'tell app "Find
我正在制作一个控制台 Java 应用程序,您可以在其中输入控制台命令,例如 Macintosh/Ubuntu/Windows 命令提示符上的终端,然后将其输出到日志。 我想知道,在执行系统/控制台命令
在终端中输入 mysql 命令并按回车键会换行。 但有时当我犯错时,即使用分号结束语句也无法退出此模式。 Ctrl + c 退出mysql。我怎样才能退出插入模式? 最佳答案 你必须用 ';' 结束
我正在尝试编写一个 C 代码来打开 xeyes 应用程序,然后那些眼睛在特定的时间段内不断改变其颜色.. 我尝试通过执行具有一种中心颜色的 xeyes、添加 3 秒的延迟、终止进程并在循环内打开具有另
是否有一种语法允许我在 System.out.println() 行 的同一行中读取用户的输入? 例子: What is your name?:(<-- Output) Jack (<-- In
我有一个 Wordpress 上传文件夹,该文件夹使用子文件夹构建了几个月。 wolfr2:uploads wolfr$ tree . . |-- 2007 | |-- 08 | | |-
如何从 mac 终端使用 sqlite3 找出表的列名?我忘记了我给这些列起的名字,我也不知道这些名字是怎么来的。谢谢! 最佳答案 来自 http://www.sqlite.org/sqlite.ht
我需要我的终端发送一个未使用的控制字符或转义序列,它在所有层都没有效果:被shell(bash,…)忽略,被行编辑器(readline,…)忽略,被所有应用程序(vim,less,mutt,…)忽略。
我做了一个文本编辑器,我想把它移植到 Linux 上,这样我就可以通过 SSH 远程使用它。我不太了解 Linux 终端,所以也许我遗漏了一些明显的东西,因为我简直不敢相信在 2013 年远程终端仍然
我最近想放一个 java 类文件供下载,人们可以在终端中运行它。这是一个 Minecraft 命令生成器,因此下载它的人不一定具有最大的心智能力(当然,我指的是 8 岁的 child ,他们不知道自己
我有一个文件“test.txt”,里面有一个数字列表,就像这样 1 3 4 2 3 40 312 53 243 321 423 ...etc 我还有一个可执行文件,它是一种排序算法,例如 hea
我是一名优秀的程序员,十分优秀!