训练集给出如下数据:
测试集提供其中的部分列:
要求预测以下列的数据:
['Tdewpoint', 'Visibility', 'Windspeed', 'RH_out', 'Press_mm_hg', 'RH_9', 'T_out', 'RH_4']
使用随机森林进行预测:
import pandas as pd from sklearn.model_selection import train_test_split from sklearn.ensemble import RandomForestRegressor from sklearn.metrics import mean_squared_error # 读入训练数据和测试数据 train_data = pd.read_csv('train_dataset.csv') test_data = pd.read_csv('test_dataset.csv') li=train_data.columns.to_list()[2::] goal=['Tdewpoint', 'Visibility', 'Windspeed', 'RH_out', 'Press_mm_hg', 'RH_9', 'T_out', 'RH_4'] feature=list(set(li)-set(goal)) # 分离特征变量和目标变量 X = train_data[feature] y = train_data[goal] # 划分训练集和验证集 X_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.2, random_state=42) # 构建随机森林模型 rf = RandomForestRegressor(n_estimators=100, random_state=42) # 训练模型 rf.fit(X_train, y_train) # 预测验证集的结果 y_pred_val = rf.predict(X_val) # 计算验证集的均方误差 mse = mean_squared_error(y_val, y_pred_val) print("Validation set MSE: {:.2f}".format(mse)) # 预测测试集的结果 y_pred_test = rf.predict(test_data) # 保存预测结果到CSV文件 pd.DataFrame(y_pred_test).to_csv('test_result.csv', index=False)
标签:val,data,train,随机,test,csv,RH,森林 From: https://www.cnblogs.com/datielaoyu/p/17436639.html