小编Aka*_*all的帖子

使用具有稀疏和密集矩阵的sklearn RandomizedPCA时的不同结果

Randomized PCA使用稀疏和密集矩阵时,我得到的结果不同:

import numpy as np
import scipy.sparse as scsp
from sklearn.decomposition import RandomizedPCA

x = np.matrix([[1,2,3,2,0,0,0,0],
               [2,3,1,0,0,0,0,3],
               [1,0,0,0,2,3,2,0],
               [3,0,0,0,4,5,6,0],
               [0,0,4,0,0,5,6,7],
               [0,6,4,5,6,0,0,0],
               [7,0,5,0,7,9,0,0]])

csr_x = scsp.csr_matrix(x)

s_pca = RandomizedPCA(n_components=2)
s_pca_scores = s_pca.fit_transform(csr_x)
s_pca_weights = s_pca.explained_variance_ratio_

d_pca = RandomizedPCA(n_components=2)
d_pca_scores = s_pca.fit_transform(x)
d_pca_weights = s_pca.explained_variance_ratio_

print 'sparse matrix scores {}'.format(s_pca_scores)
print 'dense matrix scores {}'.format(d_pca_scores)
print 'sparse matrix weights {}'.format(s_pca_weights)
print 'dense matrix weights {}'.format(d_pca_weights)
Run Code Online (Sandbox Code Playgroud)

结果:

