如何将 Python 的 map 函数与 sklearn 的 preprocessing.scale 一起使用?

How do I use Python's map function with sklearn's preprocessing.scale?

我正在尝试对数据列表使用函数 (preprocessing.scale)。我是 Python 中 mapreduce/parallelism 的新手 - 我想在大量数据上处理它以提高性能。

示例:

X = [1,2,3,4]

使用语法:

list(map(preprocessing.scale, X))

我收到这个错误:

TypeError: Singleton array array(1.0) cannot be considered a valid collection.

我认为这是因为函数的 return 类型,但我不确定如何解决这个问题。任何帮助将不胜感激!

您不会need/want像在幕后那样for loop使用地图功能。

几乎所有 sklearn 方法都是矢量化的,它们接受类似列表的对象(列表、numpy 数组等),与 map(...) 方法相比,这种方法的工作速度要快得多

演示:

In [121]: from sklearn.preprocessing import scale

In [122]: X = [1,2,3,4]

In [123]: scale(X)
Out[123]: array([-1.34164079, -0.4472136 ,  0.4472136 ,  1.34164079])

使用 numpy 数组的相同演示:

In [39]: x = np.array(X)

In [40]: x
Out[40]: array([1, 2, 3, 4])

In [41]: scale(x)
DataConversionWarning: Data with input dtype int32 was converted to float64 by the scale function.
  warnings.warn(msg, _DataConversionWarning)
Out[41]: array([-1.34164079, -0.4472136 ,  0.4472136 ,  1.34164079])

它需要 float dtype,因此我们可以轻松地将 numpy 数组动态转换为 float dtype:

In [42]: scale(x.astype('float64'))
Out[42]: array([-1.34164079, -0.4472136 ,  0.4472136 ,  1.34164079])

执行list(map(preprocessing.scale, X))等同于执行[preprocessing.scale(a) for a in X]

鉴于此,您目前正在做的是缩放一个单例(一次观察)。您不能缩放单个项目,这就是功能中断的地方。尝试做 preprocessing.scale(X[0]) 你会得到同样的错误。

您尝试 运行 而不仅仅是传递数组 X preprocessing.scale(X) 的目的是什么?