说一个使用线性回归的回归问题。我想对不同的目标y进行网格搜索,找出哪个目标模型表现最好。
有没有办法在Sklearn中实现它?
例如,输入:
- X,特征矩阵
- 价格,价格数组
- y = price.diff (n)
我想循环不同的n,并在X和price.diff(n)之间做回归。想要找出哪个估计器具有最高的相关性。
如果您试图确定预测因子和响应(依赖)变量之间的相关性。您可以简单地尝试相关矩阵表。
df.corr()
如果你想绘制这个,你可以尝试生成一个热图来可视化你的y的相关强度。下面的代码将返回一个热图来显示相关强度。
# Plotting correlation matrix heat map
import matplotlib.pyplot as plt
import seaborn as sns
cor_df = df.corr() # correlation of all attributes in df
k = 3 # Total number of variables
# Sorting the columns by largest correlation against target variable
cols = cor_df.nlargest(k, "y")["y"]
cols_index = cols.index
# Setting figure & plotting
f, ax = plt.subplots(figsize = (16,10)) # Size of the figure
sns.heatmap(df[cols_index].corr(), annot = True, linewidths = .5,
cmap = "YlGnBu")
最后但并非最不重要的是,如果您试图确定回归模型的最佳超参数。您可以使用sklearn
库中的GridSearchCV()
或RandomizedSearchCV()
。
要执行GridSearchCV()
,必须首先定义要在字典中测试的超参数范围,并将它们作为字典传入。下面只是一个例子,因为我们没有你的数据集:
from sklearn.model_selection import GridSearchCV, train_test_split
from sklearn.linear_model import LinearRegression
# Recommended: Define hyperparameters you wish to test
params = {"normalize": [True, False], "fit_intercept": [True, False]}
# Generate base model & run GridSearchCV (Note that return_train_score lets you print the best parameters)
reg = LinearRegression()
optimal = GridSearchCV(reg, cv = 5, param_grid = params, scoring = "accuracy", return_train_score = True)
# Fit training data
optimal.fit(X_train, y_train)
# Print the best hyperparameters from your Grid Search
print(f"Best Parameters: {optimal.best_params_}")