帮我优化这段代码;import numpy as np from sklearn.datasets import load_boston from sklearn.model_selection import train_test_split from linear_model_03.closed_form_sol.LineaRegression_CFSol import LinearRegressionClosedFormSol boston = load_boston() # 加载数据 X, y = boston.data, boston.target # 样本数据和目标值 X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=1, shuffle=True) lr_cfs = LinearRegressionClosedFormSol(fit_intercept=True, normalized=True) # 默认训练偏置项和进行标准化 lr_cfs.fit(X_train, y_train) # 训练模型 theta = lr_cfs.get_params() feature_names = boston.feature_names # 样本的名称 for i, fn in enumerate(feature_names): print(fn, ":", theta[0][i]) print("bias:", theta[1]) y_test_pred = lr_cfs.predict(x_test=X_test) mse, r2, r2c = lr_cfs.cal_mse_r2(y_test, y_test_pred) print("均方误差:%.5f,判决系数:%.5f,修正判决系数:%.5f" % (mse, r2, r2c)) # lr_cfs.plt_predict(y_test, y_test_pred, is_sort=False) lr_cfs.plt_predict(y_test, y_test_pred, is_sort=True)
时间: 2023-12-24 11:10:38 浏览: 98
好的,我来帮你优化代码。首先,你可以将导入的库放在代码开头,以便更好地组织代码。另外,命名规范也需要注意,例如,类名应该使用大写字母开头,函数名和变量名应该使用小写字母和下划线。下面是优化后的代码:
```python
import numpy as np
from sklearn.datasets import load_boston
from sklearn.model_selection import train_test_split
from linear_model_03.closed_form_sol.LinearRegression_CFSol import LinearRegressionClosedFormSol
boston = load_boston()
X, y = boston.data, boston.target
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=1, shuffle=True)
lr_cfs = LinearRegressionClosedFormSol(fit_intercept=True, normalized=True)
lr_cfs.fit(X_train, y_train)
theta = lr_cfs.get_params()
feature_names = boston.feature_names
for i, fn in enumerate(feature_names):
print(fn, ":", theta[0][i])
print("bias:", theta[1])
y_test_pred = lr_cfs.predict(x_test=X_test)
mse, r2, r2c = lr_cfs.cal_mse_r2(y_test, y_test_pred)
print("均方误差:%.5f,判决系数:%.5f,修正判决系数:%.5f" % (mse, r2, r2c))
lr_cfs.plt_predict(y_test, y_test_pred, is_sort=True)
```
这样,代码更加清晰易读,同时也符合 PEP8 规范。
阅读全文