我在开发一个基于Python的机器学习项目时遇到了多个让人头疼的bug。这些bug并不是简单的语法错误,而是涉及数据预处理、模型训练和部署等多个环节的问题。以下是我遇到的几个典型问题以及我的排查过程和解决方案。
在训练一个分类模型时,发现模型的准确率明显低于预期。初步检查后发现,数据集中存在大量的缺失值,但在进行特征工程时,我使用了SimpleImputer
对缺失值进行了填充,但模型表现依然不理想。
df.isnull().sum()
查看每个列的缺失值情况,确认确实存在大量缺失值。SimpleImputer
,发现虽然填充了缺失值,但没有考虑到某些列的分布特性。SimpleImputer
的strategy
参数从mean
改为median
,结果模型准确率略有提升。df.describe()
观察数据分布,发现某些列的数值范围较大,可能存在异常值影响模型。from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import Pipeline
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
# 假设X是特征矩阵,y是标签
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
# 构建管道:先填充缺失值,再标准化数据,最后训练模型
pipeline = Pipeline([
('imputer', SimpleImputer(strategy='median')),
('scaler', StandardScaler()),
('classifier', RandomForestClassifier())
])
pipeline.fit(X_train, y_train)
accuracy = pipeline.score(X_test, y_test)
print(f'模型准确率为: {accuracy:.2f}')
mean
或mode
,应根据数据分布选择合适的填充策略。在使用Keras构建神经网络模型时,发现训练集的损失值不断下降,但验证集的损失值却在波动,且整体表现较差。这表明模型可能出现了过拟合。
relu
,且没有使用正则化技术。EarlyStopping
回调,发现模型在某个epoch后停止训练,但验证集仍然表现不佳。from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from tensorflow.keras.callbacks import EarlyStopping
model = Sequential([
Dense(64, activation='relu', input_shape=(X_train.shape[1],)),
Dense(64, activation='relu'),
Dense(1, activation='sigmoid')
])
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
# 添加早停回调
early_stop = EarlyStopping(monitor='val_loss', patience=5)
# 训练模型
history = model.fit(
X_train, y_train,
epochs=100,
batch_size=32,
validation_split=0.2,
callbacks=[early_stop]
)
在将训练好的模型打包并部署到Flask服务中时,请求接口时抛出ValueError: shapes (1,1) and (1,1) not aligned: 1 (dim 1) != 1 (dim 0)
错误。这个错误提示说明输入数据与模型期望的形状不一致。
predict
方法:发现模型期望的输入是numpy.ndarray
类型,而不是列表。pickle
保存的,但未考虑数据格式转换。import numpy as np
import pickle
from flask import Flask, request, jsonify
app = Flask(__name__)
# 加载模型
with open('model.pkl', 'rb') as f:
model = pickle.load(f)
@app.route('/predict', methods=['POST'])
def predict():
data = request.get_json()
input_data = np.array(data['features']).reshape(1, -1) # 转换为二维数组
prediction = model.predict(input_data)
return jsonify({'prediction': int(prediction[0])})
if __name__ == '__main__':
app.run(debug=True)
numpy
的reshape
方法可以灵活调整数据形状,避免维度不匹配问题。在机器学习项目的开发过程中,遇到的各种bug往往不是简单的语法错误,而是涉及到数据、模型和部署等多个环节的问题。通过不断的排查和调试,我积累了不少宝贵的经验。希望这篇文章能对大家在实际开发中有所帮助。
通过这些问题的解决,我对Python机器学习的实践有了更深入的理解,也更加体会到细节的重要性。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。