numpy 为什么指定了 astype 为 float32,但是出来的结果还是 float64 呢?

numpy 为什么指定了 astype 为 float32,但是出来的结果还是 float64 呢?

def preprocess(image: Image.Image) -> ndarray:

image = image.resize((224, 224))

image = np.array(image)

image = image.transpose((2, 0, 1))

image = image.astype(np.float32)

image /= 255.0

mean = np.array([0.485, 0.456, 0.406]).reshape((3, 1, 1))

std = np.array([0.229, 0.224, 0.225]).reshape((3, 1, 1))

image = (image - mean) / std

return image

image = image.astype(np.float32) 为什么返回值的 dtype 是 float64 而不是 float32 呢?

from PIL import Image

import numpy as np

from numpy import ndarray

image = Image.open('bh.jpg')

def preprocess(image: Image.Image) -> ndarray:

image = image.resize((224, 224))

image = np.array(image)

image = image.transpose((2, 0, 1))

image = image.astype(np.float32)

image /= 255.0

mean = np.array([0.485, 0.456, 0.406]).reshape((3, 1, 1))

std = np.array([0.229, 0.224, 0.225]).reshape((3, 1, 1))

image = (image - mean) / std

return image

preprocessed_ndarray: ndarray = preprocess(image)

print(type(preprocessed_ndarray))

print(preprocessed_ndarray.shape)

print(preprocessed_ndarray.dtype)

print(preprocessed_ndarray[:1])

找了一个图片试试,print(preprocessed_ndarray.dtype) 的结果却是 float64


回答:

image = (image - mean) / std
mean 跟 std 都是 float64 ,算完结果就是 float64 了。

以上是 numpy 为什么指定了 astype 为 float32,但是出来的结果还是 float64 呢? 的全部内容, 来源链接: utcz.com/p/938838.html

回到顶部