小编cd9*_*d98的帖子

如何使用带有GridSearchCV对象的TimeSeriesSplit来调整scikit-learn中的模型?

我搜索了sklearn文档 TimeSeriesSplit交叉验证文档,但我找不到一个有效的例子.

我正在使用sklearn版本0.19.

这是我的设置

import xgboost as xgb
from sklearn.model_selection import TimeSeriesSplit
from sklearn.grid_search import GridSearchCV
import numpy as np
X = np.array([[4, 5, 6, 1, 0, 2], [3.1, 3.5, 1.0, 2.1, 8.3, 1.1]]).T
y = np.array([1, 6, 7, 1, 2, 3])
tscv = TimeSeriesSplit(n_splits=2)
for train, test in tscv.split(X):
    print(train, test)
Run Code Online (Sandbox Code Playgroud)

得到:

[0 1] [2 3]
[0 1 2 3] [4 5]
Run Code Online (Sandbox Code Playgroud)

如果我尝试:

model = xgb.XGBRegressor()
param_search = {'max_depth' : [3, 5]}

my_cv = TimeSeriesSplit(n_splits=2).split(X) …
Run Code Online (Sandbox Code Playgroud)

python scikit-learn xgboost

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

从一维数组的索引和值构造二维numpy数组

说我有

Y = np.array([2, 0, 1, 1])
Run Code Online (Sandbox Code Playgroud)

由此我想获得与形状的矩阵X (len(Y), 3).在这种特殊情况下,X的第一行应该在第二个索引上有一个,而在其他情况下为零.X的第二行应该在0索引上有一个,否则为零.要明确:

X = np.array([[0, 0, 1], [1, 0, 0], [0, 1, 0], [0, 1, 0]])
Run Code Online (Sandbox Code Playgroud)

我该如何制作这个矩阵?我开始了

X = np.zeros((Y.shape[0], 3))
Run Code Online (Sandbox Code Playgroud)

但后来无法弄清楚如何填充/填写索引列表中的那些

一如既往,谢谢你的时间!

python numpy

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

使用字典替换pandas数据帧上给定索引号的列值

请考虑以下数据帧

df_test = pd.DataFrame( {'a' : [1, 2, 8], 'b' : [np.nan, np.nan, 5], 'c' : [np.nan, np.nan, 4]})
df_test.index = ['one', 'two', 'three']
Run Code Online (Sandbox Code Playgroud)

这使

      a  b   c
one   1 NaN NaN
two   2 NaN NaN
three 8  5   4
Run Code Online (Sandbox Code Playgroud)

我有一个列b和c的行替换字典.例如:

{ 'one': [3.1, 2.2], 'two' : [8.8, 4.4] }
Run Code Online (Sandbox Code Playgroud)

3.1和8.8替换列b,2.2和4.4替换列c,结果是

      a  b   c
one   1 3.1 2.2
two   2 8.8 4.4
three 8  5   4
Run Code Online (Sandbox Code Playgroud)

我知道如何使用for循环进行这些更改:

index_list = ['one', 'two']
value_list_b = [3.1, 8.8]
value_list_c = [2.2, 4.4]
for …
Run Code Online (Sandbox Code Playgroud)

python pandas

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

在熊猫中,复杂(对我而言)从宽到长重塑

个体(索引从0到5)在两个位置之间进行选择:A和B.我的数据具有宽格式,包含因个体(ind_var)而异的特征以及仅根据位置(location_var)变化的特征.

例如,我有:

In [281]:

df_reshape_test = pd.DataFrame( {'location' : ['A', 'A', 'A', 'B', 'B', 'B'], 'dist_to_A' : [0, 0, 0, 50, 50, 50], 'dist_to_B' : [50, 50, 50, 0, 0, 0], 'location_var': [10, 10, 10, 14, 14, 14], 'ind_var': [3, 8, 10, 1, 3, 4]})

df_reshape_test

Out[281]:
    dist_to_A   dist_to_B   ind_var location location_var
