小编Eli*_*igo的帖子

Python:以函数式编程风格编写文件

我们应该如何用 Python 编写文件,同时保持功能纯粹?通常我会做这样的事情

from typing import Iterable
from io import IOBase


def transform_input(input_lines: Iterable[str]) -> Iterable[str]: ...


def print_pack(input_lines: Iterable[str], output: IOBase) -> None:
    for line in input_lines:
        print(line, file=output)


def main(*args, **kwargs):
    # Somehow we get a bunch iterables with strings and a list of output streams
    packs_of_input = ... # Iterable[Iterable[str]]
    output_streams = ... # Iterable[IOBase]
    packs_to_print = map(transform_input, packs_of_input)
    for pack, output_stream in zip(packs_to_print, output_streams):
        print_pack(pack, output_stream)
Run Code Online (Sandbox Code Playgroud)

我们可以for用这样的东西替换 -loop

list(map(lambda pack_stream: print_pack(*pack_stream), zip(packs_to_print, output_streams))
Run Code Online (Sandbox Code Playgroud)

但这只会让打印看起来像是功能性完成的。问题是这 …

python io functional-programming python-3.x

5
推荐指数
1
解决办法
1727
查看次数

在 setup.py 中为 PyPI 中的模块指定依赖 url

到目前为止,我在这里看到的问题处理相反的情况,即提供指向 off-PyPI 依赖项的链接。就我而言,依赖项是在 PyPI 中发布的,但版本不符合我的要求。这是我的摘录setup.py

setup(
    ...
    install_requires=["numpy>=1.11.0",
                      "scipy>=0.17.0",
                      "lasagne",
                      "Theano>=0.8.1",
                      "scipy>=0.17.0"],

    dependency_links=["git+https://github.com/Lasagne/Lasagne.git#egg=lasagne"]
)
Run Code Online (Sandbox Code Playgroud)

我需要lasagne从链接安装,同时pip坚持安装PyPI版本。

编辑。我试过这样做

setup(
    ...
    install_requires=["numpy>=1.11.0",
                      "scipy>=0.17.0",
                      "lasagne>=0.2.dev1",
                      "Theano>=0.8.1",
                      "scipy>=0.17.0"],

    dependency_links=[
        "git+https://github.com/Lasagne/Lasagne.git#egg=lasagne-0.2.dev1"]
)
Run Code Online (Sandbox Code Playgroud)

这导致 Could not find a version that satisfies the requirement lasagne>=0.2.dev1

编辑2

实际上通过此处--process-dependency-links所示的标志(感谢 Nehal J. Wani)使其工作。我怎样才能让这个标志默认工作?我不希望用户感到困惑。

python pip setuptools pypi setup.py

5
推荐指数
0
解决办法
1004
查看次数

__slots__ 与泛型类中的类变量冲突

我在 Python 的类型系统和__slots__. 这是一个可重现的小示例。

from typing import TypeVar, Generic, Sequence

T = TypeVar("T")

class TestGeneric(Sequence, Generic[T]):
    __slots__ = ("test",)

    def __init__(self, test: T):
        self.test = [test]

    def __iter__(self):
        return iter(self.test)
    def __len__(self):
        return len(self.test)

    def __contains__(self, item):
        return item in self.test

    def __getitem__(self, _):
        return self.test[0]
Run Code Online (Sandbox Code Playgroud)

现在每当我尝试指定内容类型时,例如

V = TestGeneric[int]
Run Code Online (Sandbox Code Playgroud)

我得到

ValueError: 'test' in __slots__ conflicts with class variable
Run Code Online (Sandbox Code Playgroud)

Generics 在没有插槽的类中使用了很多,因此我认为这个错误必须与__slots__. 此外,同一个类工作正常,如果你删除__slots__

python typing slots python-3.x python-3.5

5
推荐指数
1
解决办法
3567
查看次数

具有导入功能的Python多处理池

使用Windows和python 3.6后,一旦导入要映射的函数,就无法进行多重处理。该代码有效(给出输出[2,12,30,56,90]):

from multiprocessing import Pool
def f(x,y):
    return x*y

if __name__ == '__main__':
    args=[(1,2),(3,4),(5,6),(7,8),(9,10)]
    with Pool(4) as p:
        result=p.starmap(f,args)
    print(result)
Run Code Online (Sandbox Code Playgroud)

现在,我将函数f移到另一个名为“ test”的.py文件中,然后将其导入:

from multiprocessing import Pool
from test import f    

if __name__ == '__main__':
    args=[(1,2),(3,4),(5,6),(7,8),(9,10)]
    with Pool(4) as p:
        result=p.starmap(f,args)
    print(result)
Run Code Online (Sandbox Code Playgroud)

与test.py只包含:

def f(x,y):
    return x*y
Run Code Online (Sandbox Code Playgroud)

运行它会导致无限循环(不会返回任何CPU使用率很高的内容)。

是什么原因造成的,有没有办法解决?通过将所有代码复制到一个巨大的.py中,我已经成功地使多处理程序可以在一个程序上工作,这显然不理想。

python windows python-3.x python-multiprocessing

5
推荐指数
0
解决办法
103
查看次数

在特征向量中计算多个缺失值

编辑过的帖子

这是原帖的简短版本.

  1. 我们有一个训练数据集(一些特征显着相关).特征空间有20个维度(全部是连续的).
  2. 我们需要使用训练数据训练非参数(大多数特征形成非线性子空间,我们不能假设其中任何一个的分布)imputer(kNN或基于树的回归).
  3. 我们需要使用训练过的计算机预测查询数据中的多个缺失值(查询特征向量最多可以有13个缺失的特征,因此计算机应该处理缺失特征的任何组合).注:该imputer不应该在任何重新训练方式/安装使用查询数据(就像是在目前为止,我发现所有的主流R封装完成的:Amelia,impute,mimice...).这就是归因应该完全基于训练数据.
  4. 所有这些的目的描述如下.
  5. 下面是一个小数据样本.

原帖(TL; DR)

简而言之,我有一些复杂的数据可以做.我们有一个~100k 20D样本的训练数据集和一个较小的测试数据集.每个要素/维度都是连续变量,但比例不同.有两个不同的类.两个数据集都是非常NA膨胀的(NAs在维度上不是均匀分布的).我sklearn.ensemble.ExtraTreesClassifier用于分类,虽然树集合可以处理丢失的数据案例,但有三个理由可以进行估算

  1. 通过这种方式,我们可以在查询数据集的分类过程中从森林中的所有树获得投票(而不仅仅是那些没有缺失特征/功能的投票).
  2. 我们在培训期间不会丢失数据.
  3. scikit树集合(都ExtraTreesRandomForest)的实现不处理缺失值.但这一点并不重要.如果它不是前两个我会使用rpy2+一些不错的R实现.

训练数据集的情况非常简单,因为我可以应用特定于类的中位插补策略​​来处理缺失值,这种方法到目前为止一直运行良好.显然,这种方法不能应用于查询 - 我们没有开始的类.由于我们知道类可能在查询中具有显着不同的份额,因此我们无法应用类无关紧要的方法,因为这可能会引入偏差并降低分类性能,因此我们需要从模型中计算缺失值.

由于以下几个原因,线性模型不是一种选择:

  1. 所有特征都在某种程度上相关;
  2. 从理论上讲,我们可以在样本特征向量中获得所有可能的缺失特征组合,即使我们的工具需要至少7个非缺失特征,我们最终得到~1 ^ E6可能的模型,如果你问的话,这看起来不是很优雅我.

基于树的回归模型出于同样的原因并不好.因此我们最终选择kNN(k个最近邻居),球树或具有半径阈值的LSH更具体.这种方法非常适合这项任务,因为维度(ergo距离)是相关的,因此我们在极其NA的情况下获得了良好的性能,但有几个缺点:

  1. 我还没有发现在Python单个实现(包括impute,sklearn.preprocessing.Imputer,orange),处理功能的载体配合多套不同缺失值的,这是我们希望有一个只为缺失的功能所有可能的组合imputer.
  2. kNN使用成对点距离进行预测/插补.正如我已经提到的,我们的变量具有不同的尺度,因此在距离估计之前必须对特征空间进行归一化.我们需要知道每个维度的理论最大/最小值才能正确地进行缩放.这不是一个问题,因为这是一个建筑简单的问题(用户必须提供最小/最大值的向量).

以下是我想听到您的意见:

  1. 有没有经典的方法来解决上面列表中给出的与kNN相关的问题?我相信这一定是一个常见的案例,但我没有在网上找到任何具体内容.
  2. 在我们的案例中是否有更好的方法来估算数据?你会推荐什么?请提供Python实现(R和C/C++也被考虑).

数据

以下是训练数据集的一小部分示例.我减少了功能的数量,使其更具可读性.查询数据具有相同的结构,除了明显缺少category信息.

v1  v2  v3  v4  v5  category
0.40524 0.71542 NA  0.81033 0.8209  1
0.78421 0.76378 0.84324 0.58814 0.9348  2
0.30055 NA  0.84324 NA  0.60003 …
Run Code Online (Sandbox Code Playgroud)

python r machine-learning missing-data

4
推荐指数
1
解决办法
4169
查看次数

释放一个等于 malloc 指针的指针

我无法理解一些 free() 行为。

int* ptr1 = (int*)malloc(sizeof (int)*10);
int* ptr2 = ptr1;
free(ptr2);
Run Code Online (Sandbox Code Playgroud)

是否free(ptr2)要按我的意愿删除我的数组?

如果我这样做怎么办:

int** ptr1 = (int**)malloc(sizeof (int)*10);
int* ptr2 = (int*)malloc(sizeof (int));
*ptr2 = 10;
ptr1[0] = ptr2;
free(ptr1);
Run Code Online (Sandbox Code Playgroud)

这段代码正确吗?会free(ptr1)也将删除PTR2的空间?

谢谢

c

4
推荐指数
2
解决办法
3539
查看次数

requests.get返回403,而相同的URL在浏览器中工作

我正在尝试使用rlsnet.ru上的搜索表单.这是我从源文件中提取的表单定义:

<form id="site_search_form" action="/search_result.htm" method="get">
    <input id="simplesearch_text_input" class="search__field" type="text" name="word" value="" autocomplete="off">
    <input type="hidden" name="path" value="/" id="path">
    <input type="hidden" name="enter_clicked" value="1">
    <input id="letters_id" type="hidden" name="letters" value="">
    <input type="submit" class="g-btn search__btn" value="?????" id="simplesearch_button">
    <div class="sf_suggestion">
        <ul style="display: none; z-index:1000; opacity:0.85;">
        </ul>
    </div>
    <div id="contentsf">
    </div>
</form>
Run Code Online (Sandbox Code Playgroud)

这是我用来发送搜索请求的代码:

import requests
from urllib.parse import urlencode 

root = "http://www.rlsnet.ru/search_result.htm?"
response = requests.get(root + urlencode({"word": "????????????".encode('cp1251')})
Run Code Online (Sandbox Code Playgroud)

每次我这样做,响应状态为403.当我在http://www.rlsnet.ru/search_result.htm?word=%D6%E5%F0%E5%E1%F0%EE%EB%E8%E7%E8%EDSafari/Chrome/Opera中输入相同的请求URL(即)时,它可以正常工作并返回预期的页面.我究竟做错了什么?谷歌搜索问题只带来了这个问题:为什么网址在浏览器中工作,但没有使用请求获取方法,这没什么用处.

python unicode python-3.x python-requests

4
推荐指数
1
解决办法
6272
查看次数

CNN模型中的内核权重初始化在哪里?

我正在使用make_unet这里调用的卷积神经网络(CNN)。它可以工作,并且代码可以与此CNN一起运行。但是我知道在深度学习中,您必须初始化权重以优化神经网络。

Keras中的文档明确指出了kernel_initializer权重初始化的使用。但是,我kernel_initializer在使用的make_unet功能中看不到任何东西。

任何能够提供一些见识的人将不胜感激。

python machine-learning deep-learning conv-neural-network keras

4
推荐指数
1
解决办法
1026
查看次数

测试字符串中“ x”或“ y”的正确方法?

因此,我想在Python(3.7)中演示一个简单的if语句。我最终写了一个简单的代码(v1_alt.1)。

v1_alt.1可以按预期工作,我认为它很容易演示if语句如何工作。我也想评估前。“深绿色”为“真”。

但是我觉得它应该写得有些不同。因此,我最终测试了不同的代码。我最终以不同的方法来证明什么是行得通的,而不是行之有效的。但是我有问题理解它,为什么。

### v1
color = input("v1 - What is my favourite color? ") # ex. dark green

# alt.1 - Working code. Accept ex. 'dark green'.
if "red" in color or "green" in color:
    print(f"You entered {color}. That is is one of my favourite colors! "
          "(v1_alt.1)")

# alt.2 - Not working code. Will always evaluate True (Why?)
if "red" or "green" in color:
    print(f"You entered {color}. That is is one of my favourite colors! "
          "(v1_alt.2)")

# …
Run Code Online (Sandbox Code Playgroud)

python python-3.x

2
推荐指数
1
解决办法
81
查看次数

Python中的长数哈希复杂性

Python如何散列长数?我想32位整数需要O(1)时间,但长整数在Python中工作的方式让我觉得复杂性不是O(1).我在相关问题中寻找答案,但没有发现任何直截了当的问题让我充满信心.先感谢您.

python hash time-complexity

1
推荐指数
1
解决办法
187
查看次数

Rcpp R向量大小限制(不允许负长度向量)

根据/sf/answers/3407347261//sf/answers/366400541/ R 向量仅限于 2^31 - 1 项。但是,我已经能够通过 Rcpp 在该数字的一半处触发“不允许负长度向量”错误(这应该是尝试分配过大向量的标志)。这一切都来自我尝试调试基于 Rcpp 的 R 包(https://github.com/tpq/propr/issues/13)。

library(Rcpp)

cppFunction("
IntegerVector test(int size) {
    int veclen = size * (size - 1) / 2;
    IntegerVector vec(veclen);
    return vec;
}
")

vec <- test(47000)
Error in test(47000) : negative length vectors are not allowed
Run Code Online (Sandbox Code Playgroud)

47000^2 / 2 几乎是 2^31 的一半。我在纯 R 中没有遇到这样的问题,vec <- 1:(47000*(47000-1)/2)运行得很好,所以 Rcpp 应该有一些特别的东西。

r rcpp

1
推荐指数
1
解决办法
543
查看次数

Python回文程序不起作用

我在python中写了一个简单的程序,检查句子是否是回文.但我无法弄清楚为什么它不起作用.结果总是错误的.有谁知道什么是错的?

def isPalindrome(word):
    # Removes all spaces, and lowercase the word.
    word = word.strip().lower()
    word = word.replace(" ", "")

    # If the length of the word is less than 1, means its a palindrome
    if (len(word) <= 1):
        return True

    # Compares the first and the last character of the word.
    # If it is the same, calls the function again with the same word,
    # without its first and last characters. If its not the same, its
    # not …
Run Code Online (Sandbox Code Playgroud)

python recursion palindrome

0
推荐指数
2
解决办法
679
查看次数

Python:如何限制一行打印的整数?

在执行以下操作时,我怎么能够打印每行只说10个数字:

for a in range(100 , 201):
    print(a , end=" ")
Run Code Online (Sandbox Code Playgroud)

这样做会给

100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 …
Run Code Online (Sandbox Code Playgroud)

python python-3.x

-3
推荐指数
1
解决办法
1062
查看次数