-
-
Notifications
You must be signed in to change notification settings - Fork 161
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Using quadratic linear regression #1840
- Loading branch information
1 parent
9e40069
commit 8a1f66c
Showing
1 changed file
with
52 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 1,52 @@ | ||
# Using quadratic linear regression | ||
|
||
### Quadratic regression can be achieved by using `PolynomialFeatures` to prepare dataset for polynomial form: | ||
|
||
```python | ||
from sklearn import preprocessing, linear_model | ||
import numpy as np | ||
|
||
data = np.array([[1, 1], [2, 4], [3, 9], [4, 15], [5, 21], [6, 36]]) | ||
X = np.array(data[:,0]).reshape(-1,1) | ||
y = data[:,1] | ||
|
||
poly = preprocessing.PolynomialFeatures(degree=2, include_bias=False) | ||
Xp = poly.fit_transform(X) | ||
|
||
model = linear_model.LinearRegression() | ||
model.fit(Xp, y) | ||
|
||
y_pred = model.predict(Xp) | ||
``` | ||
|
||
- `from sklearn import` - import module from [lib:scikit-learn](https://onelinerhub.com/python-scikit-learn/how-to-install-scikit-learn-using-pip) | ||
- `.PolynomialFeatures(` - create polynomial object to prepare our dataset for polynomial form | ||
- `poly.fit_transform(` - transform original dataset to polynomial form | ||
- `linear_model.LinearRegression` - initialize linear regression model | ||
- `.fit(` - train transformation model | ||
- `.predict(` - predict target variable based on given features dataset | ||
|
||
group: linear | ||
|
||
## Example: | ||
```python | ||
from sklearn import preprocessing, linear_model | ||
import numpy as np | ||
|
||
data = np.array([[1, 1], [2, 4], [3, 9], [4, 15], [5, 21], [6, 36]]) | ||
X = np.array(data[:,0]).reshape(-1,1) | ||
y = data[:,1] | ||
|
||
poly = preprocessing.PolynomialFeatures(degree=2, include_bias=False) | ||
Xp = poly.fit_transform(X) | ||
|
||
model = linear_model.LinearRegression() | ||
model.fit(Xp, y) | ||
|
||
print(model.predict(Xp)) | ||
``` | ||
``` | ||
[ 1.57142857 3.62857143 7.97142857 14.6 23.51428571 34.71428571] | ||
``` | ||
|