黄百万 發表於 2025-6-25 23:14:00

numpy

<p style="font-size: 40px; text-align: center">numpy相关</p>
<h2 id="1-高维ndarray报错超出存储如何解决">1. 高维ndarray,报错:超出存储,如何解决?</h2>
<p>​        分块处理:将数据分成较小的块来处理,而不是一次性加载整个数据集。这样可以减少对内存的需求。</p>
<p>使用<strong>Dask</strong>并行计算库</p>
<pre><code class="language-python">import dask.array as da

# 创建一个 Dask 数组
data = da.random.random((5, 50, 300, 100, 30, 49), chunks=(1, 10, 100, 50, 10, 10))

# 对每个块进行处理
def process_block(block):
    # 在这里对块进行处理
    print(f"Processing block with shape {block.shape}")

# 使用 Dask 计算
data.map_blocks(process_block).compute()

</code></pre>
<p>使用<strong>Zarr</strong>库</p>
<pre><code class="language-python">import zarr
import numpy as np

# 创建一个 Zarr 数组
data = zarr.zeros((5, 50, 300, 100, 30, 49), chunks=(1, 10, 100, 50, 10, 10), dtype=np.float64)

# 对每个块进行处理
def process_block(block):
    # 在这里对块进行处理
    print(f"Processing block with shape {block.shape}")

# 使用 Zarr 的块读取
for block in data.iter_chunks():
    process_block(block)

</code></pre>
<h2 id="2-产生随机数">2. 产生随机数</h2>
<pre><code class="language-python"># linspace
x1 = np.linspace(4, 13, sample_num) # 产生4-13范围内的sample_num个随机数

# random.randint
np.random.randint(0, m, 1)# 产生0-m范围内的1个整数
</code></pre>
<h2 id="3-ndarray拼接">3. ndarray拼接</h2>
<pre><code class="language-python">x = np.concatenate((, ), axis=0)
</code></pre>
<h2 id="4-dot函数">4. dot函数</h2>
<pre><code class="language-python">np.dot(a,b) #a、b矩阵点乘
</code></pre>
<h2 id="5-数组多维转一维">5. 数组多维转一维</h2>
<pre><code class="language-python">ravel()、flatten()、squeeze()
ravel():                # 如果没有必要,不会产生源数据的副本
flatten():                # 返回源数据的副本
squeeze():                # 只能对维数为1的维度降维
</code></pre>
<h2 id="6-reapeat函数">6. reapeat函数</h2>
<h2 id="7-ndarray改变维度">7. ndarray改变维度</h2>
<pre><code class="language-python">a.reshape()
# 可以将数据的维度变化成想要的维度。
ndarray.reshape(x, y).astype(float)
# 再转为tensor
</code></pre>
<h2 id="8-滑动窗口">8. 滑动窗口</h2>
<pre><code class="language-python">slide_arr1 = np.lib.stride_tricks.sliding_window_view(a1, # 原数组 3 # 窗口大小,也可以是元组,如(2,2) )
</code></pre><br><br>
来源:https://www.cnblogs.com/systemTang/p/18949026
頁: [1]
查看完整版本: numpy