简要地给出sklearn库中的代码及相关功能
时间: 2023-12-31 12:05:53 浏览: 24
以下是sklearn库中的一些常用代码及相关功能:
1. 导入数据集并进行预处理:
```python
from sklearn import datasets
from sklearn.preprocessing import StandardScaler
# 导入数据集
iris = datasets.load_iris()
X = iris.data
y = iris.target
# 数据预处理
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
```
2. 划分数据集为训练集和测试集:
```python
from sklearn.model_selection import train_test_split
# 划分数据集
X_train, X_test, y_train, y_test = train_test_split(X_scaled, y, test_size=0.2, random_state=42)
```
3. 构建和训练机器学习模型:
```python
from sklearn.linear_model import LogisticRegression
# 构建模型
lr = LogisticRegression()
# 训练模型
lr.fit(X_train, y_train)
```
4. 对模型进行评估和预测:
```python
from sklearn.metrics import accuracy_score
# 评估模型
y_pred = lr.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
print('Accuracy:', accuracy)
# 预测新数据
new_data = [[5.1, 3.5, 1.4, 0.2], [6.2, 3.4, 5.4, 2.3]]
new_data_scaled = scaler.transform(new_data)
new_pred = lr.predict(new_data_scaled)
print('New predictions:', new_pred)
```
这些代码演示了sklearn库中导入数据、数据预处理、模型构建、训练和评估、预测等常用功能。当然,sklearn库中还包含了许多其他有用的函数和工具,可以根据具体的需求进行选择和使用。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)