<jupyter_start><jupyter_text>06 R Squared (R^2)<jupyter_code>import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets
boston = datasets.load_boston()
x = boston.data[:,5] # 只使用房间数量这个特征
y = boston.target

x = x[y < 50.0]
y = y[y < 50.0]
from playML.model_selection import train_test_split

x_train, x_test, y_train, y_test = train_test_split(x, y, seed=666)
from playML.SimpleLinearRegression import SimpleLinearRegression

reg = SimpleLinearRegression()
reg.fit(x_train, y_train)
reg.a_
reg.b_
y_predict = reg.predict(x_test)<jupyter_output><empty_output><jupyter_text>R Square<jupyter_code>from playML.metrics import mean_squared_error

1 - mean_squared_error(y_test, y_predict)/np.var(y_test)<jupyter_output><empty_output><jupyter_text>封装我们自己的 R Score代码参见 [这里](playML/metrics.py)<jupyter_code>from playML.metrics import r2_score

r2_score(y_test, y_predict)<jupyter_output><empty_output><jupyter_text>scikit-learn中的 r2_score<jupyter_code>from sklearn.metrics import r2_score

r2_score(y_test, y_predict)<jupyter_output><empty_output><jupyter_text>scikit-learn中的LinearRegression中的score返回r2_score:[http://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LinearRegression.html](http://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LinearRegression.html)  在我们的SimpleRegression中添加score<jupyter_code>reg.score(x_test, y_test)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.10747330960854093, 'fraction_numerical': 0.014234875444839857, 'mean_word_length': 9.18840579710145, 'pattern_counts': {'":': 0, '<': 23, '<?xml version=': 0, '>': 21, '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': '5', 'dir': 'jupyter-structured-clean-dedup', 'id': '623064', 'license': 'Apache-2.0', 'n_tokens_mistral': 581, 'n_tokens_neox': 566, 'n_words': 74, 'path': '05-Linear-Regression/06-R-Squared/06-R-Squared.ipynb', 'repo_name': 'mtianyan/Mtianyan-Play-with-Machine-Learning-Algorithms', 'size': '1405'}