Save predictions in diabetes_y_pred
No need for `regr.predict(diabetes_X_test)` to run multiple times.
Use `sklearn.metrics.mean_squared_error`.
Use `sklearn.metrics.r2_score`, instead of `regr.score`, which
runs `regr.predict` again.
@@ -26,6 +26,7 @@ print(__doc__)
import matplotlib.pyplot as plt
import numpy as np
from sklearn import datasets, linear_model
+from sklearn.metrics import mean_squared_error, r2_score
# Load the diabetes dataset
diabetes = datasets.load_diabetes()
@@ -48,18 +49,20 @@ regr = linear_model.LinearRegression()
# Train the model using the training sets
regr.fit(diabetes_X_train, diabetes_y_train)
+# Make predictions using the testing set
+diabetes_y_pred = regr.predict(diabetes_X_test)
+
# The coefficients
print('Coefficients: \n', regr.coef_)
# The mean squared error
print("Mean squared error: %.2f"
- % np.mean((regr.predict(diabetes_X_test) - diabetes_y_test) ** 2))
+ % mean_squared_error(diabetes_y_test, diabetes_y_pred))
# Explained variance score: 1 is perfect prediction
-print('Variance score: %.2f' % regr.score(diabetes_X_test, diabetes_y_test))
+print('Variance score: %.2f' % r2_score(diabetes_y_test, diabetes_y_pred))
# Plot outputs
plt.scatter(diabetes_X_test, diabetes_y_test, color='black')
-plt.plot(diabetes_X_test, regr.predict(diabetes_X_test), color='blue',
- linewidth=3)
+plt.plot(diabetes_X_test, diabetes_y_pred, color='blue', linewidth=3)
plt.xticks(())
plt.yticks(())
