此为备考记录,主要记录常用或不熟的语法用法,后续会更新调整的
迭代次数
训练Logistic回归模型(最大迭代次数为1000次)
max_iter为最大迭代次数,所以填入LogisticRegression(max_iter=1000)
训练模型
训练 Logistic 回归模型
数据变量名.fit(X_train,y_train)
保存模型
pickle.dump(前文的模型名,上文的as后的变量)
分析测试结果
(y_test == 上文新生成的ytes变量名).mean
预测数据
模型变量名.predict(X_test)
转换数据
转换成数值类型pd.to_numeric(需要转换的数据,errors='coerce')
X = df['Your age'].apply(X) # 将分类变量转为数值变量
y = df['Your age'].apply(lambda x: int(x.split(' ')[0])) # 假设年龄段为整数
X = pd.get_dummies(X) # 将分类变量转为数值变量
选择特征值建模
选择对应的变量放入对应的位置,去文中找(类似下文)
X = df[['cylinders', 'displacement', 'horsepower', 'weight', 'acceleration', 'model year', 'origin']]
y = df['mpg']
将数据集划分为训练集和测试集(测试集占比20%
一般固定为以下格式
train_test_split(X,y, random_state=42)
决策树数量
创建随机森林回归模型实例(创建的决策树的数量为100)
RandomForestRegressor(n_estimators=100, random_state=42)
2.2.3导入类错位
import xgboost as xgb修改为:from xgboost import XGBRegressor
测试工具对模型进行测试
train_score = rf_model.score(X_train,y_train) #训练集分数
test_score = rf_model.fit(X_test,y_test) #测试集分数
mse = mean_squared_error(y_test,y_pred) #均方误差
r2 = r2_score(y_test,y_pred) #决定系数
结果
with open('2.2.3_report_xgb.txt', 'w') as xgb_report_file:
xgb_report_file.write(f'XGBoost训练集得分: {xgb_model.score(X_train,y_train) }\n')
xgb_report_file.write(f'XGBoost测试集得分: {xgb_model.score(X_test,y_test) }\n')
xgb_report_file.write(f'XGBoost均方误差(MSE): {mean_squared_error(y_test,y_pred) }\n')
xgb_report_file.write(f'XGBoost决定系数(R^2): {r2_score(y_test,y_pred)}\n')