我是SAS的新手.现在,我有一个SAS数据表如下:
ID score
-------------------
01 1
02 3
03 4
04 2
Run Code Online (Sandbox Code Playgroud)
有没有办法只使用PROC SORT和DATA步骤来保存此表中的观察数量?我想在日志窗口中保存该值,就像SAS日志脚本中的"保持N = 4"一样.
对不起我的不专业描述.提前致谢.
我想通过使用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) 我有一个稀疏矩阵,它是从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) 我使用 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
给定一个矩阵和向量?我想在矩阵的相应行中找到值的索引。
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 处。
以下是我的代码:
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()".
有人知道怎么解决吗?
我正在尝试使用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)
这是什么意思?这里发生了什么?
谢谢.
我正在使用线性回归和 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) …
我有一个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_p回df?
我有两个张量如下:
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) 我正在尝试将数据框插入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
我有一个数据框,其中一列都是字典。我想选择其字典包含给定键的行。
>>> 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 ×8
matrix ×3
pandas ×3
scikit-learn ×3
scipy ×2
tensorflow ×2
dataframe ×1
dictionary ×1
keras ×1
mongodb ×1
networkx ×1
numpy ×1
sas ×1
statistics ×1
tensor ×1