【问题标题】:In Scikit, How Do You Fix Value Error When Predicting?在 Scikit 中,您如何在预测时修复值错误?
【发布时间】:2016-08-25 07:15:52
【问题描述】:

以下代码给了我以下错误: ValueError: Found array with 0 sample(s) (shape=(0, 3)) 而至少需要 1 个。

错误是在调用预测的行中产生的。我假设数据框的形状“obs_to_pred”有问题。我检查了形状,即 (1046, 3)。

你有什么建议让我可以解决这个问题并运行预测?

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import statsmodels.api as sm

from patsy import dmatrices
from sklearn.linear_model import LogisticRegression
import scipy.stats as stats
from sklearn import linear_model

# Import Titanic Data
train_loc = 'C:/Users/Young/Desktop/Kaggle/Titanic/train.csv'
test_loc = 'C:/Users/Young/Desktop/Kaggle/Titanic/test.csv'
train = pd.read_csv(train_loc)
test = pd.read_csv(test_loc)

# Predict Missing Age Values Based on Factors Pclass, SibSp, and Parch.
# In the function, combine train and test data.
def regressionPred (traindata,testdata):

    allobs = pd.concat([traindata, testdata])
    allobs = allobs[~allobs.Age.isnull()]
    y = allobs.Age

    y, X = dmatrices('y ~ Pclass + SibSp + Parch', data = allobs, return_type = 'dataframe')
    mod = sm.OLS(y,X)
    res = mod.fit()

    predictors = ['Pclass', 'SibSp', 'Parch']
    regr = linear_model.LinearRegression()
    regr.fit(allobs.ix[:,predictors], y)

    obs_to_pred = allobs[allobs.Age.isnull()].ix[:,predictors]
    prediction = regr.predict( obs_to_pred ) # Error Produced in This Line ***

    return res.summary(), prediction

regressionPred(train,test)

如果您可能想查看数据集,链接将带您前往:https://www.kaggle.com/c/titanic/data

【问题讨论】:

    标签: python numpy pandas scikit-learn


    【解决方案1】:

    排队

    allobs = allobs[~allobs.Age.isnull()]
    

    您将allobs 定义为Age 列中没有NaN 的所有情况。

    后来,用:

    obs_to_pred = allobs[allobs.Age.isnull()].ix[:,predictors]
    

    您没有任何情况可以预测,因为所有 allobs.Age.isnull() 都将被评估为 False,您将得到一个空的 obs_to_pred。因此你的错误:

    包含 0 个样本的数组(形状=(0, 3)),而至少需要 1 个。

    用你的预测检查你想要的逻辑。

    【讨论】:

      猜你喜欢
      • 2019-06-07
      • 2018-01-09
      • 2023-03-03
      • 2017-08-07
      • 2022-08-14
      • 1970-01-01
      • 2021-03-25
      • 2021-01-11
      • 1970-01-01
      相关资源
      最近更新 更多