在Python中使用切片

时间:2016-08-29 16:55:14

标签: python pandas scikit-learn slice prediction

我使用UCI repo中的数据集:http://archive.ics.uci.edu/ml/datasets/Energy+efficiency 然后做下一步:

from pandas import *
from sklearn.neighbors import KNeighborsRegressor
from sklearn.linear_model import LinearRegression, LogisticRegression
from sklearn.svm import SVR
from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import r2_score
from sklearn.cross_validation import train_test_split

dataset = read_excel('/Users/Half_Pint_boy/Desktop/ENB2012_data.xlsx')
dataset = dataset.drop(['X1','X4'], axis=1)
trg = dataset[['Y1','Y2']]
trn = dataset.drop(['Y1','Y2'], axis=1)

然后做模型并交叉验证:

models = [LinearRegression(), 
      RandomForestRegressor(n_estimators=100, max_features ='sqrt'), 
      KNeighborsRegressor(n_neighbors=6),
      SVR(kernel='linear'), 
      LogisticRegression() 
     ]
Xtrn, Xtest, Ytrn, Ytest = train_test_split(trn, trg, test_size=0.4)

我正在创建一个用于预测值的回归模型但存在问题。这是代码:

TestModels = DataFrame()
tmp = {}

for model in models:

    m = str(model)
    tmp['Model'] = m[:m.index('(')]    

for i in range(Ytrn.shape[1]):
    model.fit(Xtrn, Ytrn[:,i]) 
    tmp[str(i+1)] = r2_score(Ytest[:,0], model.predict(Xtest))
    TestModels = TestModels.append([tmp])
    TestModels.set_index('Model', inplace=True)

它显示了不可用的类型:line model.fit的'slice'(Xtrn,Ytrn [:,i])

如何避免并使其有效?

谢谢!

1 个答案:

答案 0 :(得分:1)

我认为之前我遇到过类似的问题!尝试将数据转换为numpy数组,然后再将它们提供给sklearn估算器。它最有可能解决哈希问题。例如,您可以这样做:

Xtrn_array = Xtrn.as_matrix() 
Ytrn_array = Ytrn.as_matrix()

并在将数据拟合到估算器时使用Xtrn_array和Ytrn_array。