Upload files to "Regresi.machine_learning"

This commit is contained in:
202310715049 ARYO SAPUTRO 2025-11-23 21:49:30 +07:00
parent f05cf3d8c9
commit e8cbf6f7f8
4 changed files with 1452 additions and 0 deletions

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,593 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<p style=\"text-align:center\">\n",
" <a href=\"https://skills.network\" target=\"_blank\">\n",
" <img src=\"https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/assets/logos/SN_web_lightmode.png\" width=\"200\" alt=\"Skills Network Logo\">\n",
" </a>\n",
"</p>\n",
"\n",
"\n",
"# Simple Linear Regression\n",
"\n",
"\n",
"Estimated time needed: **15** minutes\n",
" \n",
"\n",
"## Objectives\n",
"\n",
"After completing this lab you will be able to:\n",
"\n",
"* Use scikit-learn to implement simple Linear Regression\n",
"* Create a model, train it, test it and use the model\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Importing Needed packages\n"
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {},
"outputs": [],
"source": [
"import matplotlib.pyplot as plt\n",
"import pandas as pd\n",
"import pylab as pl\n",
"import numpy as np\n",
"%matplotlib inline"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Downloading Data\n",
"To download the data, we will use !wget to download it from IBM Object Storage.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"!wget -O FuelConsumption.csv https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-ML0101EN-SkillsNetwork/labs/Module%202/data/FuelConsumptionCo2.csv"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In case you're working **locally** uncomment the below line. \n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"#!curl https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-ML0101EN-SkillsNetwork/labs/Module%202/data/FuelConsumptionCo2.csv -o FuelConsumptionCo2.csv"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"## Understanding the Data\n",
"\n",
"### `FuelConsumption.csv`:\n",
"We have downloaded a fuel consumption dataset, **`FuelConsumption.csv`**, which contains model-specific fuel consumption ratings and estimated carbon dioxide emissions for new light-duty vehicles for retail sale in Canada. [Dataset source](http://open.canada.ca/data/en/dataset/98f1a129-f628-4ce4-b24d-6f16bf24dd64)\n",
"\n",
"- **MODELYEAR** e.g. 2014\n",
"- **MAKE** e.g. Acura\n",
"- **MODEL** e.g. ILX\n",
"- **VEHICLE CLASS** e.g. SUV\n",
"- **ENGINE SIZE** e.g. 4.7\n",
"- **CYLINDERS** e.g 6\n",
"- **TRANSMISSION** e.g. A6\n",
"- **FUEL CONSUMPTION in CITY(L/100 km)** e.g. 9.9\n",
"- **FUEL CONSUMPTION in HWY (L/100 km)** e.g. 8.9\n",
"- **FUEL CONSUMPTION COMB (L/100 km)** e.g. 9.2\n",
"- **CO2 EMISSIONS (g/km)** e.g. 182 --> low --> 0\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Reading the data in\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"df = pd.read_csv(\"FuelConsumption.csv\")\n",
"\n",
"# take a look at the dataset\n",
"df.head()\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Data Exploration\n",
"Let's first have a descriptive exploration on our data.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# summarize the data\n",
"df.describe()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Let's select some features to explore more.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"cdf = df[['ENGINESIZE','CYLINDERS','FUELCONSUMPTION_COMB','CO2EMISSIONS']]\n",
"cdf.head(9)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can plot each of these features:\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"viz = cdf[['CYLINDERS','ENGINESIZE','CO2EMISSIONS','FUELCONSUMPTION_COMB']]\n",
"viz.hist()\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now, let's plot each of these features against the Emission, to see how linear their relationship is:\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"plt.scatter(cdf.FUELCONSUMPTION_COMB, cdf.CO2EMISSIONS, color='blue')\n",
"plt.xlabel(\"FUELCONSUMPTION_COMB\")\n",
"plt.ylabel(\"Emission\")\n",
"plt.show()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"plt.scatter(cdf.ENGINESIZE, cdf.CO2EMISSIONS, color='blue')\n",
"plt.xlabel(\"Engine size\")\n",
"plt.ylabel(\"Emission\")\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Practice\n",
"Plot __CYLINDER__ vs the Emission, to see how linear is their relationship is:\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"plt.scatter(cdf.CYLINDERS, cdf.CO2EMISSIONS, color='blue')\n",
"plt.xlabel(\"Cylinders\")\n",
"plt.ylabel(\"Emission\")\n",
"plt.show()\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<details><summary>Click here for the solution</summary>\n",
"\n",
"```python \n",
"plt.scatter(cdf.CYLINDERS, cdf.CO2EMISSIONS, color='blue')\n",
"plt.xlabel(\"Cylinders\")\n",
"plt.ylabel(\"Emission\")\n",
"plt.show()\n",
"\n",
"```\n",
"\n",
"</details>\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Creating train and test dataset\n",
"Train/Test Split involves splitting the dataset into training and testing sets that are mutually exclusive. After which, you train with the training set and test with the testing set. \n",
"This will provide a more accurate evaluation on out-of-sample accuracy because the testing dataset is not part of the dataset that have been used to train the model. Therefore, it gives us a better understanding of how well our model generalizes on new data.\n",
"\n",
"This means that we know the outcome of each data point in the testing dataset, making it great to test with! Since this data has not been used to train the model, the model has no knowledge of the outcome of these data points. So, in essence, it is truly an out-of-sample testing.\n",
"\n",
"Let's split our dataset into train and test sets. 80% of the entire dataset will be used for training and 20% for testing. We create a mask to select random rows using __np.random.rand()__ function: \n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"msk = np.random.rand(len(df)) < 0.8\n",
"train = cdf[msk]\n",
"test = cdf[~msk]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Simple Regression Model\n",
"Linear Regression fits a linear model with coefficients B = (B1, ..., Bn) to minimize the 'residual sum of squares' between the actual value y in the dataset, and the predicted value yhat using linear approximation. \n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Train data distribution\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"plt.scatter(train.ENGINESIZE, train.CO2EMISSIONS, color='blue')\n",
"plt.xlabel(\"Engine size\")\n",
"plt.ylabel(\"Emission\")\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Modeling\n",
"Using sklearn package to model data.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from sklearn import linear_model\n",
"regr = linear_model.LinearRegression()\n",
"train_x = np.asanyarray(train[['ENGINESIZE']])\n",
"train_y = np.asanyarray(train[['CO2EMISSIONS']])\n",
"regr.fit(train_x, train_y)\n",
"# The coefficients\n",
"print ('Coefficients: ', regr.coef_)\n",
"print ('Intercept: ',regr.intercept_)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"As mentioned before, __Coefficient__ and __Intercept__ in the simple linear regression, are the parameters of the fit line. \n",
"Given that it is a simple linear regression, with only 2 parameters, and knowing that the parameters are the intercept and slope of the line, sklearn can estimate them directly from our data. \n",
"Notice that all of the data must be available to traverse and calculate the parameters.\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Plot outputs\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can plot the fit line over the data:\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"plt.scatter(train.ENGINESIZE, train.CO2EMISSIONS, color='blue')\n",
"plt.plot(train_x, regr.coef_[0][0]*train_x + regr.intercept_[0], '-r')\n",
"plt.xlabel(\"Engine size\")\n",
"plt.ylabel(\"Emission\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Evaluation\n",
"We compare the actual values and predicted values to calculate the accuracy of a regression model. Evaluation metrics provide a key role in the development of a model, as it provides insight to areas that require improvement.\n",
"\n",
"There are different model evaluation metrics, lets use MSE here to calculate the accuracy of our model based on the test set: \n",
"* Mean Absolute Error: It is the mean of the absolute value of the errors. This is the easiest of the metrics to understand since its just average error.\n",
"\n",
"* Mean Squared Error (MSE): Mean Squared Error (MSE) is the mean of the squared error. Its more popular than Mean Absolute Error because the focus is geared more towards large errors. This is due to the squared term exponentially increasing larger errors in comparison to smaller ones.\n",
"\n",
"* Root Mean Squared Error (RMSE). \n",
"\n",
"* R-squared is not an error, but rather a popular metric to measure the performance of your regression model. It represents how close the data points are to the fitted regression line. The higher the R-squared value, the better the model fits your data. The best possible score is 1.0 and it can be negative (because the model can be arbitrarily worse).\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from sklearn.metrics import r2_score\n",
"\n",
"test_x = np.asanyarray(test[['ENGINESIZE']])\n",
"test_y = np.asanyarray(test[['CO2EMISSIONS']])\n",
"test_y_ = regr.predict(test_x)\n",
"\n",
"print(\"Mean absolute error: %.2f\" % np.mean(np.absolute(test_y_ - test_y)))\n",
"print(\"Residual sum of squares (MSE): %.2f\" % np.mean((test_y_ - test_y) ** 2))\n",
"print(\"R2-score: %.2f\" % r2_score(test_y , test_y_) )"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Exercise\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Lets see what the evaluation metrics are if we trained a regression model using the `FUELCONSUMPTION_COMB` feature.\n",
"\n",
"Start by selecting `FUELCONSUMPTION_COMB` as the train_x data from the `train` dataframe, then select `FUELCONSUMPTION_COMB` as the test_x data from the `test` dataframe\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"train_x = train[[\"FUELCONSUMPTION_COMB\"]]\n",
"\n",
"test_x = test[[\"FUELCONSUMPTION_COMB\"]]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<details><summary>Click here for the solution</summary>\n",
"\n",
"```python \n",
"train_x = train[[\"FUELCONSUMPTION_COMB\"]]\n",
"\n",
"test_x = test[[\"FUELCONSUMPTION_COMB\"]]\n",
"\n",
"```\n",
"\n",
"</details>\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now train a Linear Regression Model using the `train_x` you created and the `train_y` created previously\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"regr = linear_model.LinearRegression()\n",
"\n",
"regr.fit(train_x, train_y)\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<details><summary>Click here for the solution</summary>\n",
"\n",
"```python \n",
"regr = linear_model.LinearRegression()\n",
"\n",
"regr.fit(train_x, train_y)\n",
"\n",
"```\n",
"\n",
"</details>\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Find the predictions using the model's `predict` function and the `test_x` data\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"predictions = regr.predict(test_x)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<details><summary>Click here for the solution</summary>\n",
"\n",
"```python \n",
"predictions = regr.predict(test_x)\n",
"\n",
"```\n",
"\n",
"</details>\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Finally use the `predictions` and the `test_y` data and find the Mean Absolute Error value using the `np.absolute` and `np.mean` function like done previously\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"print(\"Mean Absolute Error: %.2f\" % np.mean(np.absolute(predictions - test_y)))\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<details><summary>Click here for the solution</summary>\n",
"\n",
"```python \n",
"print(\"Mean Absolute Error: %.2f\" % np.mean(np.absolute(predictions - test_y)))\n",
"\n",
"```\n",
"\n",
"</details>\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can see that the MAE is much worse when we train using `ENGINESIZE` than `FUELCONSUMPTION_COMB`\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Thank you for completing this lab!\n",
"\n",
"\n",
"## Author\n",
"\n",
"Saeed Aghabozorgi\n",
"\n",
"\n",
"### Other Contributors\n",
"\n",
"<a href=\"https://www.linkedin.com/in/joseph-s-50398b136/\" target=\"_blank\">Joseph Santarcangelo</a>\n",
"\n",
"Azim Hirjani\n",
"\n",
"## <h3 align=\"center\"> © IBM Corporation. All rights reserved. <h3/>\n",
"\n",
"<!--\n",
"## Change Log\n",
"\n",
"\n",
"| Date (YYYY-MM-DD) | Version | Changed By | Change Description |\n",
"|---|---|---|---|\n",
"| 2020-11-03 | 2.1 | Lakshmi Holla | Changed URL of the csv |\n",
"| 2020-08-27 | 2.0 | Lavanya | Moved lab to course repo in GitLab |\n",
"| | | | |\n",
"| | | | |\n",
"\n",
"--!>\n",
"\n",
"\n"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python",
"language": "python",
"name": "conda-env-python-py"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.7.12"
},
"prev_pub_hash": "20d6dc1d9e74df451be22381c972d7921c93657bea402a00c749dca52bb85996"
},
"nbformat": 4,
"nbformat_minor": 4
}