Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Julia Linear Regression

Tags:

julia

I was trying to fit a linear regression in Julia. I have a data frame with 10 columns. The first 9 columns are the predictors I call it X and the last column is the response variable I call it Y

I typed linreg(X, Y) But I get an error message saying linreg has no method matching DataFrame and DataArray Float.

I was wondering how I could fix the issue. I was thinking of converting X to a data Array

I tried convert(X, Array) But that threw an error as well: 'Convert has no method matching convert' Does anyone have any suggestions

like image 888
user3453272 Avatar asked Mar 15 '15 01:03

user3453272


3 Answers

If you already have your data in a DataFrame, you should take a look at the GLM.jl package.

Specifically the lm function should do what you want and feel very familiar if you are an R user.

If you post more code (maybe which columns in your DataFrame store X and Y) we could help you further.

like image 163
spencerlyon2 Avatar answered Dec 22 '22 10:12

spencerlyon2


update: have to use dot operator in Julia 1.0 while performing scalar addition on arrays. i.e. y = m*x .+ b

You can also do linear regression using simple linear algebra. Here is an example:

# Linear Algebra style
# For single linear regresion y= mx .+ b
m = 3.3; b = 2; x = rand(100,1)
y = m * x .+ b
# add noise
yn= y + randn(size(y)) * 0.5

# regression
X = zeros(100,2); X[:,1] = x;  X[:,2] = 1.0
coeff_pred = X\yn

slope =  round(coeff_pred[1], 2)
intercept = round(coeff_pred[2], 2)

println("The real slope is $m, and the predicted slope is $slope")
println("The real intercept is $b, and the predicted slope is $intercept")
like image 36
Julio Cárdenas-Rodríguez Avatar answered Dec 22 '22 12:12

Julio Cárdenas-Rodríguez


You are just using convert wrong. The correct syntax is convert(T, x) it reads: convert x to a value of type T.

so basically you need to do:

linreg(convert(Array,X),convert(Array,Y))

and it should work.

like image 24
epx Avatar answered Dec 22 '22 10:12

epx