Python 3.x 何时应使用matrix.aType和何时使用matrix.view?

Python 3.x 何时应使用matrix.aType和何时使用matrix.view?,python-3.x,numpy,Python 3.x,Numpy,我有一个int32整数矩阵(50k x 50k左右),我需要将其转换为float32。我可以用它来做 # Preparation for the example import numpy as np n = 50_000 matrix = np.random.randint(0, 10, (n, n), dtype='int32') # Way 1: matrix = matrix.astype(np.float32, copy=False) # Way 2: matrix = matrix

我有一个int32整数矩阵(50k x 50k左右),我需要将其转换为float32。我可以用它来做

# Preparation for the example
import numpy as np
n = 50_000
matrix = np.random.randint(0, 10, (n, n), dtype='int32')

# Way 1:
matrix = matrix.astype(np.float32, copy=False)

# Way 2:
matrix = matrix.view(np.float32)
我什么时候应该用哪一种?与“真实”numpy阵列相比,后期使用视图是否存在速度劣势

我试过的 执行时间分析(创建,而不是以后访问)

显然,视图比aType快得多

记忆分析
清楚地显示
视图
选项使用的内存非常少。

方式1
方式2
返回不同的数组
astype()
将数组数据转换为不同的类型,而
view()
只是将内存解释为数据类型,而实际上不做任何更改。我的猜测是你想坚持方式1。这到底有什么不同?访问数据是否较慢?对于解释的矩阵乘法是否较慢?结果真的不同吗?让你的生活变得简单,只需看看这两个结果数组。“查看”如中所示,让口译员将其打印出来以供参考you@PaulPanzer这只是我的例子中的一个问题。问题仍然存在。@Dan第一个问题是“要么第一条路,要么第二条路”。示例代码已调整。
import numpy as np
import timeit


def create_boxplot(duration_list, showfliers=False):
    import seaborn as sns
    import matplotlib.pyplot as plt
    import operator

    plt.figure(num=None, figsize=(8, 4), dpi=300, facecolor="w", edgecolor="k")
    sns.set(style="whitegrid")
    sorted_keys, sorted_vals = zip(
        *sorted(duration_list.items(), key=operator.itemgetter(1))
    )
    flierprops = dict(markerfacecolor="0.75", markersize=1, linestyle="none")
    ax = sns.boxplot(
        data=sorted_vals,
        width=0.3,
        orient="h",
        flierprops=flierprops,
        showfliers=showfliers,
    )
    ax.set(xlabel="Time in ms", ylabel="")
    plt.yticks(plt.yticks()[0], sorted_keys)
    plt.tight_layout()
    plt.savefig("output.png")


n = 5_000
matrix = np.random.randint(0, 2, (n, n), dtype='int32')
print(matrix.dtype)

matrix = matrix.view(np.float32)
print(matrix.dtype)

timeit_d = {}
timeit_d["repeat"] = 500
timeit_d["number"] = 3
timeit_d["setup"] = "import numpy as np; n=5_000; matrix = np.random.randint(0, 2, (n, n), dtype='int32')"

duration_list = {}

# Way 1
durations = timeit.repeat(
    "matrix2 = matrix.view(np.float32)",
    setup=timeit_d["setup"],
    repeat=timeit_d["repeat"],
    number=timeit_d["number"],
)
duration_list["view"] = durations
print("Done views")

# Way 2
durations = timeit.repeat(
    "matrix2 = matrix.astype(np.float32)",
    setup=timeit_d["setup"],
    repeat=timeit_d["repeat"],
    number=timeit_d["number"],
)
duration_list["astype"] = durations
print("Done astype")

# Visualize
create_boxplot(duration_list)
$ valgrind --tool=massif python3 foobar.py
$ massif-visualizer massif.out.view