Using slices in Python

2024/10/12 23:24:07

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_splitdataset = 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!

Answer

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://en.xdnf.cn/q/118146.html

Related Q&A

Elasticsearch delete_by_query wrong usage

I am using 2 similar ES methods to load and delete documents:result = es.search(index=users_favourite_documents,doc_type=favourite_document,body={"query": {"match": {user: user}}})A…

SQLAlchemy: Lost connection to MySQL server during query

There are a couple of related questions regarding this, but in my case, all those solutions is not working out. Thats why I thought of asking again. I am getting this error while I am firing below quer…

row to columns while keeping part of dataframe, display on same row

I am trying to move some of my rows and make the them columns, but keep a large portion of the dataframe the same.Resulting Dataframe:ID Thing Level1 Level2 Time OAttribute IsTrue Score Value 1 …

SQLAlchemy InvalidRequestError when using composite foreign keys

My table relationships in SQLAlchemy have gotten quite complex, and now Im stuck at this error no matter how I configure my relationship.Im a bit new to SQLAlchemy so Im not sure what Im doing wrong, b…

google search by google api in r or python

I want to search some thing (ex:"python language") in google by python or R and it will give me the list of links for that google search like:https://en.wikipedia.org/wiki/Python_(programming…

NumPy Wont Append Arrays

Im currently working on a neural network to play Rock-Paper-Scissors, but Ive run into an enormous issue.Im having the neural network predict what will happen next based on a history of three moves, wh…

(Django) Limited ForeignKey choices by Current User in UpdateView

I recently was able to figure out how to do this in the CreateView, but the same is not working for the UpdateView (Heres the original post on how to do it in the CreateView: (Django) Limited ForeignKe…

Merge list concating unique values as comma seperated retaining original order from csv

Here is my data:data.csvid,fname,lname,education,gradyear,attributes 1,john,smith,mit,2003,qa 1,john,smith,harvard,207,admin 1,john,smith,ft,212,master 2,john,doe,htw,2000,devHere is the code:from iter…

Unable to submit Spark job from Windows IDE to Linux cluster

I just read about findspark and found it quite interesting, as so far I have only used spark-submit which isnt be suited for interactive development on an IDE. I tried executing this file on Windows 10…

Updating variable values when running a thread using QThread in PyQt4

So problem occurred when I tried using Threading in my code. What I want to do is passing default values to the def __init__ and then calling the thread with its instance with updated values but someho…