0    0            50             3   A       10
1    0            50             8   A       10
2    0            50            10   A       10
3    50           0              1   B       14
4    50           0              3 …
Run Code Online (Sandbox Code Playgroud)

python reshape pandas

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

pandas:使用.loc选择索引标签数组

考虑一下这个dataFrame:

df = pd.DataFrame({u'A': {2.0: 2.2,
  7.0: 1.4,
  8.0: 1.4,
  9.0: 2.2},  u'B': {2.0: 7.2,
  7.0: 6.3,
  8.0: 4.4,
  9.0: 5.0}})
Run Code Online (Sandbox Code Playgroud)

看起来像这样:

      A       B
2    2.2     7.2
7    1.4     6.3
8    1.4     4.4
9    2.2     5.0
Run Code Online (Sandbox Code Playgroud)

我想得到带标签的索引27(数字,而不是字符串)

df.loc[[2, 7]]
Run Code Online (Sandbox Code Playgroud)

给出错误!

IndexError: indices are out-of-bounds
Run Code Online (Sandbox Code Playgroud)

然而,df.loc[7]df.loc[2]做工精细,并符合预期.另外,如果我用字符串而不是数字定义数据框索引:

df2 = pd.DataFrame({u'A': {'2': 2.2,
  '7': 1.4,
  '8': 1.4,
  '9': 2.2},
 u'B': {'2': 7.2,
  '7': 6.3,
  '8': 4.4,
  '9': 5.0}})

df2.loc[['2', '8']]
Run Code Online (Sandbox Code Playgroud)

它工作正常.

这不是我期望的行为df.loc(它是一个bug还是只是一个陷阱?)我可以将一组数字作为标签索引传递而不仅仅是位置吗?

我可以将所有索引转换为字符串,然后进行操作, …

python pandas

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

从Pandas向SQLite表添加新列的工作流程

建立

两张桌子:schoolsstudents.SQLite中的索引(或多个密钥)将是idtime用于students表和schooltimeschools表.我的数据集是关于不同的东西,但我认为学生的例子更容易理解.

import pandas as pd
import numpy as np
import sqlite3

df_students = pd.DataFrame(
{'id': list(range(0,4)) + list(range(0,4)),
'time': [0]*4 + [1]*4, 'school': ['A']*2 + ['B']*2 + ['A']*2 + ['B']*2,
'satisfaction': np.random.rand(8)} )
df_students.set_index(['id', 'time'], inplace=True)

        satisfaction    school
id  time        
0   0   0.863023    A
1   0   0.929337    A
2   0   0.705265    B
3   0   0.160457    B
0   1   0.208302    A
1   1   0.029397 …
Run Code Online (Sandbox Code Playgroud)

python sql database sqlite pandas

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

熊猫师(.div)与多指数

我有类似的东西

df = pd.DataFrame(np.random.randint(2, 10, size = (5, 2)))
df.index = pd.MultiIndex.from_tuples([(1, 'A'), (2, 'A'), (4, 'B'), 
           (5, 'B'), (8, 'B')])
df.index.names = ['foo', 'bar']
df.columns = ['count1', 'count2']
df
Run Code Online (Sandbox Code Playgroud)

这使:

       count1 count2
foo bar     
1   A    6     7
2   A    2     9
4   B    6     7
5   B    4     6
8   B    5     6
Run Code Online (Sandbox Code Playgroud)

我还有一个总计列表 - 从其他地方获得 - 通过相同的'foo'索引:

totals = pd.DataFrame([2., 1., 1., 1., 10.])
totals.index = [1, 2, 4, 5, 8]
totals.index.names = ['foo']
totals
Run Code Online (Sandbox Code Playgroud)

这使:

     0 …
Run Code Online (Sandbox Code Playgroud)

python pandas

5
推荐指数
2
解决办法
3892
查看次数

Pandas 的 Sqlite 的 NTILE 给出操作错误

我正在尝试使用 NTILE 函数从 pandas 查询 SQLite 数据库,但我没有成功,尽管我已经多次重新检查了语法。

下面是独立的示例。设置:

import pandas as pd
from sqlalchemy import create_engine
disk_engine = create_engine('sqlite:///test.db')

