Python 将 numpy 数组类型和值从 Float64 转换为 Float32
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45955186/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert numpy array type and values from Float64 to Float32
提问by Akshay Tilekar
I am trying to convert threshold array(pickle file of isolation forest from scikit learn) of type from Float64 to Float32
我正在尝试将 Float64 类型的阈值数组(来自 scikit learn 的隔离森林的pickle 文件)转换为 Float32
for i in range(len(tree.tree_.threshold)):
tree.tree_.threshold[i] = tree.tree_.threshold[i].astype(np.float32)
? Then Printing it
? 然后打印
for value in tree.tree_.threshold[:5]:
print(type(value))
print(value)
the output i am getting is :
我得到的输出是:
<class 'numpy.float64'>
526226.0
<class 'numpy.float64'>
91.9514312744
<class 'numpy.float64'>
3.60330319405
<class 'numpy.float64'>
-2.0
<class 'numpy.float64'>
-2.0
I am not getting a proper conversion to Float32. I want to convert values and their type to Float32, Did anybody have any workaround this ?
我没有正确转换为 Float32。我想将值和它们的类型转换为 Float32,有人有任何解决方法吗?
采纳答案by Akshay Tilekar
Actually i tried hard but not able to do as the 'sklearn.tree._tree.Tree' objects is not writable.
It is causing a precision issue while generating a PMML file, so i raised a bug over there and they gave an updated solution for it by not converting it in to the Float64 internally.
实际上,我很努力但无法做到,因为 'sklearn.tree._tree.Tree' 对象不可写。
它在生成 PMML 文件时导致精度问题,所以我在那里提出了一个错误,他们通过不在内部将其转换为 Float64 来为它提供更新的解决方案。
For more info, you can follow this link: Precision Issue
有关更多信息,您可以点击此链接: Precision Issue
回答by Glostas
The problem is that you do not do any type conversion of the numpy array. You calculate a float32 variable and put it as an entry into a float64 numpy array. numpy then converts it properly back to float64
问题是您没有对 numpy 数组进行任何类型转换。您计算一个 float32 变量并将其作为一个条目放入一个 float64 numpy 数组中。numpy 然后将其正确转换回 float64
Try someting like this:
尝试这样的事情:
a = np.zeros(4,dtype="float64")
print a.dtype
print type(a[0])
a = np.float32(a)
print a.dtype
print type(a[0])
The output (tested with python 2.7)
输出(使用 python 2.7 测试)
float64
<type 'numpy.float64'>
float32
<type 'numpy.float32'>
a is in your case the array tree.tree_.threshold
a 在你的情况下是数组 tree.tree_.threshold
回答by Woody
You can try this:
你可以试试这个:
tree.tree_.threshold[i]=tree.tree_.threshold[i].astype('float32',casting='same_kind')