sparse matrix scores [[  1.90912166   2.37266113]
 [  1.98826835   0.67329466]
 [  3.71153199  -1.00492408]
 [  7.76361811 …
Run Code Online (Sandbox Code Playgroud)

python numpy scipy scikit-learn

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

将值列表附加到子列表

如何将一个列表的每个项目附加到另一个列表的每个子列表?

a = [['a','b','c'],['d','e','f'],['g','h','i']]
b = [1,2,3]
Run Code Online (Sandbox Code Playgroud)

结果应该是:

[['a','b','c',1],['d','e','f',2],['g','h','i',3]]
Run Code Online (Sandbox Code Playgroud)

请记住,我想对一个非常大的列表执行此操作,因此效率和速度很重要。

我试过了:

for sublist,value in a,b:
    sublist.append(value)
Run Code Online (Sandbox Code Playgroud)

它返回“ValueError:要解压的值太多”

也许 listindex 或 listiterator 可以工作,但不知道如何在这里应用

python iteration iterator list sublist

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

将两个向量的对转换为相应元素的映射

我想转换std::pair<std::vector<int>, std::vector<double>>std::map<int, double>.

例如:

// I have this:
std::pair<std::vector<int>, std::vector<double>> temp =
                            {{2, 3, 4}, {4.3, 5.1, 6.4}};
// My goal is this:
std::map<int, double> goal = {{2, 4.3}, {3, 5.1}, {4, 6.4}};
Run Code Online (Sandbox Code Playgroud)

我可以通过以下功能实现此目的.但是,我觉得必须有更好的方法来做到这一点.如果是这样的话是什么?

#include <iostream>
#include <vector>
#include <utility>
#include <map>

typedef std::vector<int> vec_i;
typedef std::vector<double> vec_d;

std::map<int, double> pair_to_map(std::pair<vec_i, vec_d> my_pair)
{
    std::map<int, double> my_map;
    for (unsigned i = 0; i < my_pair.first.size(); ++i)
    {
        my_map[my_pair.first[i]] = my_pair.second[i];
    }
    return my_map;
}

int main() …
Run Code Online (Sandbox Code Playgroud)

c++ stl c++11

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

你怎么知道一个数组是否有连续的元素是相同的?

例如,如果我有一个像这样的数组:

arr = ["HI","BYE","BYE","BYE"]
Run Code Online (Sandbox Code Playgroud)

有没有一种方法让我知道数组中有连续的"BYE"?

ruby arrays sorting ruby-on-rails

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

我无法将颜色转义码打印到终端

当我运行这个脚本时:

fn main() {
    // \033[0;31m <- Red
    // \033[0m <- No Color
    println!("\033[0;31mSO\033[0m")
}
Run Code Online (Sandbox Code Playgroud)

我希望得到

SO #in red letters
Run Code Online (Sandbox Code Playgroud)

但是,我得到:

33[0;31mSO33[0m
Run Code Online (Sandbox Code Playgroud)

当我在Go或Python中运行类似的脚本时,我得到了预期的输出.到底是怎么回事?我错过了什么?怎么解决这个问题?

我在用:

$ rustc --version
rustc 1.3.0 (9a92aaf19 2015-09-15)
$ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 14.04.3 LTS
Release:    14.04
Codename:   trusty
Run Code Online (Sandbox Code Playgroud)

linux terminal rust

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

最优雅的方式来计算列表中的整数

我正在寻找最优雅的方式来做到以下几点:

假设我想计算每个整数出现在列表中的次数; 我可以这样做:

x = [1,2,3,2,4,1,2,5,7,2]

dicto = {}

for num in x:
    try:
        dicto[num] = dicto[num] + 1
    except KeyError:
        dicto[num] = 1
Run Code Online (Sandbox Code Playgroud)

但是,我认为

try:
    dicto[num] = dicto[num] + 1
except KeyError:
    dicto[num] = 1
Run Code Online (Sandbox Code Playgroud)

这不是最优雅的方式; 我认为我看到上面的代码被一行代替了.这样做最优雅的方法是什么?

我意识到这可能是重复,但我环顾四周,无法找到我想要的东西.

先感谢您.

python

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

Python中sqlite3的交集

我正在尝试提取与我的两个数据集中存在的库存相对应的数据(在下面的代码中给出).

这是我的数据:

#(stock,price,recommendation)
my_data_1 = [('a',1,'BUY'),('b',2,'SELL'),('c',3,'HOLD'),('d',6,'BUY')]

#(stock,price,volume)
my_data_2 = [('a',1,5),('d',6,6),('e',2,7)]
Run Code Online (Sandbox Code Playgroud)

这是我的问题:

问题1:

我正在尝试提取与资产'a'对应的价格,建议和数量.理想情况下,我想得到这样的元组:

(u'a',1,u'BUY',5)
Run Code Online (Sandbox Code Playgroud)

问题2:

如果我想获得所有股票的交叉点(不仅仅是问题1中的'a'),在这种情况下它是股票'a'和股票'd',那么我想要的输出变成:

(u'a',1,u'BUY',5)
(u'd',6,u'BUY',6)
Run Code Online (Sandbox Code Playgroud)

我该怎么做?

这是我的尝试(问题1):

import sqlite3

my_data_1 = [('a',1,'BUY'),('b',2,'SELL'),('c',3,'HOLD'),('d',6,'BUY')]

my_data_2 = [('a',1,5),('d',6,6),('e',2,7)]

 #I am using :memory: because I want to experiment
 #with the database a lot

conn = sqlite3.connect(':memory:') 

c = conn.cursor()

c.execute('''CREATE TABLE MY_TABLE_1
          (stock TEXT, price REAL, recommendation TEXT )''' )

c.execute('''CREATE TABLE MY_TABLE_2
          (stock TEXT, price REAL, volume REAL )''' )



for ele in my_data_1:
    c.execute('''INSERT INTO MY_TABLE_1 VALUES(?,?,?)''',ele)

for ele …
Run Code Online (Sandbox Code Playgroud)

python sqlite

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

直接从一个频道发送到另一个频道

当我从一个频道直接发送到另一个频道时,我偶然发现了我发现的惊人行为:

package main

import (
    "fmt"
)

func main() {
    my_chan := make(chan string)
    chan_of_chans := make(chan chan string)

    go func() {
        my_chan <- "Hello"
    }()

    go func() {
        chan_of_chans <- my_chan
    }()

    fmt.Println(<- <- chan_of_chans)
}
Run Code Online (Sandbox Code Playgroud)

去游乐场

我期望<- my_chan发送"Hello"类型string.但是,它发送类型chan string,我的代码运行正常.这意味着发送(stringchan string)发送的内容取决于接收器的类型.

我尝试了天真的谷歌搜索,但由于我不熟悉正确的术语,我什么也没想到.是否有与上述行为相关的适当术语?任何额外的见解当然都很棒.

channel go

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

如果存在同名的位置参数,为什么kwargs中的键被丢弃?

我刚遇到这种令我惊讶的行为:

def my_func(a=4, **kwargs):
    print kwargs
Run Code Online (Sandbox Code Playgroud)

演示:

>>> my_func(a=5, b=6)
{'b': 6}  # I was expecting {'a' : 4, 'b' : 6}
          # Maybe {'a' : 5, 'b' : 6}
Run Code Online (Sandbox Code Playgroud)

另外,如果我得到,我不会感到惊讶:

SyntaxError: keyword argument repeated

如在

>>> my_func(a=4, a=5)
  File "<stdin>", line 1
SyntaxError: keyword argument repeated
Run Code Online (Sandbox Code Playgroud)

要么 TypeError: my_func() got multiple values for keyword argument 'a'

如在

>>> my_func(a=4, **{'a' : 5, 'b' : 6})
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: my_func() got …
Run Code Online (Sandbox Code Playgroud)

python kwargs

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

返回指向局部变量的指针时的堆栈行为

我有一个简单的例子,其中Rust的行为与我的心理图像不匹配,所以我想知道我错过了什么:

fn make_local_int_ptr() -> *const i32 {
    let a = 3;
    &a
}

fn main() {
    let my_ptr = make_local_int_ptr();
    println!("{}", unsafe { *my_ptr } );
}
Run Code Online (Sandbox Code Playgroud)

结果:

3
Run Code Online (Sandbox Code Playgroud)

这不是我所期望的.使用堆栈和堆中给出的符号

我希望堆栈框架看起来像这样:

Address | Name | Value
-----------------------
   0    |   a  |   3  
Run Code Online (Sandbox Code Playgroud)

在里面make_local_int_ptr(),但在此之后,

let my_ptr = make_local_int_ptr();
Run Code Online (Sandbox Code Playgroud)

由于a超出范围,我希望堆栈被清除.但它显然没有.

此外,如果我在创建my_ptr和打印它的解除引用值之间定义另一个变量:

fn main() {
    let my_ptr = make_local_int_ptr();
    let b = 6;
    println!("{}", b); // We have to use b otherwise Rust
                       // compiler …
Run Code Online (Sandbox Code Playgroud)

stack rust

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