小编Mun*_*ong的帖子

如何计算SAS表中的观察数量?

我是SAS的新手.现在,我有一个SAS数据表如下:

    ID       score
-------------------
    01         1
    02         3
    03         4
    04         2
Run Code Online (Sandbox Code Playgroud)

有没有办法只使用PROC SORT和DATA步骤来保存此表中的观察数量?我想在日志窗口中保存该值,就像SAS日志脚本中的"保持N = 4"一样.

对不起我的不专业描述.提前致谢.

statistics sas

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

稀疏矩阵:ValueError:矩阵类型必须为'f','d','F'或'D'

我想通过使用scipy在稀疏矩阵上进行SVD​​:

from svd import compute_svd
print("The size of raw matrix: "+str(len(raw_matrix))+" * "+str(len(raw_matrix[0])))

from scipy.sparse import dok_matrix
dok = dok_matrix(raw_matrix)

matrix = compute_svd( dok )
Run Code Online (Sandbox Code Playgroud)

函数compute_svd是我的自定义模块,如下所示:

def compute_svd( matrix ):
    from scipy.sparse import linalg
    from scipy import dot, mat
    # e.g., matrix = [[2,1,0,0], [4,3,0,0]]
#    matrix = mat( matrix );
#    print "Original matrix:"
#    print matrix
    U, s, V = linalg.svds( matrix )
    print "U:"
    print U
    print "sigma:"
    print s
    print "VT:"
    print V
    dimensions = 1 …
Run Code Online (Sandbox Code Playgroud)

matrix scipy sparse-matrix

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

scipy稀疏矩阵:删除所有元素为零的行

我有一个稀疏矩阵,它是从sklearn tfidfVectorier转换而来的.我相信有些行是全零行.我想删除它们.但是,据我所知,现有的内置函数,例如nonzero()和eliminate_zero(),专注于零条目而不是行.

有没有简单的方法从稀疏矩阵中删除全零行?

示例:我现在拥有的(实际上是稀疏格式):

[ [0, 0, 0]
  [1, 0, 2]
  [0, 0, 1] ]
Run Code Online (Sandbox Code Playgroud)

我想得到什么:

[ [1, 0, 2]
  [0, 0, 1] ]
Run Code Online (Sandbox Code Playgroud)

python numpy scipy scikit-learn

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

Keras RNN 损失不会随着 epoch 减少

我使用 Keras 构建了一个 RNN。RNN 用于解决回归问题:

def RNN_keras(feat_num, timestep_num=100):
    model = Sequential()
    model.add(BatchNormalization(input_shape=(timestep_num, feat_num)))
    model.add(LSTM(input_shape=(timestep_num, feat_num), output_dim=512, activation='relu', return_sequences=True))
    model.add(BatchNormalization())  
    model.add(LSTM(output_dim=128, activation='relu', return_sequences=True))
    model.add(BatchNormalization())
    model.add(TimeDistributed(Dense(output_dim=1, activation='relu'))) # sequence labeling

    rmsprop = RMSprop(lr=0.00001, rho=0.9, epsilon=1e-08)
    model.compile(loss='mean_squared_error',
                  optimizer=rmsprop,
                  metrics=['mean_squared_error'])
    return model
Run Code Online (Sandbox Code Playgroud)

整个过程看起来不错。但是损失在各个时期内保持完全相同。

61267 in the training set
6808 in the test set

Building training input vectors ...
888 unique feature names
The length of each vector will be 888
Using TensorFlow backend.

Build model...

# Each batch has 1280 examples
# The training …
Run Code Online (Sandbox Code Playgroud)

machine-learning neural-network deep-learning keras recurrent-neural-network

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

Tensorflow 获取张量中值的索引

给定一个矩阵和向量?我想在矩阵的相应行中找到值的索引。

m = tf.constant([[0, 2, 1],[2, 0, 1]])  # matrix
y = tf.constant([1,2])  # values whose indices should be found
Run Code Online (Sandbox Code Playgroud)

理想的输出是 [2,0],因为 y 的第一个值 1 位于 m 的第一个向量的索引 2 处。y 的第二个值 2 位于 m 的第二个向量的索引 0 处。

python matrix tensorflow

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

Python networkx图:不要将旧图与新图一起绘制

以下是我的代码:

import networkx as nx
for i in range(2):
    G = nx.DiGraph()
    if i==0:
        G.add_edge("A", "B")
    elif i==1:
        G.add_edge("A", "C")
    import matplotlib.pyplot as plt
    nx.draw(G)
    plt.savefig(str(i)+".png")
    G.clear()
Run Code Online (Sandbox Code Playgroud)

它应该在文件0.png中绘制线AB并在文件1.png中绘制线AC.但是,在我运行之后.在0.png中,有一条线AB,但在1.png中,有两条线:AB和AC.似乎没有清理0.png的内存,虽然我有"G.clear()".

有人知道怎么解决吗?

networkx

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

