【问题标题】:Convert numpy array type and values from Float64 to Float32将 numpy 数组类型和值从 Float64 转换为 Float32
【发布时间】:2018-02-07 20:37:36
【问题描述】:

我正在尝试将类型从 Float64 转换为 Float32 的阈值数组(来自 scikit learn 的隔离林的泡菜文件)

for i in range(len(tree.tree_.threshold)):
    tree.tree_.threshold[i] = tree.tree_.threshold[i].astype(np.float32)

​ 然后打印出来

for value in tree.tree_.threshold[:5]:
    print(type(value))
    print(value)

我得到的输出是:

<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

我没有正确转换为 Float32。我想将值及其类型转换为 Float32,有人有解决方法吗?

【问题讨论】:

  • 不,没有缺失值,最大值为526225.98822
  • 你能给我们打印 tree.tree_.threshold.flags
  • C_CONTIGUOUS : False F_CONTIGUOUS : False OWNDATA : False WRITEABLE : True ALIGNED : True UPDATEIFCOPY : False

标签: python numpy scikit-learn pickle


【解决方案1】:

问题是您没有对 numpy 数组进行任何类型转换。您计算一个 float32 变量并将其作为一个条目放入 float64 numpy 数组中。 numpy 然后将其正确转换回 float64

试试这样的:

a = np.zeros(4,dtype="float64") 
print a.dtype
print type(a[0])
a = np.float32(a)
print a.dtype
print type(a[0])

输出(使用 python 2.7 测试)

float64
<type 'numpy.float64'>
float32
<type 'numpy.float32'>

a 在你的情况下是数组 tree.tree_.threshold

【讨论】:

  • 你能解释一下np.zeroes参数,特别是“4”
  • 这是创建一个 numpy 数组的快速方法,该数组充满了一些东西......这里是零。 4 只是零的数量。我选择 4 因为我喜欢这个数字...
  • ------------------------------------------ --------------------------------- AttributeError Traceback(最近一次调用)() ----> 1 tree.tree_.threshold = np.zeros(4,dtype="float64") 2 print (tree.tree_.threshold.dtype) 3 tree.tree_.threshold= float32( tree.tree_.threshold) 4 print (a.dtype) AttributeError: 'sklearn.tree._tree.Tree' 对象的属性 'threshold' 不可写
  • 得到同样的错误:AttributeError Traceback(最近一次调用最后) in () ----> 1 tree.tree_.threshold = np.zeros (4,dtype="float64") 2 打印 (tree.tree_.threshold.dtype) 3 打印 (tree.tree_.threshold[0].dtype) 4 tree.tree_.threshold= float32(a) 5 打印 (tree. tree_.threshold.dtype) AttributeError: 'sklearn.tree._tree.Tree' 对象的属性 'threshold' 不可写
  • 好吧,如果它不是一个可写对象,你就不能覆盖它。因此该解决方案将不起作用。它仅在您使用可能不想要的新 numpy 数组时才有效。
【解决方案2】:

你可以试试这个:

tree.tree_.threshold[i]=tree.tree_.threshold[i].astype('float32',casting='same_kind’)

【讨论】:

    【解决方案3】:

    其实我很努力,但做不到 'sklearn.tree._tree.Tree' 对象不可写。

    在生成 PMML 文件时会导致精度问题,所以我 在那里提出了一个错误,他们为此提供了更新的解决方案 不在内部将其转换为 Float64。

    有关更多信息,您可以点击此链接: Precision Issue

    【讨论】:

      猜你喜欢
      • 2016-11-16
      • 1970-01-01
      • 2019-05-21
      • 2023-03-11
      • 2018-01-30
      • 1970-01-01
      • 2016-05-15
      • 2015-12-12
      • 2016-06-14
      相关资源
      最近更新 更多