如何在Python的Statsmodels中检索拟合数据的建模函数?
Hey there! Let's clear this up for you—Statsmodels doesn't expose a standalone f() function for your model, but the fitted OLS object already contains everything you need to compute that f(X)=Y mapping, and it's easy to access or wrap into a function of your own.
How to get your f(X) mapping from the fitted OLS model
First, remember that when you fit an OLS model with Statsmodels, you're estimating a linear function:
f(X) = β₀ + β₁X₁ + β₂X₂ + ... + βₖXₖ
where β₀ is the intercept, and β₁ to βₖ are the coefficients for your features.
1. Access the model coefficients directly
Once you've fitted your model like this:
import statsmodels.api as sm # Assume X is your feature matrix, y is your target variable X_with_intercept = sm.add_constant(X) # Add intercept term (critical for OLS!) model = sm.OLS(y, X_with_intercept).fit()
You can get all the β values from model.params—this is a Series where the first entry is β₀ (intercept), followed by coefficients for each feature in your X matrix.
2. Compute f(X) using predict()
The easiest way to calculate f(X) for new or existing data is to use the model's built-in predict() method:
# For your original X (with intercept) y_pred = model.predict(X_with_intercept) # For new data X_new (make sure to add the intercept if you didn't include it in training!) X_new_with_intercept = sm.add_constant(X_new) y_new_pred = model.predict(X_new_with_intercept)
This is exactly equivalent to evaluating your f(X) function.
3. Wrap it into a custom f() function if you want
If you really want a standalone function named f, you can wrap the predict logic like this:
def f(X_input): # Add intercept if your training data included it (which it should for OLS) X_input_with_intercept = sm.add_constant(X_input, has_constant='add') return model.predict(X_input_with_intercept)
Now you can call f(X) directly to get your predicted Y values.
Why you won't find a named f() in the docs
Statsmodels designs its models as objects that hold all the model information (coefficients, residuals, summary stats, etc.) rather than exposing a single function. The predict() method is the official way to compute the model's output for any input X, which is exactly what you're looking for when you say f(X)=Y.
内容的提问来源于stack exchange,提问作者Bilbo




