【问题标题】:MatLab regression in PythonPython 中的 MatLab 回归
【发布时间】:2021-06-07 07:39:08
【问题描述】:

我有一些关于使用蒙特卡罗模拟和 OLS 回归来估计一些系数的 Matlab 代码。 在 Python 中怎么可能做到这一点?

see screenshot of code, or below

Define the true DGP parameters and distributions
% Set the parameters in the model
b1 = 5;
b2 = -2;
% The variance of the error term
sigma2 = 2;
% The sample length. We will play with three different sample sizes and see how this affects the results 
N = [100 500 1000];
% The number of simulations
S = 1000;
Generate x data
% Generate the x values as draws from the multivariate normal distributions
% This is the correlation structure between the x's
Sigma   = [0.7 0.4;
            0.4 0.3];
% Simple way of drawing random numbers from the multivariate normal distribution        
x       = chol(Sigma)'*randn(2,max(N));    
% Make the x1 and x2 variables
x1      = x(1,:)';
x2      = x(2,:)';
Monte Carlo simulation 1
y = b1*x1 + e is the true model 
We will now simulate data from this model and then use OLS to estimate two versions of the model: 
y = b1mc*x1 + e and 
y = b1mc_2*x1 + b2*x2 + e 
% Always good practive to allocate empty output before loops
b1mc    = nan(S, numel(N));
b1mc_2  = nan(S, numel(N));
% Simple counter to use when allocating results into b1mc below
cnt  = 1;
for n = N % Loop over the different sample sizes N
    for s = 1 : S
        % generate random errors
        u = randn(n,1)*sqrt(sigma2);    
        % simulate the process
        y = b1*x1(1:n) + u;           
        % Estimate coefficients by OLS (easy in Matlab) and save
        b1mc(s,cnt)     = x1(1:n)\y; 
        tmp             = [x1(1:n) x2(1:n)]\y;                                
        b1mc_2(s,cnt)   = tmp(1); % Only save the first parameter
    end
    cnt = cnt + 1;
end

【问题讨论】:

  • 嘿,从你的问题中不清楚你在问什么,你在 python 中缺少哪些功能,而你在 matlab 中有哪些功能?你想做最小二乘回归吗?如果有,试试this,sklearn有很多预测工具
  • 嗨!我想知道如何在 Python 中进行与 Matlab 命令 x1(1:n)\y 类似的回归
  • 你能帮我吗,告诉我\在matlab中做了什么?自从我使用它以来已经有一段时间了。和使用的here一样吗?
  • 表示回归!因此它以 x1 作为预测变量对 y 进行回归。
  • 欢迎来到 Stack Overflow!请使用tour、阅读what's on-topic hereHow to Askquestion checklist,并提供minimal reproducible example。 “为我实现此功能”与此站点无关。你必须诚实地尝试,然后就你的算法或技术提出一个具体问题

标签: python matlab regression montecarlo


【解决方案1】:

有一些方法可以在 python 中使用 MATLAB 代码!!..查看下面的链接

[检查这个]A tool to convert MATLAB code to Python

【讨论】:

  • 答案不应该只是指向 Stack Overflow 上其他帖子的链接。如果您认为适用,您应该将问题标记为重复。请阅读How to Answer 并使用tour。欢迎来到 SO!
猜你喜欢
  • 2020-09-10
  • 2011-10-11
  • 2016-10-21
  • 2013-11-17
  • 2012-06-06
  • 2012-03-17
  • 1970-01-01
  • 2018-04-25
  • 2016-07-11
相关资源
最近更新 更多