<jupyter_start><jupyter_text>Week 2 - Polynomial Regression<jupyter_code>import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
df = pd.read_csv('FuelConsumption.csv')
df.head()
# X = df[['ENGINESIZE','CYLINDERS','FUELCONSUMPTION_COMB']]
X = df[['ENGINESIZE']]
X.head()
y = df[['CO2EMISSIONS']]
y.head()<jupyter_output><empty_output><jupyter_text>Train test split<jupyter_code>from sklearn.cross_validation import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2)
y_test.head()<jupyter_output><empty_output><jupyter_text>Making the features polynomial<jupyter_code>from sklearn import preprocessing
poly = preprocessing.PolynomialFeatures(degree = 2)<jupyter_output><empty_output><jupyter_text>The **fit_transform()** method takes an argument and returns a polynomial of each feature, for example, if we use a degree **2** in a feature is *x*, then it would replace that featurewith *1 + x + x2*<jupyter_code>X_train_poly = poly.fit_transform(X_train)   # Return numpy.ndarray
type(X_train_poly)
print(X_train_poly)<jupyter_output><empty_output><jupyter_text>Training with the data<jupyter_code>from sklearn import linear_model

model = linear_model.LinearRegression()
model.fit(X_train_poly, y_train)<jupyter_output><empty_output><jupyter_text>Making the test features polynomial<jupyter_code>poly = preprocessing.PolynomialFeatures(degree = 2)

X_test_poly = poly.fit_transform(X_test)<jupyter_output><empty_output><jupyter_text>Making a prediction from a test feature<jupyter_code>model.predict([X_test_poly[3]])<jupyter_output><empty_output><jupyter_text>Evaluation of the model<jupyter_code>from sklearn import metrics

predicted_y = model.predict(X_test_poly)
mean_error = np.mean(np.absolute(predicted_y - y_test))
mean_square_error = mean_error ** 2
my_r2_score = metrics.r2_score(predicted_y, y_test)
print("Mean error is %.2f" % mean_error)
print("Mean Square error is %.2f" % mean_square_error)
print("R2 score is %.2f" % my_r2_score)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.1101364522417154, 'fraction_numerical': 0.008771929824561403, 'mean_word_length': 9.014634146341463, 'pattern_counts': {'":': 0, '<': 33, '<?xml version=': 0, '>': 33, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '8', 'dir': 'jupyter-structured-clean-dedup', 'id': '387049', 'license': 'MIT', 'n_tokens_mistral': 766, 'n_tokens_neox': 745, 'n_words': 147, 'path': 'Week 2/Polynomial Regression.ipynb', 'repo_name': 'Razdeep/Coursera-ML-with-Python-notebooks', 'size': '2052'}