sklearn单变量特征选择

我正在尝试使用sklearn单变量功能选择来过滤掉不相关的功能:

ufs = feature_selection.SelectPercentile(feature_selection.f_classif, percentile = 60)
X_default_cvtrain = ufs.fit_transform( X_cvtrain, Y_cvtrain )
Run Code Online (Sandbox Code Playgroud)

但是,我得到了这个警告:

UserWarning: Duplicate scores. Result may depend on feature ordering.
             There are probably duplicate features, or you used a classification score for a regression task.
warn("Duplicate scores. Result may depend on feature ordering."
Run Code Online (Sandbox Code Playgroud)

这是什么意思?这里发生了什么?

谢谢.

python machine-learning scikit-learn

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

带Lasso惩罚的线性回归需要增加迭代次数,Scikit-learn

我正在使用线性回归和 Scikit-learn 包中实现的 Lasso。

linear_regress = linear_model.Lasso(alpha = 2)
linear_regress.fit(X, Y)
Run Code Online (Sandbox Code Playgroud)

对于 X,有 7827 个示例和 758 个特征。但是我收到了警告:

Objective did not converge for target 0, you might want to increase the number of iterations ' to increase the number of iterations')
Run Code Online (Sandbox Code Playgroud)

同时,交叉验证的MAE为0.00304247702091

然后,我按照它的建议增加了迭代次数。(我假设我做得正确):

linear_regress = linear_model.Lasso(alpha = 2, max_iter = 100000, tol = 1e-20)
Run Code Online (Sandbox Code Playgroud)

但警告仍然存在,MAE 增加到 0.0191056040626,这更糟。

那么有谁知道如何解决这个问题?

顺便说一句,对于交叉验证的结果,训练数据的 MAE 远小于测试数据的 MAE,例如(alpha=2):

The MAE on the TRAINING data is 6.3462754706e-14
The MAE on the TEST data is 0.238521024414
Run Code Online (Sandbox Code Playgroud)

我假设存在过度拟合。但增加 alpha 并没有多大帮助,例如(alpha=5) …

python machine-learning linear-regression scikit-learn

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

Pandas 数据透视表的倒数

我有一个df_p已经转换为数据透视表的 DataFrame(例如,):

import pandas as pd
df = pd.DataFrame({'start_year':[2000, 2001, 2002],
                  'end_year':[2010, 2011, 2012],
                  'price':[1.0, 2.0, 3.0]})

#    end_year  price  start_year
# 0      2010    1.0        2000
# 1      2011    2.0        2001
# 2      2012    3.0        2002

df_p = df.pivot('start_year', 'end_year', 'price')

# end_year    2010  2011  2012
# start_year                  
# 2000         1.0   NaN   NaN
# 2001         NaN   2.0   NaN
# 2002         NaN   NaN   3.0
Run Code Online (Sandbox Code Playgroud)

我应该如何转换df_pdf

python pandas

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

tensorflow合并并压缩两个张量

我有两个张量如下:

x1 = tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
x2 = tf.constant([[7.0, 8.0, 9.0], [10.0, 11.0, 12.0]])
Run Code Online (Sandbox Code Playgroud)

我应该如何合并和转换x1和x2,这样我就可以得到如下的张量:

[[[1.0, 7.0]
  [2.0, 8.0]
  [3.0, 9.0]]

 [[4.0, 10.0]
  [5.0, 11.0]
  [6.0, 12.0]]
]
Run Code Online (Sandbox Code Playgroud)

python matrix tensorflow tensor

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

熊猫-将数据框插入MongoDB

我正在尝试将数据框插入MongoDB。每行应为一个文档。

from pymongo import MongoClient
import pandas as pd

client = MongoClient()
col = client['test']['test']

d = {'name': ['Braund', 'Cummings', 'Heikkinen', 'Allen'],
     'age': [22,38,26,35],
     'fare': [7.25, 71.83, 0 , 8.05],
     'survived?': [False, True, True, False]}

df = pd.DataFrame(d)

col.insert_many(df)
Run Code Online (Sandbox Code Playgroud)

但是,以上代码返回错误: ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

更改col.insert_many(df)col.insert_many(df.to_dict())col.insert_many(df.to_json())原因TypeError: document must be an instance of dict, bson.son.SON, bson.raw_bson.RawBSONDocument, or a type that inherits from collections.MutableMapping

python mongodb pandas

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

熊猫:选择字典中包含特定键的行

我有一个数据框,其中一列都是字典。我想选择其字典包含给定键的行。

>>> df = pd.DataFrame({"A": [1,2,3], "B": [{"a":1}, {"b":2}, {"c":3}]})
>>> df
   A         B
0  1  {'a': 1}
1  2  {'b': 2}
2  3  {'c': 3}
>>> df['b' in df['B']]  
# the desired result is the row with index 1. But this causes an error: KeyError: False
Run Code Online (Sandbox Code Playgroud)

python dictionary dataframe pandas

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