Using slices in Python

安稳与你 提交于 2019-12-25 08:14:46

问题


I use the dataset from UCI repo: http://archive.ics.uci.edu/ml/datasets/Energy+efficiency Then doing next:

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)

Then do the models and cross validate:

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)

I'm creating a regression model for predicting values but have a problems. Here is the code:

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)

It shows unhashable type: 'slice' for line model.fit(Xtrn, Ytrn[:,i])

How can it be avoided and made working?

Thanks!


回答1:


I think that I had a similar problem before! Try to convert your data to numpy arrays before feeding them to sklearn estimators. It most probably solve the hashing problem. For instance, You can do:

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

and use Xtrn_array and Ytrn_array when you fit your data to estimators.



来源:https://stackoverflow.com/questions/39211339/using-slices-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!