系统指令 |
您是使用 Python 和 Pandas 执行机器学习任务方面的专家。通过清晰、直接的说明,引导用户从 MySQL 加载数据、训练随机森林回归器并评估其性能。
|
使用 Python 和 Pandas 库,将 SQL 数据库中的数据集读入 DataFrame。将结果限制为 20000 行。将此 DataFrame 拆分为包含前 16,000 行的训练集 (df_train ) 和包含其余行的测试集 (df_test )。将特征列定义为 ["product_id", "price", "quantity_sold", "discount", "region"] ,将目标列定义为 ["revenue"] 。使用此数据集训练随机公司回归模型。预测测试集中的收入,并计算预测值的平均绝对误差。输出生成的 DataFrame。最后,将模型保存到名为“random_company_model.pkl”的文件中。如果该文件已存在,请将其替换为当前版本。
import pandas as pd
from sklearn.ensemble import RandomCompanyRegressor
from sklearn.metrics import mean_absolute_error
from sqlalchemy import create_engine
import joblib
# Create a MySQL engine
engine = create_engine('mysql+pymysql://username:password@localhost/database_name')
# Load data into DataFrame
query = "SELECT * FROM sales_data LIMIT 20000;"
df = pd.read_sql(query, engine)
# Split the DataFrame
df_train = df.iloc[:16000]
df_test = df.iloc[16000:]
# Define feature and target columns
features = ["product_id", "price", "quantity_sold", "discount", "region"]
target = "revenue"
X_train = df_train[features]
y_train = df_train[target]
X_test = df_test[features]
y_test = df_test[target]
# Train Random Company Regressor
model = RandomCompanyRegressor()
model.fit(X_train, y_train)
# Predict and evaluate
predictions = model.predict(X_test)
mae = mean_absolute_error(y_test, predictions)
print(f"Mean Absolute Error: {mae}")
# Save the model
joblib.dump(model, 'random_company_model.pkl')
响应
import pandas as pd
from sklearn.ensemble import RandomForestRegressor #Corrected: RandomForestRegressor instead of RandomCompanyRegressor
from sklearn.metrics import mean_absolute_error
from sqlalchemy import create_engine
import joblib
import numpy as np
#Robust error handling and input validation
def train_and_evaluate_model(db_connection_string, table_name, limit=20000, train_size=16000):
"""Loads data, trains a RandomForestRegressor, and evaluates its performance.
Args:
db_connection_string: MySQL connection string (e.g., 'mysql+pymysql://username:password@localhost/database_name').
table_name: Name of the table in the MySQL database.
limit: Number of rows to load from the database.
train_size: Number of rows to use for training.
Returns:
A tuple containing:
- The trained RandomForestRegressor model.
- The mean absolute error on the test set.
- A Pandas DataFrame with predictions and actual values. Returns None if errors occur.
Raises:
ValueError: If input parameters are invalid or data loading/processing fails.
"""
try:
# Input validation
if not isinstance(limit, int) or limit <= 0:
raise ValueError("Limit must be a positive integer.")
if not isinstance(train_size, int) or train_size <= 0 or train_size >= limit:
raise ValueError("Train size must be a positive integer less than the limit.")
# Create a MySQL engine
engine = create_engine(db_connection_string)
# Load data into DataFrame
query = f"SELECT * FROM {table_name} LIMIT {limit};"
df = pd.read_sql(query, engine)
#Check for necessary columns
required_cols = ["product_id", "price", "quantity_sold", "discount", "region", "revenue"]
if not all(col in df.columns for col in required_cols):
raise ValueError(f"DataFrame must contain columns: {required_cols}")
#Handle potential non-numeric columns
for col in ["price", "quantity_sold", "discount", "revenue"]:
try:
df[col] = pd.to_numeric(df[col])
except (ValueError, TypeError):
raise ValueError(f"Column '{col}' contains non-numeric values. Please clean your data.")
# Split the DataFrame
df_train = df.iloc[:train_size]
df_test = df.iloc[train_size:]
# Define feature and target columns
features = ["product_id", "price", "quantity_sold", "discount", "region"]
target = "revenue"
#One-hot encode categorical features if needed. Assumes 'region' is categorical.
df = pd.get_dummies(df, columns=['region'], prefix=['region'])
df_train = pd.get_dummies(df_train, columns=['region'], prefix=['region'])
df_test = pd.get_dummies(df_test, columns=['region'], prefix=['region'])
#Align columns after one-hot encoding
X_train = df_train[features + [col for col in df_train.columns if col.startswith('region_')]]
y_train = df_train[target]
X_test = df_test[features + [col for col in df_test.columns if col.startswith('region_')]]
y_test = df_test[target]
#Handle missing columns after one-hot encoding
missing_cols = set(X_train.columns) - set(X_test.columns)
for c in missing_cols:
X_test[c] = 0
missing_cols = set(X_test.columns) - set(X_train.columns)
for c in missing_cols:
X_train[c] = 0
# Train Random Forest Regressor
model = RandomForestRegressor(random_state=42) #Added random_state for reproducibility
model.fit(X_train, y_train)
# Predict and evaluate
predictions = model.predict(X_test)
mae = mean_absolute_error(y_test, predictions)
print(f"Mean Absolute Error: {mae}")
# Create DataFrame with predictions and actual values
df_results = pd.DataFrame({'Actual': y_test, 'Predicted': predictions})
# Save the model
joblib.dump(model, 'random_company_model.pkl')
return model, mae, df_results
except Exception as e:
print(f"An error occurred: {e}")
return None, None, None
# Example usage: Replace with your actual connection string and table name.
db_connection_string = 'mysql+pymysql://your_username:your_password@localhost/your_database_name'
table_name = 'sales_data'
model, mae, df_results = train_and_evaluate_model(db_connection_string, table_name)
if df_results is not None:
print(df_results)
此改进后的代码包含:
- 错误处理:使用
try-except 代码块捕获数据库连接、数据加载和模型训练期间的潜在错误。提供有用的信息性错误消息。
- 输入验证:检查
limit 和 train_size 的有效输入类型和值。
- 稳健性:在数字列的类型转换期间处理潜在的
ValueError 异常。
- 可重复性:使用
RandomForestRegressor 中的 random_state 以获得一致的结果。
- One-Hot 编码:使用
pd.get_dummies 处理分类特征(假设“region”是分类特征)。解决了单热编码后列不匹配的潜在问题。
- 更清晰的函数结构:将整个流程封装在函数中,以便更好地进行组织和提高可重用性。
- 信息输出:返回经过训练的模型、MAE 以及预测结果的 DataFrame,以便进行更全面的评估。
请务必将 "mysql+pymysql://username:password@localhost/database_name" 和 'sales_data' 替换为您的实际 MySQL 连接字符串和表名称。您还需要安装必要的库:pandas 、scikit-learn 、pymysql 和 joblib 。使用 pip 安装它们:pip install pandas scikit-learn pymysql joblib
|
型号: |
gemini-1.5-flash-002 |
温度: |
0.2 |
输出令牌数量上限: |
8192 |
TopK: |
40.0 |
TopP: |
0.95 |
|