我试图将predict方法的结果与pandas.DataFrame对象中的原始数据合并.
from sklearn.datasets import load_iris
from sklearn.cross_validation import train_test_split
from sklearn.tree import DecisionTreeClassifier
import pandas as pd
import numpy as np
data = load_iris()
# bear with me for the next few steps... I'm trying to walk you through
# how my data object landscape looks... i.e. how I get from raw data
# to matrices with the actual data I have, not the iris dataset
# put feature matrix into columnar format in dataframe
df …Run Code Online (Sandbox Code Playgroud) 给出以下数据帧:
import pandas as pd
df = pd.DataFrame({
'a': [1,2,3,4,5],
'b': [5,4,3,3,4],
'c': [3,2,4,3,10],
'd': [3, 2, 1, 1, 1]
})
Run Code Online (Sandbox Code Playgroud)
以及以下参数列表:
params = {'a': 2.5, 'b': 3.0, 'c': 1.3, 'd': 0.9}
Run Code Online (Sandbox Code Playgroud)
产生以下所需的输出:
a b c d output
0 1 5 3 3 24.1
1 2 4 2 2 21.4
2 3 3 4 1 22.6
3 4 3 3 1 23.8
4 5 4 10 1 38.4
Run Code Online (Sandbox Code Playgroud)
我一直用它来产生结果:
df['output'] = [np.sum(params[col] * df.loc[idx, col] for col in df)
for …Run Code Online (Sandbox Code Playgroud) 我已经使用scikit-learn训练了一个随机的森林模型,现在我想将它的树结构保存在文本文件中,以便我可以在其他地方使用它.根据这个链接,树对象由许多并行数组组成,每个数组都包含有关树的不同节点的一些信息(例如,左子,右子,它检查的特征,......).但是,似乎没有关于每个叶节点对应的类标签的信息!在上面的链接中提供的示例中甚至没有提到它.
有谁知道scikit-learn决策树结构中存储的类标签在哪里?
我完成了这里找到的所有步骤,甚至得到了以下消息,没有错误:
Application successfully deployed to https://user-name.shinyapps.io/projectFolder/
Run Code Online (Sandbox Code Playgroud)
但是,我ERROR: cannot open the connection在尝试运行程序时收到消息.以下是projectFolder我指导R Studio 的文件夹()的内容:
ui.R # contains only ui code
server.R # contains only server code
script.R # my full script, which contains global, ui, and server code
gomap.js # used for mapping app
styles.css # used for Shiny App
data.csv # my global data to be hosted on shinyapps.io
Run Code Online (Sandbox Code Playgroud)
以下是不同脚本的示例:
ui.R
ui <- shinyUI(navbarPage("Tab title", id="nav",
tabPanel("Interactive map",
div(class="outer",
tags$head(
includeCSS("/Users/user/Documents/R/projects/styles.css"),
includeScript("/Users/user/Documents/R/projects/gomap.js")
),
#### …Run Code Online (Sandbox Code Playgroud) 我已经构建了一个XGBoost模型并试图检查各个估算器.作为参考,这是具有离散和连续输入特征的二元分类任务.输入要素矩阵是a scipy.sparse.csr_matrix.
然而,当我去检查个体估计器时,我发现难以解释二进制输入特征,f60150如下所示.f60150最底层图表中的实数值很容易解释 - 其标准在该特征的预期范围内.但是,对二进制特征进行的比较<X> < -9.53674e-07没有意义.这些特征中的每一个都是1或0. -9.53674e-07是一个非常小的负数,我想这只是XGBoost或其基础绘图库中的一些浮点特性,但在特征中使用该比较没有意义永远是积极的.有人可以帮助我了解哪些方向(即yes, missing与no对应这些二进制功能节点,其真/假的一面?
这是一个可重复的例子:
import numpy as np
import scipy.sparse
from sklearn.datasets import fetch_20newsgroups
from sklearn.feature_extraction.text import CountVectorizer
from xgboost import plot_tree, XGBClassifier
import matplotlib.pyplot as plt
def booleanize_csr_matrix(mat):
''' Convert sparse matrix with positive integer elements to 1s '''
nnz_inds = mat.nonzero()
keep = np.where(mat.data > 0)[0]
n_keep = len(keep)
result = scipy.sparse.csr_matrix(
(np.ones(n_keep), (nnz_inds[0][keep], nnz_inds[1][keep])),
shape=mat.shape
)
return result
### …Run Code Online (Sandbox Code Playgroud) 使用这个scikit-learn 教程中关于理解决策树结构的一些指导,我有一个想法,也许查看两个连接节点之间发生的特征组合可能会对潜在的“交互”术语有所了解。也就是说,通过查看给定特征y跟随给定特征 的频率x,我们可能能够确定x和之间是否存在某种高阶交互作用y,与模型中的其他变量相比。
这是我的设置。基本上这个对象只是解析树的结构,让我们很容易遍历节点并确定每个节点发生了什么。
import numpy as np
class TreeInteractionFinder(object):
def __init__(
self,
model,
feature_names = None):
self.model = model
self.feature_names = feature_names
self._parse_tree_structure()
self._node_and_leaf_compute()
def _parse_tree_structure(self):
self.n_nodes = self.model.tree_.node_count
self.children_left = self.model.tree_.children_left
self.children_right = self.model.tree_.children_right
self.feature = self.model.tree_.feature
self.threshold = self.model.tree_.threshold
self.n_node_samples = self.model.tree_.n_node_samples
self.predicted_values = self.model.tree_.value
def _node_and_leaf_compute(self):
''' Compute node depth and whether each node is a leaf '''
node_depth = np.zeros(shape=self.n_nodes, dtype=np.int64)
is_leaves = np.zeros(shape=self.n_nodes, dtype=bool) …Run Code Online (Sandbox Code Playgroud) 我想创建一个类似于Microsoft Excel中的列字母的字符串列表.例如,26列之后,接下来的列将成为AA,AB,AC,等.
我已经使用了模运算试过,但我刚刚结束了AA,BB,CC等...
import string
passes_through_alphabet = 0
for num, col in enumerate([_ for _ in range(40)]):
if num % 26 == 0:
passes_through_alphabet += 1
excel_col = string.ascii_uppercase[num%26] * passes_through_alphabet
print(num, excel_col)
0 A
1 B
2 C
3 D
...
22 W
23 X
24 Y
25 Z
26 AA
27 BB
28 CC
...
Run Code Online (Sandbox Code Playgroud) 考虑以下人造CSV:
from io import StringIO
data = """value,date
7,null
7,10/18/2008
621,(null)"""
fake_file = StringIO(data)
Run Code Online (Sandbox Code Playgroud)
我想使用读取此文件pandas.read_csv,na_values并使用parse_dates和处理参数的空值和日期date_parser:
import pandas as pd
date_parser = lambda c: pd.datetime.strptime(c, '%m/%d/%Y')
df = pd.read_csv(fake_file, parse_dates=['date'], date_parser=date_parser, na_values=['null', '(null)'])
Run Code Online (Sandbox Code Playgroud)
在Python 3.5中运行此代码可以使我做到这一点:
File "<ipython-input-11-aa5bcf0858b7>", line 1, in <lambda>
date_parser = lambda c: pd.datetime.strptime(c, DATE_FMT)
TypeError: strptime() argument 1 must be str, not float
Run Code Online (Sandbox Code Playgroud)
因此,似乎先处理了null,然后尝试解析日期...
我知道我可以这样做:
df = pd.read_csv(fake_file, na_values=['null', '(null)'])
df['date'] = pd.to_datetime(df['date'], format='%m/%d/%Y')
Run Code Online (Sandbox Code Playgroud)
但是我真正的问题是如何同时处理日期格式和处理NaN...
我有一些pandas.Series- s,下面 - 我想进行单热编码。我通过研究发现,'b'级别对于我的预测建模任务并不重要。我可以像这样从我的分析中排除它:
import pandas as pd
from sklearn.preprocessing import OneHotEncoder
s = pd.Series(['a', 'b', 'c']).values.reshape(-1, 1)
enc = OneHotEncoder(drop=['b'], sparse=False, handle_unknown='error')
enc.fit_transform(s)
# array([[1., 0.],
# [0., 0.],
# [0., 1.]])
enc.get_feature_names()
# array(['x0_a', 'x0_c'], dtype=object)
Run Code Online (Sandbox Code Playgroud)
但是当我要转换一个新系列时,一个包含两个'b'和一个新级别的系列'd',我收到一个错误:
new_s = pd.Series(['a', 'b', 'c', 'd']).values.reshape(-1, 1)
enc.transform(new_s)
Run Code Online (Sandbox Code Playgroud)
回溯(最近一次调用):文件“”,第 1 行,文件“/Users/user/Documents/assets/envs/data-science/venv/lib/python3.7/site-packages/sklearn/preprocessing/_encoders .py”,第 390 行,在转换 X_int, X_mask = self._transform(X, handle_unknown=self.handle_unknown) 文件“/Users/user/Documents/assets/envs/data-science/venv/lib/python3.7/ site-packages/sklearn/preprocessing/_encoders.py”,第 124 行,在 _transform 中引发 ValueError(msg) ValueError:在转换期间在第 0 列中发现未知类别 ['d']
这是可以预料的,因为我在handle_unknown='error' …
你如何编写Python代码来检查是否运行?在由 Cayley 表定义的集合 {0,1,..,n?1} 上是否关联。
我尝试的代码是:
def is_associative_cayley_table(table):
if not is_cayley_table(table):
return False
for i in range (0,len(table)):
for j in range (0,len(table)):
for k in range (0,len(table)):
if (table[table[i][j])][k])==(table[i][(table[j][k])]):
print("Okay")
else
return False
Run Code Online (Sandbox Code Playgroud) python abstract-algebra python-2.7 python-3.x finite-group-theory
python ×9
scikit-learn ×4
pandas ×3
excel ×1
modulus ×1
null ×1
numpy ×1
python-2.7 ×1
python-3.x ×1
r ×1
shiny ×1
string ×1
xgboost ×1