Skip to main content
 首页 » 编程设计

python之我找不到一种方法来使用 sklearn pandas 中数据框中的数据来避免值错误

2025年04月02日12softidea

我正在尝试对数值数据( float )运行一些基本的机器学习算法,但在读取数据时遇到问题。我使用 python 2.7、sklearn、pandas,并通过 jupyter(ipython notebook)工作。作为第一步,我尝试使用基本的随机森林搜索,但是在使用这些函数时,我不断收到 ValueError。

数据被读入数据框

df = pd.read_table("p12.dat", delim_whitespace=True) 

screenshot of data

df.dtypes 显示所有感兴趣的值都是 float64。

使用基本表达式:

def classification_model(model, data, predictors, outcome): 
  model.fit(data[predictors],data[outcome]) 
  predictions = model.predict(data[predictors]) 
  accuracy = metrics.accuracy_score(predictions,data[outcome]) 
  print "Accuracy : %s" % "{0:.3%}".format(accuracy) 
  print "Cross-Validation Score : %s" % "{0:.3%}".format(np.mean(error)) 
  model.fit(data[predictors],data[outcome])  

然后设置变量并执行:

outcome_var = 'ki' 
predictor_var = ['Etot','TSs','Eww-nbr'] 
model = RandomForestClassifier(n_estimators=100) 
classification_model(model, df,predictor_var,outcome_var) 

错误是:

ValueError                                Traceback (most recent call last) 
<ipython-input-9-7dd611cce611> in <module>() 
----> 1 classification_model(model, df,predictor_var,outcome_var) 
 
<ipython-input-8-956e572db2f4> in classification_model(model, data, predictors, outcome) 
      1 def classification_model(model, data, predictors, outcome): 
      2   #Fit the model: 
----> 3   model.fit(data[predictors],data[outcome].values) 
      4  
      5   #Make predictions on training set: 
 
/Users/jonathangough/anaconda/lib/python2.7/site-packages/sklearn/ensemble/forest.pyc in fit(self, X, y, sample_weight) 
    233         self.n_outputs_ = y.shape[1] 
    234  
--> 235         y, expanded_class_weight = self._validate_y_class_weight(y) 
    236  
    237         if getattr(y, "dtype", None) != DOUBLE or not y.flags.contiguous: 
 
/Users/jonathangough/anaconda/lib/python2.7/site-packages/sklearn/ensemble/forest.pyc in _validate_y_class_weight(self, y) 
    419  
    420     def _validate_y_class_weight(self, y): 
--> 421         check_classification_targets(y) 
    422  
    423         y = np.copy(y) 
 
/Users/jonathangough/anaconda/lib/python2.7/site-packages/sklearn/utils/multiclass.pyc in check_classification_targets(y) 
    171     if y_type not in ['binary', 'multiclass', 'multiclass-multioutput',  
    172             'multilabel-indicator', 'multilabel-sequences']: 
--> 173         raise ValueError("Unknown label type: %r" % y) 
    174  
    175  
 
ValueError: Unknown label type: array([[  2.72000000e+00], 
       [  4.60000000e+00], 
       [  6.70000000e+00], 
       [  2.30000000e+00], 
       [  1.70000000e+00], 
       [  2.20000000e+00], 
       [  3.60000000e+00], 
       [  9.10000000e+00], 

我进行了搜索和谷歌搜索,但我不知道该怎么做。我的理解是可以在随机森林算法中使用 float (所以我认为这不是错误)。

如有任何见解,我们将不胜感激。

请您参考如下方法:

在 scikit-learn 中,分类器预测一个离散变量,即目标变量的数据类型必须是整数或字符串。如果您尝试对连续变量建模,则必须使用“回归器”模型,在您的情况下,等效模型是 RandomForestRegresser。