Now, you can analyze the pricing per unit based on their bushel measurement. If you print out the data one more time, you can see how it's standardized.
✅ Did you notice that pumpkins sold by the half-bushel are very expensive? Can you figure out why? Hint: little pumpkins are way pricier than big ones, probably because there are so many more of them per bushel, given the unused space taken by one big hollow pie pumpkin.
## Visualization Strategies
Part of the data scientist's role is to demonstrate the quality and nature of the data they are working with. To do this, they often create interesting visualizations, or plots, graphs, and charts, showing different aspects of data. In this way, they are able to visually show relationships and gaps that are otherwise hard to uncover. Visualizations can also help determine the machine learning technique most appropriate for the data. A scatterplot that seems to follow a line, for example, indicates that the data is a good candidate for a linear regression exercise.
So far you have explored what regression is with sample data gathered from the pumpkin pricing dataset that we will use throughout this unit. You have also visualized it using Matplotlib. Now you are ready to dive deeper into regression for ML. In this lesson, you will learn more about two types of regression: basic linear regression and polynomial regression, along with some of the math underlying these techniques.
So far, you have explored what regression is with sample data gathered from the pumpkin pricing dataset that we will use throughout this lesson. You have also visualized it using Matplotlib.
Now you are ready to dive deeper into regression for ML. In this lesson, you will learn more about two types of regression: _basic linear regression_ and _polynomial regression_, along with some of the math underlying these techniques.
> Throughout this curriculum, we assume minimal knowledge of math, and seek to make it accessible for students coming from other fields, so watch for notes, callouts, diagrams, and other learning tools to aid in comprehension.
### Prerequisite
You should be familiar by now with the structure of the pumpkin data that we are examining. You can find it preloaded and pre-cleaned in this lesson's notebook.ipynb files, with the pumpkin price displayed per bushel in a new dataframe. Make sure you can run these notebooks in kernels in VS Code.
### Preparation
## Prerequisite
You should be familiar by now, with the structure of the pumpkin data that we are examining. You can find it preloaded and pre-cleaned in this lesson's _notebook.ipynb_ file. In the file, the pumpkin price is displayed per bushel in a new dataframe. Make sure you can run these notebooks in kernels in Visual Studio Code.
## Preparation
As a reminder, you are loading this data so to ask questions of it, questions like:
- When is the best time to buy pumpkins?
- What price can I expect of a case of miniature pumpkins?
- Should I buy them in half-bushel baskets or by the 1 1/9 bushel box?
Let's keep digging into this data.
### Limitations of the previous lesson
As a reminder, you are loading this data so as to ask questions of it. When is the best time to buy pumpkins? What price can I expect of a case of miniature pumpkins? Should I buy them in half-bushel baskets or by the 1 1/9 bushel box? Let's keep digging into this data.
In the previous lesson, you created a Pandas data frame and populated it with part of the original dataset, standardizing the pricing by the bushel. By doing that, however, you were _only_ able to gather about 400 data points and only for the fall months.
In the previous lesson, you created a Pandas dataframe and populated it with part of the original dataset, standardizing the pricing by the bushel. By doing that, however, you were only able to gather about 400 datapoints and only for the fall months.
✅ Take a look at the data that we preloaded in this lesson's accompanying notebook _notebook.ipynb_. The data is preloaded and an initial scatter plot is charted to show month data. Maybe we can get a little more detail about the nature of the data by cleaning it more.
Take a look at the data that we preloaded in this lesson's accompanying notebook. The data is preloaded and an initial scatterplot is charted to show month data. Maybe we can get a little more detail about the nature of the data by cleaning it more.
## A Linear Regression Line
As you learned in Lesson 1, the goal of a linear regression exercise is to be able to plot a line to show the relationship between variables and make accurate predictions on where a new datapoint would fall in relationship to that line.
> **🧮 Show me the math**
>
> This line has an equation: `Y = a + bX`. It is typical of **Least-Squares Regression** to draw this type of line.
>
> `X` is the 'explanatory variable'. `Y` is the 'dependent variable'. The slope of the line is `b` and `a` is the y-intercept, which refers to the value of `Y` when `X = 0`.
>
> In other words, and referring to our pumpkin data's original question: "predict the price of a pumpkin per bushel by month", `X` would refer to the price and `Y` would refer to the month of sale. The math that calculates the line must demonstrate the slope of the line, which is also dependent on the intercept, or where `Y` is situated when `X = 0`.
>
> You can observe the method of calculation for these values on the [Math is Fun](https://www.mathsisfun.com/data/least-squares-regression.html) web site.
>
> A common method of regression is **Least-Squares Regression** which means that all the datapoints surrounding the regression line are squared and then added up. Ideally, that final sum is as small as possible, because we want a low number of errors, or `least-squares`. We do so since we want to model a line that has the least cumulative distance from all of our data points. We also square the terms before adding them since we are concerned with its magnitude rather than its direction.
>
> One more term to understand is the **Correlation Coefficient** between given X and Y variables. For a scatterplot, you can quickly visualize this coefficient. A plot with datapoints scattered in a neat line have high correlation, but a plot with datapoints scattered everywhere between X and Y have a low correlation.
>
> A good linear regression model will be one that has a high (nearer to 1 than 0) Correlation Coefficient using the Least-Squares Regression method with a line of regression.
As you learned in Lesson 1, the goal of a linear regression exercise is to be able to plot a line to:
✅ Run the notebook accompanying this lesson and look at the City to Price scatterplot. Does the data associating City to Price for pumpkin sales seem to have high or low correlation, according to your visual interpretation of the scatterplot?
## Create a Linear Regression Model correlating Pumpkin Datapoints
- **Variable relationship**. Show the relationship between variables.
- **Make preditions**. Make accurate predictions on where a new data point would fall in relationship to that line.
Now that you have an understanding of the math behind this exercise, create a Regression model to see if you can predict which package of pumpkins will have the best pumpkin prices. Someone buying pumpkins for a holiday pumpkin patch might want this information to be able to optimize their purchases of pumpkin packages for the patch.
### Understand the math
Since you'll use Scikit-Learn, there's no reason to do this by hand (although you could!). In the main data-processing block of your lesson notebook, add a library from Scikit-Learn to automatically convert all string data to numbers:
If you look at the new_pumpkins dataframe now, you see that all the strings are now numeric. This makes it harder for you to read but much more intelligible for Scikit-Learn!
It is typical of **Least-Squares Regression** to draw this type of line.
Now you can make more educated decisions (not just based on eyeballing a scatterplot) about the data that is best suited to regression.
`X` is the 'explanatory variable'. `Y` is the 'dependent variable'.
Try to find a good correlation between two points of your data to potentially build a good predictive model. As it turns out, there's only weak correlation between the City and Price:
The slope of the line is `b` and `a` is the y-intercept (where the line intersects with the Y-axis), which refers to the value of `Y` when `X = 0`.
In other words, and referring to our pumpkin data's original question: _predict the price of a pumpkin per bushel by month_:
However there's a bit better correlation between the Package and its Price. That makes sense, right? Normally, the bigger the produce box, the higher the price.
The math that calculates the line must demonstrate the slope of the line, which is also dependent on the intercept, or where `Y` is situated when `X = 0`.
A good question to ask of this data will be: 'What price can I expect of a given pumpkin package?'
✅ You can observe the method of calculation for these values on the [Math is Fun](https://www.mathsisfun.com/data/least-squares-regression.html) web site.
Let's build this regression model
## Building A Linear Model
### Least-squares regression
Before building your model, do one more tidy-up of your data. Drop any null data and check once more what the data looks like.
A common method of regression is **Least-Squares Regression**. Which means that all the data points, surrounding the regression line, are _squared_ and then added up.
```python
new_pumpkins.dropna(inplace=True)
new_pumpkins.info()
```
Ideally, that final sum is as small as possible, because we want a low number of errors, or _least-squares_.
Then, create a new dataframe from this minimal set and print it out:
We want to model a line that has the least cumulative distance from all of our data points. We also square the terms before adding them since we are concerned with its magnitude rather than its direction.
```python
new_columns = ['Package', 'Price']
lin_pumpkins = new_pumpkins.drop([c for c in new_pumpkins.columns if c not in new_columns], axis='columns')
### Correlation coefficent
lin_pumpkins
One more term to understand is the **Correlation Coefficient** between given `X` and `Y` variables.
```
For a scatter plot, you can quickly visualize this coefficient.
Now you can assign your X and y coordinate data:
- **High correlation**. A plot with data points scattered in a neat line have high correlation.
- **Low correlation**. A plot with data points scattered everywhere between X and Y have a low correlation.
```python
X = lin_pumpkins.values[:, :1]
y = lin_pumpkins.values[:, 1:2]
```
> What's going on here? You're using [Python slice notation](https://stackoverflow.com/questions/509211/understanding-slice-notation/509295#509295) to create arrays to populate `X` and `y`.
> A good linear regression model will be one that has a high (nearer to 1 than 0) Correlation Coefficient using the Least-Squares Regression method with a line of regression.
Next, start the regression model-building routines:
✅ Run the notebook accompanying this lesson and look at the City to Price scatter plot. Does the data associating City to Price for pumpkin sales seem to have high or low correlation, according to your visual interpretation of the scatter plot?
```python
from sklearn.linear_model import LinearRegression
from sklearn.metrics import r2_score, mean_squared_error, mean_absolute_error
from sklearn.model_selection import train_test_split
## Exercise - create a Linear Regression Model correlating Pumpkin data points
Now that you have an understanding of the math behind this exercise the next step is create a Regression model to see if you can predict _which package of pumpkins will have the best pumpkin prices_.
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
lin_reg = LinearRegression()
lin_reg.fit(X_train,y_train)
✅ Someone buying pumpkins for a holiday pumpkin patch might want this information to be able to optimize their purchases of pumpkin packages for the patch.
pred = lin_reg.predict(X_test)
Since you'll use Scikit-Learn, there's no reason to do this by hand (although you could!).
accuracy_score = lin_reg.score(X_train,y_train)
print('Model Accuracy: ', accuracy_score)
### Convert string data to numbers
```
In the main data-processing block of your lesson notebook, add a library from Scikit-Learn to automatically convert all string data to numbers.
Because the correlation isn't particularly good, the model produced isn't terribly accurate.
You can visualize the line that's drawn in the process:
If you look at the `new_pumpkins` dataframe now, you see that all the strings are now numeric. This makes it harder for you to read but much more intelligible for Scikit-Learn!
```python
plt.scatter(X_test, y_test, color='black')
plt.plot(X_test, pred, color='blue', linewidth=3)
### Find a good correlation
plt.xlabel('Package')
plt.ylabel('Price')
Now you can make more educated decisions (not just based on eyeballing a scatterplot) about the data that is best suited to regression.
plt.show()
```
![A scatterplot showing package to price relationship](./images/linear.png)
Try to find a good correlation between two points of your data to potentially build a good predictive model.
And you can test the model against a hypothetical variety:
1. Let's see what the correlation is between `City` and `Price` and by using the method `corr()`:
```python
lin_reg.predict( np.array([ [2.75] ]) )
```
The returned price for this mythological Variety is:
`> 0.6`, that's better than the last thing we tried. There's a bit better correlation between the `Package` and its `Price`. That makes sense, right? Normally, the bigger the produce box, the higher the price.
✅ A good question to ask of this data will be: _What price can I expect of a given pumpkin package?_
Let's build this regression model next.
## Exercise - building a linear model
Before building your model, do one more tidy-up of your data.
1. Drop any null data and check once more what the data looks like.
```python
new_pumpkins.dropna(inplace=True)
new_pumpkins.info()
```
1. Then, create a new dataframe from this minimal set and print it out:
```python
new_columns = ['Package', 'Price']
lin_pumpkins = new_pumpkins.drop([c for c in new_pumpkins.columns if c not in new_columns], axis='columns')
lin_pumpkins
```
1. Now you can assign your X and y coordinate data:
That number makes sense, if the logic of the regression line holds true.
```python
X = lin_pumpkins.values[:, :1]
y = lin_pumpkins.values[:, 1:2]
```
> What's going on here? You're using [Python slice notation](https://stackoverflow.com/questions/509211/understanding-slice-notation/509295#509295) to create arrays to populate `X` and `y`.
1. Next, start the regression model-building routines:
```python
from sklearn.linear_model import LinearRegression
from sklearn.metrics import r2_score, mean_squared_error, mean_absolute_error
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
lin_reg = LinearRegression()
lin_reg.fit(X_train,y_train)
pred = lin_reg.predict(X_test)
accuracy_score = lin_reg.score(X_train,y_train)
print('Model Accuracy: ', accuracy_score)
```
Because the correlation isn't particularly good, the model produced isn't terribly accurate.
```output
Model Accuracy: 0.3315342327998987
```
1. To visualize the line that's drawn in the process:
```python
plt.scatter(X_test, y_test, color='black')
plt.plot(X_test, pred, color='blue', linewidth=3)
plt.xlabel('Package')
plt.ylabel('Price')
plt.show()
```
![A scatterplot showing package to price relationship](./images/linear.png)
1. Test the model against a hypothetical variety:
```python
lin_reg.predict( np.array([ [2.75] ]) )
```
The returned price for this mythological Variety is:
```output
array([[33.15655975]])
```
That number makes sense, if the logic of the regression line holds true.
Congratulations, you just created a model that can help predict the price of a few varieties of pumpkins. Your holiday pumpkin patch will be beautiful. But you can probably create a better model!
## Polynomial Regression
Another type of Linear Regression is Polynomial Regression. While sometimes there's a linear relationship between variables - the bigger the pumpkin in volume, the higher the price - sometimes these relationships can't be plotted as a plane or straight line.
Another type of Linear Regression is Polynomial Regression. While sometimes there's a linear relationship between variables - _the bigger the pumpkin in volume, the higher the price_. Sometimes these relationships can't be plotted as a plane or straight line.
✅ Here are [some more examples](https://online.stat.psu.edu/stat501/lesson/9/9.8) of data that could use Polynomial Regression
Take another look at the relationship between Variety to Price in the previous plot. Does this scatterplot seem like it should necessarily be analyzed by a straight line? Perhaps not. In this case, you can try Polynomial Regression.
Take another look at the relationship between `Variety` to `Price` in the previous plot. Does this scatterplot seem like it should necessarily be analyzed by a straight line? Perhaps not. In this case, you can try Polynomial Regression.
✅ Polynomials are mathematical expressions that might consist of one or more variables and coefficients
Polynomial regression creates a curved line to better fit nonlinear data. Let's recreate a dataframe populated with a segment of the original pumpkin data:
Polynomial regression creates a curved line to better fit nonlinear data.
poly_pumpkins = new_pumpkins.drop([c for c in new_pumpkins.columns if c not in new_columns], axis='columns')
poly_pumpkins
```
### Visualize in a chart
A good way to visualize the correlations between data in dataframes is to display it in a 'coolwarm' chart:
```python
corr = poly_pumpkins.corr()
corr.style.background_gradient(cmap='coolwarm')
```
1. Use the `Background_gradient()` method with `coolwarm` as argument value like so:
![A heatmap showing data correlation](./images/heatmap.png)
```python
corr = poly_pumpkins.corr()
corr.style.background_gradient(cmap='coolwarm')
```
Looking at this chart, you can visualize the good correlation between Package and Price. So you should be able to create a somewhat better model than the last one.
This code creates a heat map looking like so:
Build out the X and y columns:
![A heatmap showing data correlation](./images/heatmap.png)
```python
X=poly_pumpkins.iloc[:,3:4].values
y=poly_pumpkins.iloc[:,4:5].values
```
Looking at this chart, you can visualize the good correlation between `Package` and `Price`. So you should be able to create a somewhat better model than the last one.
### Create a pipeline
Scikit-Learn includes a helpful API for building polynomial regression models - the `make_pipeline` [API](https://scikit-learn.org/stable/modules/generated/sklearn.pipeline.make_pipeline.html?highlight=pipeline#sklearn.pipeline.make_pipeline). A 'pipeline' is created which is a chain of estimators. In this case, the pipeline includes Polynomial Features, or predictions that form a nonlinear path.
```python
from sklearn.preprocessing import PolynomialFeatures
![A polynomial plot showing package to price relationship](./images/polynomial.png)
You created a new data frame by calling `pd.DataFrame`. Furthermore you sorted the values by a call to `sort_values()`. Thereafter you created a polynomial plot that ended up looking like so:
You can see a curved line that fits your data better. Let's check the model's accuracy:
![A polynomial plot showing package to price relationship](./images/polynomial.png)
```python
accuracy_score = pipeline.score(X_train,y_train)
print('Model Accuracy: ', accuracy_score)
```
And voila!
```
Model Accuracy: 0.8537946517073784
```
That's better! Try to predict a price:
You can see a curved line that fits your data better.
```python
pipeline.predict( np.array([ [2.75] ]) )
```
You are given this prediction:
1. Let's check the model's accuracy by calling `score()`:
```
array([[46.34509342]])
```
It does make sense! And, if this is a better model than the previous one, looking at the same data, you need to budget for these more expensive pumpkins!
```python
accuracy_score = pipeline.score(X_train,y_train)
print('Model Accuracy: ', accuracy_score)
```
And voila!
```output
Model Accuracy: 0.8537946517073784
```
🏆 Well done! You created two Regression models in one lesson. In the final section on Regression, you will learn about Logistic Regression to determine categories.
That's better! Try to predict a price:
### Do a prediction
Let's see where we are, can we input a new value and get a prediction?
1. Call `predict()` to make a prediction:
```python
pipeline.predict( np.array([ [2.75] ]) )
```
You are given this prediction:
```output
array([[46.34509342]])
```
It does make sense, if you compare it to the polynomial plot! And, if this is a better model than the previous one, looking at the same data, you need to budget for these more expensive pumpkins!
🏆 Well done! You created two Regression models in one lesson. In the final section on Regression, you will learn about Logistic Regression to determine categories.
---
## 🚀Challenge
Test several different variables in this notebook to see how correlation corresponds to model accuracy.