构建神经网络之sklearn(完善)

1.数据预处理

1.缺失值

import pandas as pd

# 假设我们有一个 DataFrame df
print(df.isnull().sum())  # 查看每一列缺失值的数量

数值型数据:

from sklearn.impute import SimpleImputer

# 对于数值型数据,使用均值填充
imputer = SimpleImputer(strategy='mean')  # 可选:'mean', 'median', 'most_frequent'
df_imputed = imputer.fit_transform(df)  # 填充缺失值

类别

from sklearn.impute import SimpleImpute

imputer = SimpleImputer(strategy='most_frequent')
df_imputed = imputer.fit_transform(df)

2.数据缩放

from sklearn.preprocessing import StandardScaler

scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)  # 标准化 X


from sklearn.preprocessing import MinMaxScaler

scaler = MinMaxScaler()
X_normalized = scaler.fit_transform(X)  # 归一化 X

为什么需要标准化和归一化?

  • 标准化:对于距离度量(如 K 最近邻、支持向量机等)非常重要,因为特征的尺度不一致可能导致某些特征对模型的影响过大。标准化能确保每个特征对模型有相同的贡献。

  • 归一化:有些算法(如神经网络、梯度下降优化算法等)对输入数据的范围非常敏感,归一化有助于加速收敛

2.模型评估

1 交叉验证

1.cross_val_score 函数用于执行 K-fold 交叉验证

scores = cross_val_score(model, X, y, cv=5)

2 超参数调优

from sklearn.model_selection import RandomizedSearchCV
from sklearn.svm import SVC
from sklearn.datasets import load_iris
from scipy.stats import uniform

# 加载数据
data = load_iris()
X, y = data.data, data.target

# 创建模型
model = SVC()

# 定义超参数分布
param_distributions = {'C': uniform(0, 10), 'kernel': ['linear', 'rbf']}

# 执行随机搜索
random_search = RandomizedSearchCV(model, param_distributions, n_iter=10, cv=5)
random_search.fit(X, y)

# 输出最佳参数和最佳得分
print(f"Best parameters: {random_search.best_params_}")
print(f"Best score: {random_search.best_score_}")

你可能感兴趣的:(神经网络,sklearn,机器学习)