python - 嵌套 for 循环 vs numpy
问题描述
我在嵌套循环内的嵌套循环内有嵌套循环,但这真的很慢。有没有一种麻木的方式来做这种事情?
这类似于用于视觉识别的 cs231n 神经网络。
N = 100 # number of points per class
D = 2 # dimensionality
K = 3 # number of classes
X = np.zeros((N*K,D)) # data matrix (each row = single example)
y = np.zeros(N*K, dtype='uint8') # class labels
for j in xrange(K):
ix = range(N*j,N*(j+1))
r = np.linspace(0.0,1,N) # radius
t = np.linspace(j*4,(j+1)*4,N) + np.random.randn(N)*0.2 # theta
X[ix] = np.c_[r*np.sin(t), r*np.cos(t)]
y[ix] =
解决方案
三个选项:
np.tensordot(x,w,((1,2),(1,2)))+b
np.inner(x.reshape(N,-1),w.reshape(M,-1))+b
np.einsum("ikl,jkl",x,w)+b
推荐阅读
- arguments - 为什么 Tcl 允许带有空格的 proc 名称,但不允许带有空格的参数?
- javascript - 我在 Vue 中构建了一个应用程序。我需要存储信息以备后用,使用js-cookie是一种好方法吗?
- c++ - 如何使用带有重心公式的代码获得正确答案?
- tornadofx - 类型安全的 css 对控制 tornadofx 没有影响
- forms - 用于订购的附加选择字段
- javascript - Javascript - 将设备加速度转换为地球坐标
- events - DDD、领域服务和事件
- sap - Sap.Data.SQLAnywhere.SAException:使用 .NET 连接到 Sybase SQL Anywhere 时找不到语言资源文件 (dblgen17.dll)
- python - 使用 Pomegranate 拟合 Beta 分布
- gatsby - 使用 netlifyCMS 和 Gatsby “找不到后端”