小编fas*_*oth的帖子

使用sklearn.feature_extraction.text.TfidfVectorizer的tf-idf特征权重

本页:http://scikit-learn.org/stable/modules/feature_extraction.html提及:

由于tf-idf经常用于文本特征,因此还有另一个名为TfidfVectorizer的类,它将CountVectorizerTfidfTransformer的所有选项组合在一个模型中.

然后我按照代码在我的语料库上使用fit_transform().如何获得fit_transform()计算的每个特征的权重?

我试过了:

In [39]: vectorizer.idf_
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-39-5475eefe04c0> in <module>()
----> 1 vectorizer.idf_

AttributeError: 'TfidfVectorizer' object has no attribute 'idf_'
Run Code Online (Sandbox Code Playgroud)

但是这个属性丢失了.

谢谢

python tf-idf scikit-learn

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

pandas groupby和join list

我有一个数据帧df,有两列,我想组合一列并加入列表属于同一组,例如:

column_a, column_b
1,         [1,2,3]
1,         [2,5]
2,         [5,6]
Run Code Online (Sandbox Code Playgroud)

过程结束后:

column_a, column_b
1,         [1,2,3,2,5]
2,         [5,6]
Run Code Online (Sandbox Code Playgroud)

我想保留所有重复项.我有以下问题:

  • 数据帧的dtypes是对象.convert_objects()不会自动将column_b转换为列表.我怎样才能做到这一点?
  • df.groupby(...).apply(lambda x:...)中的函数适用于什么?x的形式是什么?清单?
  • 解决我的主要问题?

提前致谢.

python pandas

25
推荐指数
3
解决办法
2万
查看次数

pandas饼图绘图删除楔形上的标签文本

pandas plotting教程http://pandas.pydata.org/pandas-docs/version/0.15.0/visualization.html上的饼图示例生成下图:

在此输入图像描述

使用此代码:

import matplotlib.pyplot as plt
plt.style.use('ggplot')
import numpy as np
np.random.seed(123456)


import pandas as pd
df = pd.DataFrame(3 * np.random.rand(4, 2), index=['a', 'b', 'c', 'd'], columns=['x', 'y'])

f, axes = plt.subplots(1,2, figsize=(10,5))
for ax, col in zip(axes, df.columns):
    df[col].plot(kind='pie', autopct='%.2f', labels=df.index,  ax=ax, title=col, fontsize=10)
    ax.legend(loc=3)

plt.show()
Run Code Online (Sandbox Code Playgroud)

我想从两个子图中删除文本标签(a,b,c,d),因为对于我的应用程序,这些标签很长,所以我只想在图例中显示它们.

阅读本文后:如何在matplotlib饼图中添加图例?,我想出了一个方法,matplotlib.pyplot.pie但即使我仍在使用ggplot,这个数字也不那么华丽.

f, axes = plt.subplots(1,2, figsize=(10,5))
for ax, col in zip(axes, df.columns):
    patches, text, _ = ax.pie(df[col].values, autopct='%.2f')
    ax.legend(patches, labels=df.index, loc='best')
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

我的问题是,有没有一种方法可以将我想要的东西结合起来?要清楚,我想要大熊猫的幻想,但要从楔子中删除文字.

谢谢

matplotlib legend pandas pie-chart

14
推荐指数
2
解决办法
2万
查看次数

IPython:从特定行开始运行脚本

我正在用IPython以交互方式编写我的脚本.这就是我目前所做的事情:

  1. 写一大堆代码,
  2. 使用"run -i file_name.py"在ipython中运行.
  3. 进行更改并重复2,直到我认为它没问题.
  4. 注释掉整个上一个块.
  5. 编写基于前一代码的新代码块.
  6. 回到第2步.
  7. ......

有更有效的方法吗?我可以在使用当前命名空间中的所有变量时从特定行启动脚本吗?

ipython

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

sklearn,LassoCV()和ElasticCV()坏了吗?

sklearn提供用于回归估计的LASSO方法.但是,当我尝试使用ya矩阵拟合LassoCV(X,y)时,它会抛出错误.请参阅下面的屏幕截图以及其文档的链接.我使用的sklearn版本是0.15.2.

http://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LassoCV.html#sklearn.linear_model.LassoCV

它的文件说y可以是一个ndarray:

y : array-like, shape (n_samples,) or (n_samples, n_targets)
Run Code Online (Sandbox Code Playgroud)

当我使用Lasso()来适应相同的X和y时,它工作正常.所以我想知道LassoCV()是否已损坏或我是否需要做其他事情?

In [2]:  import numpy as np 
im
In [3]: import sklearn.linear_model

In [4]: from sklearn import linear_model

In [5]: X = np.random.random((10,100))

In [6]: y = np.random.random((50, 100)) 

In [7]: linear_model.Lasso().fit(X,y) 
Out[7]: 
Lasso(alpha=1.0, copy_X=True, fit_intercept=True, max_iter=1000,
   normalize=False, positive=False, precompute='auto', tol=0.0001,
   warm_start=False)

In [8]: linear_model.LassoCV().fit(X,y)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-8-9c8ad3459ac8> in <module>()
----> 1 linear_model.LassoCV().fit(X,y)

/chimerahomes/wenhoujx/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/sklearn/linear_model/coordinate_descent.pyc in fit(self, X, y)
   1006             if y.ndim > 1:
   1007 …
Run Code Online (Sandbox Code Playgroud)

python regression linear-regression scikit-learn

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

番石榴为什么toStringFunction不是通用函数?

Guava toStringFunction()具有以下声明:

public static Function<Object, String> toStringFunction() { ... } 
Run Code Online (Sandbox Code Playgroud)