marks = pd.DataFrame({'StudentID': ['S1', 'S2', 'S3', 'S4', 'S5'],
                      'Marks': [75, 83, 91, 83, 93]})
marks.to_sql('marks_sql', disk_engine, if_exists='replace')
Run Code Online (Sandbox Code Playgroud)

现在尝试使用 NTILE:

q = """select StudentID, Marks, NTILE(2) OVER (ORDER BY Marks DESC)
        AS groupexample FROM marks_sql"""
pd.read_sql_query(q, disk_engine)
Run Code Online (Sandbox Code Playgroud)

回溯很长,但主要部分是:

OperationalError: near "(": syntax error
OperationalError: (sqlite3.OperationalError) near "(": syntax error [SQL: 'select StudentID, Marks, NTILE(2) OVER (ORDER BY Marks DESC)\n        AS groupexample FROM …
Run Code Online (Sandbox Code Playgroud)

python sqlite pandas

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

从 Pandas 数据帧向(大)SQLite 数据库添加额外的列

我觉得我忽略了一些非常简单的事情,但我无法让它发挥作用。我现在正在使用SQLite,但解决方案SQLAlchemy也将非常有帮助。

让我们创建原始数据集:

### This is just the setup part
import pandas as pd
import sqlite3
conn = sqlite3.connect('test.sqlite')

orig = pd.DataFrame({'COLUPC': [100001, 100002, 100003, 100004],
'L5': ['ABC ALE', 'ABC MALT LIQUOR', 'ABITA AMBER', 'ABITA AMBER'],
'attr1': [0.25, 0.25, 0.041, 0.041]})

orig.to_sql("UPCs", conn, if_exists='replace', index=False)

#Create an index just in case it's needed
conn.execute("""CREATE INDEX upc_index
ON UPCs (COLUPC);""")
Run Code Online (Sandbox Code Playgroud)

现在假设我接受orig dataframe并添加一个名为“L5_lower”的列。然后我在 SQLite 数据库中创建列:

# Create new variable
orig['L5_lower'] = orig.L5.str.lower()
conn.execute("alter table UPCs add column …
Run Code Online (Sandbox Code Playgroud)

python sqlite sqlalchemy pandas

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

R版本不支持石英图形设备 - RStudio不会绘图

我正在运行Mac OS Maverick.

在我之前的设置中,绘图将正确显示在RStudio的绘图选项卡上.我重新安装R with homebrew,当我使用RStudio时,它给了我以下警告

警告:您运行的R版本不支持石英图形设备(RStudio要求图形设备)."Plots"选项卡将被禁用,直到安装了支持quartz的R版本.

当我绘制一些东西时,它会XQuartz在我的Mac上打开应用程序.它确实显示了图形(有时虽然有奇怪的颜色),但我真的很喜欢它在RStudio中绘制.

是不是homebrew有一个版本R不支持石英图形设备或我搞砸了其他地方的东西?

与往常一样,任何帮助将非常感谢.


我的设置的一些细节:

  • R版本3.1.2(2014-10-31) - "南瓜头盔"

  • RStudio版本0.98.1091

  • 平台:x86_64-apple-darwin13.4.0(64位).Mac OS 10.9.5

  • Rhomebrew以下方式安装

    brew tap homebrew/science brew install r

  • 以前我安装tcl/tk了以下方式

    brew tap homebrew/dupes brew install tcl-tk --with-tk

macos homebrew r quartz-graphics rstudio

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

传单 - 随着时间的推移交互式等值线图

从2000年到2010年,我有30多个地区的密度数据.我想为每年创建一个交互式的等值区域地图,然后使用滑块(理想情况下)或单选按钮来选择年份.

我可以在第一年获得互动,但不会在其他年份的层次上.你可以在这里看到一个有用的例子,但是让我在下面提供一些细节:

为简单起见,请考虑两年.blocks1995具有非重叠多边形BlockA和BlockB(两个区)并blocks1996具有相同的块.他们有一个叫做density产生等值的财产:

var blocks1995 = {
    "type": "FeatureCollection",
    "crs": {
        "type": "name",
        "properties": { "name": "urn:ogc:def:crs:OGC:1.3:CRS84" }
    },
    "features": [{
        "type": "Feature",
        "properties": { "time": 1995, "density": 3.1, "nameB": "BlockA" },
        "geometry": {
            "type": "Polygon",
            "coordinates": [[[50.0, 29.0],[50.0, 29.99],[50.51, 29.99],[50.0, 29.0]]]
        }
    }, {
        "type": "Feature",
        "properties": { "time": 1995, "density": 1.1, "nameB": "BlockB" },
        "geometry": {
            "type": "Polygon",
            "coordinates": [[[50.01, 30.0],[50.52, 30.0],[50.52, 30.5]]]
        }
    }]
};

var blocks1996 …
Run Code Online (Sandbox Code Playgroud)

javascript interactive geo leaflet choropleth

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

使用 Dask 从谷歌云存储读取镶木地板文件

我正在尝试使用 Dask 从 google 存储桶读取和写入。使用一堆csv文件可以,但不方便(速度较慢,无法压缩,无法仅读取某些列),所以我尝试使用该apache parquet格式。

看起来写得很好:

import dask.dataframe as dd
pandas_df = pd.DataFrame({'x' : [2,3, 2], 'y': [1, 0, 0]})
dask_df = dd.from_pandas(pandas_df, npartitions=2)
dask_df.to_parquet("gcs://my_google_bucket/test/")
Run Code Online (Sandbox Code Playgroud)

但当我尝试读回来时

read_again_df = dd.read_parquet("gcs://my_google_bucket/test/") 
Run Code Online (Sandbox Code Playgroud)

我收到一个未实现的错误:

AttributeError                            Traceback (most recent call last)
~/miniconda3/envs/env1/lib/python3.6/site-packages/dask/bytes/core.py in get_pyarrow_filesystem(fs)
    520     try:
--> 521         return fs._get_pyarrow_filesystem()
    522     except AttributeError:

AttributeError: 'DaskGCSFileSystem' object has no attribute '_get_pyarrow_filesystem'

During handling of the above exception, another exception occurred:

NotImplementedError                       Traceback (most recent call last)
<ipython-input-42-ef1fc41d04d5> in <module>()
----> 1 …
Run Code Online (Sandbox Code Playgroud)

python google-cloud-storage parquet dask pyarrow

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

在Tweepy中优雅地处理user_timeline方法的错误和异常

我正在为大量用户收集推文,因此该脚本将在无人监督的情况下运行数天/数周.我有一个user_ids列表big_list.我认为有些推文是私有的,我的脚本会停止,所以我想让脚本继续使用下一个user_id(并且可能会打印一条警告消息).

我还想了解如何使其对其他错误或异常具有鲁棒性(例如,脚本在出错或超时时休眠)

这是我的总结:

import tweepy
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
my_api = tweepy.API(auth)

for id_str in big_list:
    all_tweets = get_all_tweets(id_str=id_str, api=my_api)
    #Here: insert some tweets into my database
Run Code Online (Sandbox Code Playgroud)

get_all_tweets函数抛出错误,它基本上反复调用:

my_api.user_timeline(user_id = id_str, count=200)
Run Code Online (Sandbox Code Playgroud)

以防万一,它给出的回溯如下:

/home/username/anaconda/lib/python2.7/site-packages/tweepy/binder.pyc in execute(self)
    201                 except Exception:
    202                     error_msg = "Twitter error response: status code = %s" % resp.status
--> 203                 raise TweepError(error_msg, resp)
    204 
    205             # Parse the response payload

TweepError: Not authorized.
Run Code Online (Sandbox Code Playgroud)

如果您需要更多详细信息,请告诉我们.谢谢!

-----------编辑--------

这个问题有一些信息.

我想我可以尝试try/except为不同类型的错误做一个块?我不知道所有相关的,所以有现场经验的人的最佳实践将不胜感激!

----------编辑2 …

python twitter tweepy

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