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

阅读 2.2k
1 个回答

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

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题