Object的所有非原始根,因此该函数运行良好.

但是当我尝试用另一个函数组合它时,例如:

Function<Integer, Double> f1 = Functions.compose(Functions.forMap(someMap),
                                                 Functions.toStringFunction());
Run Code Online (Sandbox Code Playgroud)

someMap变量是map <String,Double>,所以我希望toStringFunction将Integer转换为String,然后forMap将String转换为Double.但是我收到编译错误:

    Function<Integer, Double> f1 = Functions.compose(Functions.forMap(someMap),
                                                    ^
  required: Function<Integer,Double>
  found:    Function<Object,Double>
2 errors
Run Code Online (Sandbox Code Playgroud)

我的两个问题是:

1.如何具体告诉编译器toStringFunction应该是Function <Integer,String>?一个简单的演员不会起作用,我正在寻找这两个函数的真实组合.

Function< Integer, String> g1 = (Function< Integer, String>)Functions.toStringFunction(); 

// cause error 
Run Code Online (Sandbox Code Playgroud)

2.将toStringFunction写成如下:

 @SuppressWarnings("unchecked") 
  public static <E> Function<E, String> toStringFunction(){
    return (Function<E, String>) ToStringFunction.INSTANCE;
  }

  // enum singleton pattern
  private enum ToStringFunction implements Function<Object, String>{
    INSTANCE;


    // @Override public String toString(){
    //   return "Functions.toStringFunction()";
    // } …
Run Code Online (Sandbox Code Playgroud)

java generics guava

6
推荐指数
2
解决办法
391
查看次数

numpy,transposition是一个视图,并不会使矩阵对称?

阅读scipy讲座时:http://scipy-lectures.github.io/intro/numpy/operations.html

有一个例子:

>>> a = np.triu(np.ones((3, 3)), 1)
>>> a
array([[ 0.,  1.,  1.],
       [ 0.,  0.,  1.],
       [ 0.,  0.,  0.]])
>>> a.T
array([[ 0.,  0.,  0.],
       [ 1.,  0.,  0.],
       [ 1.,  1.,  0.]])
Run Code Online (Sandbox Code Playgroud)

然后它说: 在此输入图像描述

而且我不明白为什么.我做了一个实验,它确实使它对称. 在此输入图像描述


编辑1:

随机矩阵的结果相同: 在此输入图像描述

python numpy

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

Python,使用多处理来进一步加速cython功能

这里显示的代码是简单的,但触发相同的PicklingError.我知道有很多关于什么能够和不能被腌制的讨论,但我确实找到了他们的解决方案.

我用以下函数编写了一个简单的cython脚本:

def pow2(int a) : 
    return a**2 
Run Code Online (Sandbox Code Playgroud)

编译工作正常,我可以在python脚本中调用此函数.

在此输入图像描述

但是,我想知道如何在多处理中使用此功能,

from multiprocessing import Pool
from fast import pow2
p = Pool(processes =4 )
y = p.map( pow2, np.arange( 10, dtype=int))
Run Code Online (Sandbox Code Playgroud)

给我一个PicklingError: 在此输入图像描述

dtw是包的名称,fast是fast.pyx.

我怎样才能解决这个问题?提前致谢

python arrays numpy multiprocessing cython

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

Pythonic将字典转换为numpy数组的方法

这更像是关于编程风格的问题.我删除了以下字段的网页:"温度:51 - 62","高度:1000-1500"......等结果保存在字典中

{"temperature": "51-62", "height":"1000-1500" ...... }
Run Code Online (Sandbox Code Playgroud)

所有键和值都是字符串类型.每个键都可以映射到许多可能值中的一个.现在我想将这个字典转换为numpy数组/向量.我有以下问题:

  • 每个键对应于数组中的一个索引位置.
  • 每个可能的字符串值都映射到一个整数.
  • 对于某些字典,某些键不可用.例如,我也有一个没有"温度"键的字典,因为该网页不包含这样的字段.

我想知道在Python中编写这种转换的最清晰有效的方法是什么.我正在考虑构建另一个字典,将关键字映射到向量的索引号.还有许多其他字典将值映射到整数.

我遇到的另一个问题是我不确定某些键的范围.我想动态跟踪字符串值和整数之间的映射.例如,我可能会发现key1将来可以映射到val1_8.

谢谢

python dictionary numpy

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

Python JSON转储对象列表.

我有一个字典列表,如何使用JSON每个字典一行转储它?

我试过了:

json.dump( d, open('./testing.json','w'), indent=0)
Run Code Online (Sandbox Code Playgroud)

其中d是词典列表.但这会对每个(键,值)对进行换行.我希望每行字典在一行中.我该怎么做?

谢谢

python json

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

Python模块不可调用

我搜索了很多帖子,但它们似乎没有帮助.

在文件夹dir1 /我有main.py和plotcluster.py.在plotcluster.py我有:

import matplotlib as plt
import itertools as it
....
def plotc():
    colors = it.cycle('ybmgk')
    ....
    plt.figure()
    ....
Run Code Online (Sandbox Code Playgroud)

在main.py中,我使用plotcluster.py:

import plotcluster as plc
....
plc.plotc()
Run Code Online (Sandbox Code Playgroud)

但这给了我一个错误,说模块对象不可调用.

     20     linestyles = it.cycle('-:_')
     21
---> 22     plt.figure()
     23     # plot the most frequent ones first
     24     for iter_count, (i, _) in enumerate(Counter(centerid).most_common()):

TypeError: 'module' object is not callable
Run Code Online (Sandbox Code Playgroud)

它不会抱怨itertools模块,但是它会让人烦恼.这让我很困惑!

任何帮助将不胜感激 !!提前致谢!

python module

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