I am trying my hands on Linear Regression using the iris dataset available on Kaggle. The columns in this dataset are:
- Id
- SepalLengthCm
- SepalWidthCm
- PetalLengthCm
- PetalWidthCm
- Species
The species are categorized into 3 as the following plot illustrates.
Now I want to predict the Species
based on the input Sepal width
and Sepal length
.
The first thing I did was to transform the species name into numbers using the following:
transformSpecies <- function(species) {
transformed <- -1
if(species == 'Iris-virginica'){
transformed <- 1
}else if(species == 'Iris-versicolor') {
transformed <- 2
}else if(species == 'Iris-setosa') {
transformed <- 3
}else {
print('Failed to transform species ', species)
}
}
iris$transformedSpecies <- sapply(iris$Species, transformSpecies)
Then I constructed a linear model:
linearModel <- lm(transformedSpecies~SepalLengthCm + SepalWidthCm, iris)
The equation is same as:
y = c + M1X1 + M2X2
To find the coefficients, the above linear model was passed to the coef
function.
theta <- coef(linearModel)
Then I tried to make some predictions using predict
:
predict(linearModel, data.frame(SepalLengthCm = c(5,5.5,6,7.5,8.5),
SepalWidthCm = c(2,2.5,4.5,3.5,5)))
The results are as follows:
1 2 3 4 5
1.949183 1.899571 2.807600 1.062697 1.282687
Few questions:
- Is it the correct way to create a linear model when there is more than one predictor variable?
- How can I improve this linear model?
- What is the best way to handle response variables when they are not numeric, as the case here?