我意外地注意到,当不适合拦截时,OLS模型由R ^ 2 实现sklearn并statsmodels产生不同的R ^ 2值.否则他们似乎工作正常.以下代码产生:
import numpy as np
import sklearn
import statsmodels
import sklearn.linear_model as sl
import statsmodels.api as sm
np.random.seed(42)
N=1000
X = np.random.normal(loc=1, size=(N, 1))
Y = 2 * X.flatten() + 4 + np.random.normal(size=N)
sklernIntercept=sl.LinearRegression(fit_intercept=True).fit(X, Y)
sklernNoIntercept=sl.LinearRegression(fit_intercept=False).fit(X, Y)
statsmodelsIntercept = sm.OLS(Y, sm.add_constant(X))
statsmodelsNoIntercept = sm.OLS(Y, X)
print(sklernIntercept.score(X, Y), statsmodelsIntercept.fit().rsquared)
print(sklernNoIntercept.score(X, Y), statsmodelsNoIntercept.fit().rsquared)
print(sklearn.__version__, statsmodels.__version__)
Run Code Online (Sandbox Code Playgroud)
打印:
0.78741906105 0.78741906105
-0.950825182861 0.783154483028
0.19.1 0.8.0
Run Code Online (Sandbox Code Playgroud)
差异来自哪里?
问题不同于不同的线性回归系数与statsmodels和sklearn,因为那里sklearn.linear_model.LinearModel(有截距)适合X准备的statsmodels.api.OLS.
问题不同于 Statsmodels:计算拟合值和R平方, 因为它解决了两个Python包( …
python linear-regression python-3.x scikit-learn statsmodels
我必须将矩阵相乘A(100x8000),B(8000x27)和C(27x1)。
由于矩阵B和C是常数并且A是可变的,因此我更喜欢将其计算为:ABC = np.dot(A, np.dot(B, C))。但是我不知道,它可能是数值恶化(在以下方面准确性)比np.dot(np.dot(a, B), C)。
可能重要的是:矩阵A并B包含8000个分别(分别)100个和27个相关特征的样本。
乘法在数值上(在精度上)是否最优?如果是,我该如何确定?
可以假定A和B矩阵都是非负的。此外:
C = np.linalg.solve(cov(B, k), X)
Run Code Online (Sandbox Code Playgroud)
其中X是27x1矩阵,其中包含27个(可能是相关的)未知分布的随机变量cov = lambda X, k: np.dot(X.T, X) + k * np.eye(X.shape[1]),并且k是将表达式最小化的非负常数:
sum((X[i, 0] - np.dot(np.dot(B[:, [i]].T, drop(B, i)),
np.linalg.solve(cov(drop(B, i), k),
np.delete(X, …Run Code Online (Sandbox Code Playgroud) python numpy floating-accuracy numerical-methods matrix-multiplication
是否有与以下功能等效的标准库/ numpy:
def augmented_assignment_sum(iterable, start=0):
for n in iterable:
start += n
return start
Run Code Online (Sandbox Code Playgroud)
?
虽然sum(ITERABLE)非常优雅,但它使用+operator代替+=,如果出现np.ndarray对象,这可能会影响性能。
我已经测试过,我的功能可能和它一样快sum()(而使用它的等效+速度要慢得多)。由于它是纯Python函数,因此我认为它的性能仍然受到限制,因此我正在寻找一些替代方法:
In [49]: ARRAYS = [np.random.random((1000000)) for _ in range(100)]
In [50]: def not_augmented_assignment_sum(iterable, start=0):
...: for n in iterable:
...: start = start + n
...: return start
...:
In [51]: %timeit not_augmented_assignment_sum(ARRAYS)
63.6 ms ± 8.88 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
In …Run Code Online (Sandbox Code Playgroud) python performance numpy standard-library augmented-assignment
在Snakemake中,我有 5 条规则。对于每个选项,我都设置了内存限制resources mem_mb。它看起来像这样:
rule assembly:
input:
file1 = os.path.join(MAIN_DIR, "1.txt"), \
file2 = os.path.join(MAIN_DIR, "2.txt"), \
file3 = os.path.join(MAIN_DIR, "3.txt")
output:
foldr = dir, \
file4 = os.path.join(dir, "A.png"), \
file5 = os.path.join(dir, "A.tsv")
resources:
mem_mb=100000
shell:
" pythonscript.py -i {input.file1} -v {input.file2} -q {input.file3} --cores 5 -o {output.foldr} "
Run Code Online (Sandbox Code Playgroud)
Snakefile我想通过执行以下操作来限制整体的内存使用:
snakamake --snakefile mysnakefile_snakefile --resources mem_mb=100000
Run Code Online (Sandbox Code Playgroud)
因此,并非所有作业都会使用100GB每个作业(如果我有 5 个规则,即500GB内存分配),但它们的所有执行都将是最大的100GB(5 个作业,100 GB分配总数?)
有一段时间我收到以下错误(警告?):
错误!会话/行号在数据库中不是唯一的.历史记录日志已移至新会话
使用Jupyter笔记本时(<XXXX>是一个数字,例如9149).由于Spyder报告了相同的错误(Spyder的警告:"会话/行号在数据库中不是唯一的"),我的猜测是IPython内核日志记录存在一些问题.
问题是:运行我的代码和错误之间可能有任何关系吗?
错误是否可能是由我的代码引起的?我触摸IPython API如下:
import IPython
def beep():
Python.display.display(IPython.display.Audio(url="http://www.w3schools.com/html/horse.ogg", autoplay=True))
def play_sound(self, etype, value, tb, tb_offset=None):
self.showtraceback((etype, value, tb), tb_offset=tb_offset)
beep()
get_ipython().set_custom_exc((Exception,), play_sound)
Run Code Online (Sandbox Code Playgroud)
我beep()在我的代码中使用该函数.我还处理大数据,导致MemoryError异常.
更重要的是,错误可能会影响我的代码行为(假设我不尝试访问日志)?
[编辑]似乎问题不同于Spyder的警告:"会话/行号在数据库中不是唯一的",因为我能够用Jupyter Notebook重现它,但不能用Spyder重现它.
我有一个带有重载比较运算符的int派生类.
在重载方法的主体中,我需要使用原始运算符.
玩具示例:
>>> class Derived(int):
... def __eq__(self, other):
... return super(Derived, self).__eq__(other)
Run Code Online (Sandbox Code Playgroud)
使用Python 3.3+可以正常工作,但是在Python 2.7中有例外AttributeError: 'super' object has no attribute '__eq__'.
我可以考虑几个walkarrounds,我觉得不是很干净:
return int(self) == other
Run Code Online (Sandbox Code Playgroud)
需要创建一个新int对象,只是为了比较它
try:
return super(Derived, self).__eq__(other)
except AttributeError:
return super(Derived, self).__cmp__(other) == 0
Run Code Online (Sandbox Code Playgroud)
基于Python版本拆分控制流,我觉得非常混乱(因此明确地检查Python版本).
如何使用Python 2.7和3.3+以优雅的方式访问原始整数比较?
python inheritance operator-overloading comparison-operators python-2.7
规范方法(使用np.vectorize())在空数组的情况下不起作用 - 它以以下结尾IndexError: index 0 is out of bounds for axis 0 with size 0:
>>> def f(x):
... return x + 1
...
>>> F = np.vectorize(f)
>>> F(np.array([]))
[Traceback removed]
IndexError: index 0 is out of bounds for axis 0 with size 0
Run Code Online (Sandbox Code Playgroud)
目前我使用
>>> np.array([f(x) for x in X])
Run Code Online (Sandbox Code Playgroud)
但我正在寻找更优雅的解决方案(和高效).在Python 2中,我可以选择
>>> np.array(map(f, X))
Run Code Online (Sandbox Code Playgroud)
但它在Python 3中失败了.
[编辑]
问题在NumPy阵列的每个单元的函数的有效评估中没有答案,因为:
vectorise 失败,A(i, j) := f(A(i, j)).我需要将大量 (1 440 000 000) 行附加到pandas.DataFrame.
我预先知道行数,因此我可以预先分配它,然后以类似于 C 的方式填充数据。
到目前为止,我最好的想法是相当丑陋的:
>>> N = 1000000
>>> sham = [-1] * (N * len(THRESHOLDS) * len(OBJECTS)) # 1440000000
>>> DATA = pd.DataFrame({'threshold': pd.Categorical(sham, categories=THRESHOLDS, ordered=True),
... 'expected': pd.Series(sham, dtype=np.float16),
... 'iteration': pd.Series(sham, dtype=np.int32),
... 'analyser': pd.Categorical(sham, categories=ANALYSERS),
... 'object': pd.Categorical(sham, categories=OBJECTS),
... },
... columns=['threshold', 'expected', 'iteration', 'analyser', 'object'])
>>> ptr = 0
>>> for t in THRESHOLDS:
... for o in OBJECTS:
... for a in ANALYSERS:
... for …Run Code Online (Sandbox Code Playgroud) 我正在开发一个包含Cython扩展的软件包。
根据https://github.com/pypa/pip/issues/1958,我将使用setup_requires并推迟的导入Cython。我想出的最好的解决方案是致电setup()两次setup.py:
... # initial imports
setup(setup_requires=['cython'])
from Cython.Build import cythonize
bar = Extension('foo.bar', sources = ['bar.pyx'])
setup(name = 'foo',
... # parameters
ext_modules = cythonize([bar]),
... # more parameters
)
Run Code Online (Sandbox Code Playgroud)
但是我有一种感觉,setup()建议的名称只能被调用一次。像我一样多次叫它安全吗?
我不能只分发轮子,因为该软件包也将对Linux用户可用。
[编辑]
我也认为这个问题比处理编译器依赖性更为笼统。可能需要导入一些软件包(例如sphinx或pweave)来预处理一个软件包的描述。
偶然我注意到,这两个csv和rePython标准库的模块有自己的.__version__属性:
>>> import re, csv
>>> re.__version__
'2.2.1'
>>> csv.__version__
'1.0'
Run Code Online (Sandbox Code Playgroud)
令我感到惊讶的是,因为它们是标准库的一部分,所以我希望它们的版本由sys.version(和sys.version_info)定义.
我注意到Python 2.7.13和3.6.1的属性值是相同的,尽管模块已经改变.
它们只是一种"代码化石"还是它们在某种程度上是有意义的,程序员应该关注它们的价值观?
python ×9
python-3.x ×6
python-2.7 ×5
numpy ×3
dataframe ×1
distutils ×1
inheritance ×1
ipython ×1
memory ×1
pandas ×1
performance ×1
resources ×1
scikit-learn ×1
setuptools ×1
snakemake ×1
statsmodels ×1
version ×1