我刚接触Python和Numpy,试图创建263维数组,因为我需要这么多维度来构建机器学习模型。当然,一种方法是使用numpy.zeros或numpy.ones,并编写以下代码:
x=np.zeros((1,1,1,1,1,1,1,1,1,1,1)) #and more 1,1,1,1
有没有更简单的方法创建多维数组?
2 ** 263
个元素,它们是:
14821387422376473014217086081112052205218558037201992197050570753012880593911808。>>> np.zeros(263)
array([ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
0., 0., 0.])
>>> np.zeros((263, 3))
array([[ 0., 0., 0.],
[ 0., 0., 0.],
[ 0., 0., 0.],
[ 0., 0., 0.],
...
...
[ 0., 0., 0.],
[ 0., 0., 0.],
[ 0., 0., 0.],
[ 0., 0., 0.],
[ 0., 0., 0.],
[ 0., 0., 0.]])
许多先进的研究中心完全满足于使用普通的Numpy。对于量子力学或机器学习,不必使用少于32个维度似乎并没有太大影响。
让我们从 numpy
文档开始,help(np.zeros)
给出了:
zeros(shape, dtype=float, order='C')
Return a new array of given shape and type, filled with zeros.
Parameters
----------
shape : int or sequence of ints
Shape of the new array, e.g., ``(2, 3)`` or ``2``.
...
Returns
-------
out : ndarray
Array of zeros with the given shape, dtype, and order.
...
shape参数只是每个维度大小的列表(但您可能已经知道了)。在Python中有很多简单的方法来创建这样的列表,其中一种快速的方法是
np.zeros(np.ones(263, dtype=int))
numpy
有一个相对任意的32维限制。根据我的经验,您可以通过保留一个索引数组来显示每行属于哪个“维度”,从而获得类似且更灵活的行为。对于机器学习应用程序而言,你很可能并不需要这个:
shape = np.random.randint(1,10,(263,))
arr = np.zeros(shape) # causes a ValueError anyway
你实际上想要的是稀疏的东西
for i, value in enumerate(nonzero_values):
arr[idx[i]] = value
idx
在这种情况下是一个 (num_samples, 263)
的数组,而 nonzero_values
是一个 (num_samples,)
的数组。
机器学习算法通常使用这些 idx
和 value
数组(通常称为 X
和 Y
),否则实际的数组将会非常庞大。
有时候你需要一个维度的“one-hot”数组,这将使得 idx.shape == (num_samples, shape.sum())
,其中 idx
只包含 0 或 1 值。但这仍然比任何高维数组都要小。
现在有一个名叫DimPy的新包,可以非常方便地在 Python 中创建多维数组。要安装,请使用以下命令:
pip install dimpy
使用示例
from dimpy import *
a=dim(4,5,6) # This is a 3 dimensional array of 4x5x6 elements. Use any number of dimensions within '( ) ' separated by comma
print(a)
默认情况下,每个元素的值都为零。要更改它,请使用dfv(a,'新值')
要将其转换为numpy样式数组,请使用
a=npary(a)
在此处查看更多详细信息:https://www.respt.in/p/python-package-dimpy.html?m=1
np.zeros([1] * 263)
- cs95