import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn.metrics import r2_score
from sklearn.model_selection import train_test_split
df = pd.read_csv('XXX.csv', encoding='gbk')
df.head()
X = df.drop(['MEDV'], axis=1)
y = df['MEDV']
print('X数据集:',X)
print('X数据集类型:',type(X))
print('y数据集:',y)
print('Y数据集类型:',type(y))
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3 , random_state=0)
print(X_train.shape,y_train.shape,X_test.shape,y_test.shape)
mlr = LinearRegression()
mlr.fit(X_train, y_train)
print(mlr.intercept_)
coeff_df = pd.DataFrame(mlr.coef_, X.columns, columns =['Coefficient_value'])
print(coeff_df)
y_pred = mlr.predict(X_test)
print('实际值:',y_test[:30])
print('测试值:',y_pred[:30])
print('训练值R^2:',mlr.score(X_train, y_train))
print('测试值R^2:',mlr.score(X_test, y_test))