python - Linear Regression on Pandas DataFrame using Sci-kit Learn -
i'm new python , trying perform linear regression using sklearn on pandas dataframe. did:
data = pd.read_csv('xxxx.csv') after got dataframe of 2 columns, let's call them 'c1', 'c2'. want linear regression on set of (c1,c2) entered
x=data['c1'].values y=data['c2'].values linear_model.linearregression().fit(x,y) which resulted in following error
indexerror: tuple index out of range what's wrong here? also, i'd know
- visualize result
- make predictions based on result?
i've searched , browsed large number of sites none of them seemed instruct beginners on proper syntax. perhaps what's obvious experts not obvious novice myself.
can please help? thank time.
ps: have noticed large number of beginner questions down-voted in stackoverflow. kindly take account fact things seem obvious expert user may take beginner days figure out. please use discretion when pressing down arrow lest you'd harm vibrancy of discussion community.
let's assume csv looks like:
c1,c2 0.000000,0.968012 1.000000,2.712641 2.000000,11.958873 3.000000,10.889784 ... i generated data such:
import numpy np sklearn import datasets, linear_model import matplotlib.pyplot plt length = 10 x = np.arange(length, dtype=float).reshape((length, 1)) y = x + (np.random.rand(length)*10).reshape((length, 1)) this data saved test.csv (just know came from, you'll use own).
data = pd.read_csv('test.csv', index_col=false, header=0) x = data.c1.values y = data.c2.values print x # prints: [ 0. 1. 2. 3. 4. 5. 6. 7. 8. 9.] you need take @ shape of data feeding .fit().
here x.shape = (10,) need (10, 1), see sklearn. same goes y. reshape:
x = x.reshape(length, 1) y = y.reshape(length, 1) now create regression object , call fit():
regr = linear_model.linearregression() regr.fit(x, y) # plot in example @ http://scikit-learn.org/ plt.scatter(x, y, color='black') plt.plot(x, regr.predict(x), color='blue', linewidth=3) plt.xticks(()) plt.yticks(()) plt.show() see sklearn linear regression example. 
Comments
Post a Comment