text_plain_output_1.png
from sklearn.linear_model import LinearRegression

from sklearn.metrics import r2_score

from sklearn.model_selection import train_test_split

import pandas as pd

cars_data = pd.read_csv('../input/aqalds/AQA-large-data-set.csv')
cars_data

cleaned_cars_data = cars_data[(cars_data['EngineSize'] > 0) & (cars_data['Mass'] > 0) & (cars_data['CO2'] > 0)].copy()
cleaned_cars_data['PropulsionType'] = cars_data['PropulsionTypeId'].replace({1: 'Petrol', 2: 'Diesel', 3: 'Electric', 7: 'Gas/Petrol', 8: 'Electric/Petrol'})
cleaned_cars_data

petrol_data = cleaned_cars_data[cleaned_cars_data['PropulsionType'] == 'Petrol'].copy()
petrol_data

input_features = ['Mass']
input_data = petrol_data[input_features]
target_data = petrol_data['CO2']
input_train, input_test, target_train, target_test = train_test_split(input_data, target_data, train_size=0.75, random_state=1)
linear_model = LinearRegression().fit(input_train, target_train)
target_pred = linear_model.predict(input_test)

input_features = ['EngineSize']
input_data = petrol_data[input_features]
target_data = petrol_data['CO2']
input_train, input_test, target_train, target_test = train_test_split(input_data, target_data, train_size=0.75, random_state=1)
linear_model = LinearRegression().fit(input_train, target_train)
target_pred = linear_model.predict(input_test)

input_features = ['Mass', 'EngineSize']
input_data = petrol_data[input_features]
target_data = petrol_data['CO2']
input_train, input_test, target_train, target_test = train_test_split(input_data, target_data, train_size=0.75, random_state=1)
linear_model = LinearRegression().fit(input_train, target_train)
target_pred = linear_model.predict(input_test)

diesel_data = cleaned_cars_data[cleaned_cars_data['PropulsionType'] == 'Diesel'].copy()
diesel_data

input_features = ['Mass']
input_data = diesel_data[input_features]
target_data = diesel_data['CO2']
input_train, input_test, target_train, target_test = train_test_split(input_data, target_data, train_size=0.75, random_state=1)
linear_model = LinearRegression().fit(input_train, target_train)
target_pred = linear_model.predict(input_test)

input_features = ['EngineSize']
input_data = diesel_data[input_features]
target_data = diesel_data['CO2']
input_train, input_test, target_train, target_test = train_test_split(input_data, target_data, train_size=0.75, random_state=1)
linear_model = LinearRegression().fit(input_train, target_train)
print('Coefficients: ', linear_model.coef_.round(4))
print('Intercept: ', linear_model.intercept_.round(3))
target_pred = linear_model.predict(input_test)
print('R²: ', r2_score(target_test, target_pred).round(3))