利用score函数得到模型的拟合优度 代码
时间: 2023-12-12 08:02:46 浏览: 31
以下是使用score函数得到模型拟合优度的示例代码:
如果是分类模型:
```python
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
# 假设X和y为数据集和标签
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0)
clf = LogisticRegression(random_state=0).fit(X_train, y_train)
score = clf.score(X_test, y_test) # 返回测试集的准确率
```
如果是回归模型:
```python
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
# 假设X和y为数据集和标签
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0)
reg = LinearRegression().fit(X_train, y_train)
score = reg.score(X_test, y_test) # 返回测试集的R-squared值
```
需要注意的是,不同的模型评估指标不同,具体可以查看对应模型的文档。