【问题标题】:Why will numpy.round will not round my array?为什么 numpy.round 不会舍入我的数组?
【发布时间】:2019-07-17 14:22:22
【问题描述】:

我正在尝试对 Keras 模型预测结果输出的 numpy 数组进行舍入。但是在执行 numpy.round/numpy.around 之后,没有任何变化。

这里的最终目标是,如果低于/等于 0.50,则数组向下舍入为 0,如果高于 0.50,则向上舍入。

代码在这里:

from keras.models import load_model

import numpy

model = load_model('tried.h5')
data = numpy.loadtxt("AppData\Roaming\MetaQuotes\Terminal\94DDB309C90B408373EFC53AC730F336\MQL4\Files\indicatorout.csv", delimiter=",")
data = numpy.array([data])
print(data)
outdata = model.predict(data)
print(outdata)
numpy.around(outdata, 0)
print(outdata)
numpy.savetxt("AppData\Roaming\MetaQuotes\Terminal\94DDB309C90B408373EFC53AC730F336\MQL4\Files\modelout.txt", outdata)

日志也在这里:

Using TensorFlow backend.
[[1.19539070e+01 1.72686310e+01 2.24426384e+01 1.82771435e+01
  2.23788052e+01 1.62105408e+01 1.44595184e+01 1.90179043e+01
  1.71749554e+01 1.69194088e+01 1.89911938e+01 1.76701393e+01
  5.19613740e-01 5.38522415e+01 9.64037247e+01 1.73570000e-04
  4.35710000e-04 9.55710000e-04]]
[[0.4215713]]
[[0.4215713]]

任何帮助将不胜感激,谢谢。

【问题讨论】:

  • np.around 不会就地运行。大多数numpy 函数返回一个新数组。
  • 因为如果没有创建新数组,您需要指定 out=None。
  • 非常感谢你们!

标签: python numpy tensorflow rounding numpy-ndarray


【解决方案1】:

我假设您希望数组中的元素四舍五入到一些 n 小数位。下面是这样做的说明:

# sample array to work with
In [21]: arr = np.random.randn(4)

In [22]: arr
Out[22]: array([-0.94817409, -1.61453252,  0.16566428, -0.53507549])

# round to 3 decimal places; note that `arr` is still unaffected.
In [23]: arr.round(decimals=3)
Out[23]: array([-0.948, -1.615,  0.166, -0.535])

# if you want to round it to nearest integer
In [24]: arr_rint = np.rint(arr)

In [25]: arr_rint
Out[25]: array([-1., -2.,  0., -1.])

要使小数舍入就地工作,请指定 out= 参数,如下所示:

In [26]: arr.round(decimals=3, out=arr)
Out[26]: array([-0.948, -1.615,  0.166, -0.535])

【讨论】:

    猜你喜欢
    • 2021-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多