<jupyter_start><jupyter_text>Machine Learning MethodAbout this NotebookIn this notebook, we learn how to use scikit-learn to implement simple linear regression. We download a dataset that is related to fuel consumption and Carbon dioxide emission of cars. Then, we split our data into training and test sets, create a model using training set, evaluate your model using test set, and finally use model to predict unknown value. Table of contents            Understanding the Data        Reading the data in        Data Exploration        Simple Regression Model      Importing Needed packages<jupyter_code>import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import pylab as pl
import numpy as np
%matplotlib inline

from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression, Lasso, Ridge
from sklearn.metrics import mean_absolute_error, r2_score<jupyter_output><empty_output><jupyter_text>Downloading DataTo download the data, we will use !wget to download it from IBM Object Storage.<jupyter_code>#!wget -O MY2022_Fuel_Consumption_Ratings.csv https://www.nrcan.gc.ca/sites/nrcan/files/oee/files/csv/MY2022%20Fuel%20Consumption%20Ratings.csv<jupyter_output><empty_output><jupyter_text>Understanding the Data `MY2022_Fuel_Consumption_Ratings.csv`:We have downloaded a fuel consumption dataset, **`MY2022 Fuel Consumption Ratings.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](https://open.canada.ca/data/en/dataset/98f1a129-f628-4ce4-b24d-6f16bf24dd64)- **MODELYEAR** e.g. 2022- **MAKE** e.g. Acura- **MODEL** e.g. ILX- **VEHICLE CLASS** e.g. Compact- **ENGINE SIZE** e.g. 2.4- **CYLINDERS** e.g 4- **TRANSMISSION** e.g. AM8- **FUEL** e.g. Z- **FUEL CONSUMPTION in CITY(L/100 km)** e.g. 9.9- **FUEL CONSUMPTION in HWY (L/100 km)** e.g. 7- **FUEL CONSUMPTION COMB (L/100 km)** e.g. 8.6- **CO2 EMISSIONS (g/km)** e.g. 200   --> 6- **SMOG** e.g. 3 Reading the data in<jupyter_code>emissions_df = pd.read_csv("MY2022_Fuel_Consumption_Ratings.csv", encoding='cp1252',
                 nrows=882, usecols=[1,2,3,4,5,6,7,8,9,10,11,12,13,14], index_col=False)

# take a look at the dataset
emissions_df.tail(3)<jupyter_output><empty_output><jupyter_text>Data ExplorationLets first have a descriptive exploration on our data.<jupyter_code># summarize the data
emissions_df.describe()<jupyter_output><empty_output><jupyter_text>Lets select some features to explore more.<jupyter_code>emissions_df = emissions_df[['Engine_Size','Cylinders','Fuel_Consumption_City','Fuel_Consumption_Hwy','Fuel_Consumption_Comb','CO2_Emissions','CO2_Rating','Smog_Rating']]
emissions_df.sample(4)<jupyter_output><empty_output><jupyter_text>we can plot each of these features:<jupyter_code>viz = emissions_df[['Engine_Size','Cylinders','Fuel_Consumption_City','Fuel_Consumption_Hwy']]
viz.hist()
plt.show()<jupyter_output><empty_output><jupyter_text>Now, lets plot each of these features vs the Emission, to see how linear is their relation:<jupyter_code>plt.scatter(emissions_df['Fuel_Consumption_City'], emissions_df['CO2_Emissions'],  color='blue')
plt.xlabel("FUELCONSUMPTION_COMB")
plt.ylabel("Emission")
plt.show()
plt.scatter(emissions_df['Engine_Size'], emissions_df['CO2_Emissions'],  color='blue')
plt.xlabel("Engine size")
plt.ylabel("Emission")
plt.show()
plt.scatter(emissions_df['Cylinders'], emissions_df['CO2_Emissions'], color='blue')
plt.xlabel('Cylinders')
plt.ylabel('Emission')
plt.show()
upp_mat = np.triu(emissions_df.corr())
sns.heatmap(emissions_df.corr(), vmin = -1, vmax = +1, annot = True, cmap = 'coolwarm', mask = upp_mat)<jupyter_output><empty_output><jupyter_text>Separate features and target in different datasets<jupyter_code>X =  emissions_df[['Engine_Size','Cylinders','Fuel_Consumption_City','Fuel_Consumption_Hwy']]
y =  emissions_df['CO2_Emissions']<jupyter_output><empty_output><jupyter_text>Apply Principal Component Analysis<jupyter_code># n_components = min(n_muestras, n_feactures)
pca = PCA(n_components=3)
pca.fit(X)
plt.plot(range(len(pca.explained_variance_)), pca.explained_variance_ratio_)
plt.legend(['PCA'])
plt.show()<jupyter_output><empty_output><jupyter_text>Normalize<jupyter_code>#X = StandardScaler().fit_transform(X)<jupyter_output><empty_output><jupyter_text>The dataset is separated into a training set and a test set  Creating train and test datasetTrain/Test Split involves splitting the dataset into training and testing sets respectively, which are mutually exclusive. After which, you train with the training set and test with the testing set. 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 data. It is more realistic for real world problems.This means that we know the outcome of each data point in this dataset, making it great to test with! And 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.Lets split our dataset into train and test sets, 70% of the entire data for training, and the 30% for testing.<jupyter_code>X_train,X_test,y_train,y_test = train_test_split(X, y, test_size=0.3, random_state=42)<jupyter_output><empty_output><jupyter_text>Simple Regression ModelLinear Regression fits a linear model with coefficients $\theta = (\theta_1, ..., \theta_n)$ to minimize the 'residual sum of squares' between the independent x in the dataset, and the dependent y by the linear approximation.   Model<jupyter_code>stimators = {'Linear':LinearRegression(),
            'Lasso': Lasso(alpha=0.02),
            'Ridge': Ridge(alpha=1)}
for name, stimator in stimators.items():
    stimator.fit(X_train,y_train)
    predictions = stimator.predict(X_test)
    print('*'*64)
    print(name)
    print('MSE:', mean_absolute_error(y_test, predictions))
    print("R2-score: %.2f" % r2_score(y_test, predictions))
    print('intecep:',stimator.intercept_,' Coeficient:',stimator.coef_)

    plt.ylabel('Predicted Score')
    plt.xlabel('Real Score')
    plt.title('Predicted VS Real')
    plt.scatter(y_test, predictions)
    plt.plot(predictions, predictions,'r--')
    plt.show()<jupyter_output>****************************************************************
Linear
MSE: 7.5023996350735525
R2-score: 0.95
intecep: 21.737655663753117  Coeficient: [ 0.39502355  3.0100433  11.2690848   8.33262087]
{'fraction_non_alphanumeric': 0.11916942521817635, 'fraction_numerical': 0.030544688534456816, 'mean_word_length': 6.155005382131324, 'pattern_counts': {'":': 0, '<': 48, '<?xml version=': 0, '>': 49, 'https://': 2, 'lorem ipsum': 0, 'www.': 1, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 5, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '12', 'dir': 'jupyter-structured-clean-dedup', 'id': '663052', 'license': 'MIT', 'n_tokens_mistral': 2355, 'n_tokens_neox': 2184, 'n_words': 592, 'path': 'code/.ipynb_checkpoints/Regression - CO2 Emission Regression-checkpoint.ipynb', 'repo_name': 'CrowBonilla/sistemas-inteligentes', 'size': '6646'}