以下代码有效,但是我想通过向量化来创建Z。如何实现?
import numpy as np
from numpy import sqrt
from math import fsum
points = np.array([[0,0],\
[5,-1],\
[4,6],\
[1,3]])
d = lambda x: fsum([sqrt((x[0]-z[0])**2 + (x[1]-z[1])**2) for z in points])
x = np.linspace(min(points[:,0]),max(points[:,0]),100)
y = np.linspace(min(points[:,1]),max(points[:,1]),100)
X, Y = np.meshgrid(x,y)
Z = np.zeros(np.shape(X))
for (i,j),_ in np.ndenumerate(Z):
Z[i,j] = d([X[i,j],Y[i,j]])
#Z=d([X,Y]) #this fails
答案 0 :(得分:0)
我们可以利用broadcasting
直接与
INFO ExtHandler Updated NIC state
[
{
"name": "lo",
"link": " mtu 65536 qdisc noqueue state UNKNOWN mode DEFAULT group default qlen 1000\"
"link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00 promiscuity 0 addrgenmode eui64 numtxqueues 1 "
"numrxqueues 1 gso_max_size 65536 gso_max_segs 65535 "
},
{
"name": "docker0",
"link": " mtu 1500 qdisc noqueue state DOWN mode DEFAULT group default \"
" link/ether 02:42:7d:f0:24:58 brd ff:ff:ff:ff:ff:ff promiscuity 0 \ bridge forward_delay 1500 hello_time "
"200 max_age 2000 ageing_time 30000 stp_state 0 priority 32768 vlan_filtering 0 vlan_protocol 802.1Q bridge_id "
"8000.2:42:7d:f0:24:58 designated_root 8000.2:42:7d:f0:24:58 root_port 0 root_path_cost 0 topology_change 0 "
"topology_change_detected 0 hello_timer 0.00 tcn_timer 0.00 topology_change_timer 0.00 gc_timer "
"16.78 vlan_default_pvid 1 vlan_stats_enabled 0 group_fwd_mask 0 group_address 01:80:c2:00:00:00 mcast_snooping "
"1 mcast_router 1 mcast_query_use_ifaddr 0 mcast_querier 0 mcast_hash_elasticity 4 mcast_hash_max 512 "
"mcast_last_member_count 2 mcast_startup_query_count 2 mcast_last_member_interval 100 mcast_membership_interval "
"26000 mcast_querier_interval 25500 mcast_query_interval 12500 mcast_query_response_interval 1000 mcast_startup_query_interval "
"3125 mcast_stats_enabled 0 mcast_igmp_version2 mcast_mld_version 1 nf_call_iptables 0 nf_call_ip6tables 0 nf_call_arptables 0 "
"addrgenmode eui64 numtxqueues 1 numrxqueues 1 gso_max_size 65536 gso_max_segs 65535 "
},
{
"name": "eth0",
"link": " mtu 1500 qdisc mq state UP mode DEFAULT group default qlen 1000\ "
"link/ether 00:0d:3a:11:4e:57 brd ff:ff:ff:ff:ff:ff promiscuity 0 addrgenmode eui64 numtxqueues 64 numrxqueues
""64 gso_max_size 62780 gso_max_segs 65535 "
}
]
版本一起工作,从而提高内存效率,并为自己提供矢量化的单层代码,就像这样-
1D
发布的样本数据的时间-
Z = np.sqrt((x[:,None] - points[:,0])**2 + (y[:,None,None] - points[:,1])**2).sum(2)
In [80]: %%timeit
...: X, Y = np.meshgrid(x,y)
...: Z = np.zeros(np.shape(X))
...: for (i,j),_ in np.ndenumerate(Z):
...: Z[i,j] = d([X[i,j],Y[i,j]])
10 loops, best of 3: 101 ms per loop
In [81]: %timeit ((x[:,None] - points[:,0])**2 + (y[:,None,None] - points[:,1])**2).sum(2)
1000 loops, best of 3: 246 µs per loop
在那里加速!