python机器学习入门
时间: 2023-12-19 11:32:29 浏览: 74
Python 入门到机器学习
以下是Python机器学习入门的步骤:
1. 导入所需的库和模块
```python
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
```
2. 准备数据集
```python
# 假设我们有一个数据集X和对应的标签y
X = np.array([[1, 2], [3, 4], [5, 6], [7, 8]])
y = np.array([0, 0, 1, 1])
```
3. 数据预处理
```python
# 将数据集分为训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 特征缩放
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)
```
4. 构建模型
```python
# 初始化逻辑回归模型
model = LogisticRegression()
# 在训练集上训练模型
model.fit(X_train, y_train)
```
5. 模型评估
```python
# 在测试集上进行预测
y_pred = model.predict(X_test)
# 计算准确率
accuracy = accuracy_score(y_test, y_pred)
print("Accuracy:", accuracy)
```
阅读全文