python - 如果您的数据具有单个特征,则使用 array.reshape(-1, 1) 重塑您的数据,如果它包含单个样本,则使用 array.reshape(1, -1)
问题描述
虽然我从我的数据中预测一个样本,但它给出了重塑错误,但我的模型有相同的行数,什么是问题家伙,发现了类似的问题,但不同的原因无法解释。
import pandas as pd
from sklearn.linear_model import LinearRegression
import numpy as np
x = np.array([2.0 , 2.4, 1.5, 3.5, 3.5, 3.5, 3.5, 3.7, 3.7])
y = np.array([196, 221, 136, 255, 244, 230, 232, 255, 267])
lr = LinearRegression()
lr.fit(x,y)
print(lr.predict(2.4))
错误是
“如果它包含单个样本。”.format(array)) ValueError:预期的二维数组,得到标量数组:array=2.4。如果您的数据具有单个特征,则使用 array.reshape(-1, 1) 重塑您的数据,如果它包含单个样本,则使用 array.reshape(1, -1) 。
解决方案
您应该将您的 X 重塑为 2D 数组而不是 1D 数组。拟合模型需要一个二维数组。i.e (n_samples, n_features)
x = np.array([2.0 , 2.4, 1.5, 3.5, 3.5, 3.5, 3.5, 3.7, 3.7])
y = np.array([196, 221, 136, 255, 244, 230, 232, 255, 267])
lr = LinearRegression()
lr.fit(x.reshape(-1, 1), y)
print(lr.predict([[2.4]]))
推荐阅读
- node.js - 无法从主机(osx)访问 docker 容器
- google-apps-script - 用于谷歌文档中条件格式表格单元格的谷歌应用脚本
- c++ - 链接 cURL lib 但 cURL 目录中没有 lib 文件
- python - 如何使用 django 将 html 表单变量传递给 python 函数
- visual-studio - 构建和部署与其他应用程序在一个解决方案中的 ASP.NET MVC 应用程序
- haskell - 哪些图表后端支持动画?
- c# - MSBuild 无法正确构建 Windows CE 项目,而 devenv 确实如此
- python - 将字符串转换为 utf-16
- sql-server - 为什么有这么多内存授权?
- twitter-bootstrap-3 - 在角度 6 中使用引导程序 3