Linear RegressionCode with Python
Now that you understand the concepts, let's see how this looks in Python! We will use a popular toolkit called scikit-learn, which handles all the heavy math (like Gradient Descent) for us behind the scenes.
Let's write a program to predict Ice Cream Sales based on the Temperature outside.
1. The Setup
First, we need to bring in our machine learning tools and set up our data. Think of this like taking your toolkit out of the garage.
from sklearn.linear_model import LinearRegression
# X is our Temperature (the feature we know)
X = [[60], [70], [80], [90]]
# y is our Ice Cream Sales (the target we want to predict)
y = [100, 150, 200, 250]Notice that X is a list of lists. The machine learning model expects features to be grouped together, because we could have multiple features (like temperature and humidity), though here we just have one. y is simply a flat list of our target numbers.
2. Creating the Model
Before we can train anything, we need an "empty" model. It is like buying a blank notebook before you start taking notes.
model = LinearRegression()3. Training the Model
This is where the magic happens! We tell the computer to look at our data and find the best line. In machine learning terminology, this is called fitting the model.
model.fit(X, y)By running this single line of code, the computer just did all the calculus and gradient descent we talked about earlier to find the perfect coefficients!
4. Reading the Coefficients
Let's see what the computer learned. We can ask our model for its calculated Slope (the coefficient) and the Intercept.
print("Slope:", model.coef_)
print("Intercept:", model.intercept_)If it prints a slope of 5, that means for every 1 degree warmer it gets, our model expects us to sell 5 more ice creams!
5. Predicting the Future
Now for the best part. Let's use our trained model to predict our sales for a brand new day that is 85 degrees outside.
new_temp = [[85]]
prediction = model.predict(new_temp)
print("Predicted sales:", prediction)And just like that, you have written your first machine learning code!
Thanks for reading.