美文网首页GIS之时空数据分析
Python LinearRegression 输入变量维度问题

Python LinearRegression 输入变量维度问题

作者: 王叽叽的小心情 | 来源:发表于2019-12-11 14:01 被阅读0次

    应用场景:Python sklearn LinearRegression 方法进行模型训练(可回归,可聚类)

    常出现问题:
    Exception: Data must be 1-dimensional
    ValueError: Expected 2D array, got 1D array instead
    Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample.

    核心:在采用sklearn包进行回归或者聚类分析时,默认训练的样本格式为二维数据,即样本数量和训练特征的二维向量。(这一点不同于其他的线性回归,输入数据是一维向量)

    解决方法;

    1. 根据提示,采用numpy中的reshape方法进行维度调整,如果是只有一个维度特征而含有多个样本,则有y = np.reshape(x, (-1,1)),如果是一个样本含有多个特征,则有y = np.reshape(x, (1,-1))。-1代表的是一维。具体步骤是:
      '''
      x = np.arange(5)
      x
      array([0, 1, 2, 3, 4])
      np.shape(x)
      (5,)
      y = np.reshape(x, (-1,1))
      y
      array([[0],
      [1],
      [2],
      [3],
      [4]])
      np.shape(y)
      (5, 1)
      '''
    2. 另外一种方法是采用numpy中的newaxis进行维度增加,该方法可以增加多个维度,具体应用方法是 y = x[:, np.newaxis] 即可得到维度为(5,1)的输入样本

    参考资料:
    https://docs.scipy.org/doc/numpy/reference/constants.html?highlight=newaxis#numpy.newaxis

    https://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html#numpy.reshape

    相关文章

      网友评论

        本文标题:Python LinearRegression 输入变量维度问题

        本文链接:https://www.haomeiwen.com/subject/wwrogctx.html