我有一个形状为address
的numpy数组,意思是componentDidMount() {
getAsyncAddress().then((address) => {
this.props.loadProfile(address);
}
}
。
现在我使用以下代码对图像数据进行标准化:
(34799, 32, 32, 3)
但结果似乎不对,(num examples, width, height, channels)
的值为def normalize(x):
return (x - 128) / 128
X_train_norm = normalize(X_train)
,但X_train[0][0][0]
的输出为[28 25 24]
。
我使用以下测试代码:
X_train_norm[0][0][0]
输出:
[1.21875 1.1953125 1.1875]
为什么test = np.array([[[[28, 25, 24]]]])
print ((test - 128) / 128)
函数得到了错误的结果?
答案 0 :(得分:5)
我认为图片是作为一个充满uint8
字节的numpy数组加载的,其值介于0
和255
之间。
如果您对uint8
执行减法操作,结果为否定,则会发生回绕。与123 - 128 == 251
类似,然后将其除以128.例如:
>>> np.array([28,25,24], dtype=np.uint8) - 128
array([156, 153, 152], dtype=uint8)
然后,我们得到了报告:
>>> (np.array([28,25,24], dtype=np.uint8) - 128)/128
array([1.21875 , 1.1953125, 1.1875 ])
要解决此问题,您可以使用.astype(..)
:
def normalize(x):
return (x.astype(float) - 128) / 128
请注意,这与您使用函数的事实无关,如果您使用了原始数组的表达式,那么您将获得相同的结果。
答案 1 :(得分:4)
由于代码是当前编写的,如果x
有dtype uint8
(它似乎有),则减法将在uint8中进行,但除法是在float中完成的。
解决此问题的最简单方法是通过让128为浮点数来强制减法在浮点数中发生
def normalize(x):
return (x - 128.0) / 128