Ami*_*ory 4 python numpy scikit-learn
我经常有两个numpy一维数组,x并且y,想用它们来执行一些快速sklearn配件+预测.
import numpy as np
from sklearn import linear_model
# This is an example for the 1d aspect - it's obtained from something else.
x = np.array([1, 3, 2, ...])
y = np.array([12, 32, 4, ...])
Run Code Online (Sandbox Code Playgroud)
现在我想做点什么
linear_model.LinearRegression().fit(x, y)...
Run Code Online (Sandbox Code Playgroud)
问题是它期望X一个二维列数组.出于这个原因,我通常喂它
x.reshape((len(x), 1))
Run Code Online (Sandbox Code Playgroud)
我觉得这很麻烦,难以阅读.
是否有一些更短的方法将1d数组转换为2d列数组(或者,sklearn可以接受1d数组)?
您可以切片阵列,创建新轴:
x[:, None]
Run Code Online (Sandbox Code Playgroud)
这个:
>>> x = np.arange(5)
>>> x[:, None]
array([[0],
[1],
[2],
[3],
[4]])
Run Code Online (Sandbox Code Playgroud)
相当于:
>>> x.reshape(len(x), 1)
array([[0],
[1],
[2],
[3],
[4]])
Run Code Online (Sandbox Code Playgroud)
如果您发现它更具可读性,则可以使用转置矩阵:
np.matrix(x).T
Run Code Online (Sandbox Code Playgroud)
如果你想要一个数组:
np.matrix(x).T.A
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2663 次 |
| 最近记录: |