如何使用pymc3包创建独立的python可执行文件?

2024-03-28 08:49:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我用python创建了一个数学模型。我想为我的模型制作一个独立的python可执行文件。python脚本使用了几个python库,比如numpy、pandas、pymc3。我尝试使用pyinstaller和auto-py-to-exe制作python可执行文件。在这两种情况下,它都无法创建可执行文件。导入pymc3模块(theano库)时出错。我的主要模型依赖于pymc3模块。我不能绕过这个模块。有人能帮我解决这个问题吗?你知道吗

这是我执行.exe文件时收到的错误消息

WARNING (theano.tensor.blas): Using NumPy C-API based implementation for BLAS functions.
c:\python\lib\site-packages\PyInstaller\loader\pyimod03_importers.py:621: MatplotlibDeprecationWarning:
The MATPLOTLIBDATA environment variable was deprecated in Matplotlib 3.1 and will be removed in 3.3.
  exec(bytecode, module.__dict__)
Traceback (most recent call last):
  File "sample.py", line 46, in <module>
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
  File "c:\python\lib\site-packages\PyInstaller\loader\pyimod03_importers.py", line 621, in exec_module
    exec(bytecode, module.__dict__)
  File "site-packages\pymc3\__init__.py", line 11, in <module>
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
  File "c:\python\lib\site-packages\PyInstaller\loader\pyimod03_importers.py", line 621, in exec_module
    exec(bytecode, module.__dict__)
  File "site-packages\pymc3\stats.py", line 20, in <module>
  File "site-packages\pkg_resources\__init__.py", line 481, in get_distribution
  File "site-packages\pkg_resources\__init__.py", line 357, in get_provider
  File "site-packages\pkg_resources\__init__.py", line 900, in require
  File "site-packages\pkg_resources\__init__.py", line 786, in resolve
pkg_resources.DistributionNotFound: The 'scipy' distribution was not found and is required by the application
[13796] Failed to execute script sample

这是python脚本

class modelFit:
    # Initialises the attributes
    def __init__(self, x, y):
        self.x = x
        self.y = y

    # Performs the Bayes estimation
    def coeffEstimation(self):
        X = np.array(self.x)
        Y = np.array(self.y)

        with pm.Model() as linearRegModel:
            # Define priors
            #regCoeff = pm.HalfNormal('regCoeff', sd = 20, shape=X.shape[1])
            regCoeff = pm.Uniform('regCoeff', lower = 0, upper = 100, shape=X.shape[1])

            # Standard deviation
            sigma = pm.HalfNormal('sigma', sd = 5)

            # Estimate of mean
            mean = pm.math.dot(X, regCoeff)

            # Likelihood estimate
            likelihood = pm.Normal('Y_estimated', mu = mean, sd = sigma, observed = Y)

            # Sampler
            step = pm.NUTS()

            # Posterior distribution
            linearTrace = pm.sample(draws = 500, chains = 1,
                                    tune = 500, nuts_kwargs=dict(target_accept=0.95))

        with open('Summary.txt', 'w') as f:
            print(pm.summary(linearTrace).round(3), file=f)
            diverging = linearTrace['diverging']
            print('Number of Divergent Chains: {}'.format(diverging.nonzero()[0].size), file=f)
            divergingPer = diverging.nonzero()[0].size / len(linearTrace) * 100
            print('Percentage of Divergent Chains: {:.1f}'.format(divergingPer), file=f)

        print('Bayesian Inference Done! Exporting the results, Please hold on!')
        return(linearTrace)


import theano.tensor.shared_randomstreams
import scipy
import pymc3 as pm
import numpy as np
import pandas as pd
dataLocation = './input/'
inputData = pd.read_excel(dataLocation + 'input.xlsx')
sizeInputData = inputData.shape
x = inputData.iloc[:,1:sizeInputData[1]]
y = inputData.iloc[:,0]


# Executes the Bayes method
linReg = modelFit(x, y)
regTrace = linReg.coeffEstimation()

Tags: andinpyinitpackageslinesiteload