簡體   English   中英

將數組范圍作為參數傳遞給函數?

[英]Passing array range as argument to a function?

有沒有辦法將數組范圍作為參數傳遞給函數? 就像是 :

> blah(ary,arg1=1:5)

def blah(ary,arg1): print ary[arg1]

Python 只接受方括號內的1:5語法。 解釋器將其轉換為slice對象。 然后對象的__getitem__方法應用切片。

查看numpy/lib/index_tricks.py以了解一些利用此功能的函數。 實際上,它們不是函數,而是定義自己的__getitem__方法的類。 該文件可能會給您一些想法。

但是,如果您無法做到這一點,那么可能性包括:

blah(arr, slice(1, 5))
blah(arr, np.r_[1:5])

nd_gridmgridogrid擴展了“切片”概念以接受虛構的“步長”值:

mgrid[-1:1:5j]
# array([-1. , -0.5,  0. ,  0.5,  1. ])

請注意,在將切片傳遞給您的blah函數之前在切片上展開的任何內容都不會知道其他參數的形狀。 所以np.r_[:-1]只返回[]

並且None可以用於slice :例如slice(None,None,-1)相當於[::-1]

您可以使用切片功能

>>> def blah(ary,arg1):
...     print ary[arg1]
>>> blah(range(10), slice(1, 5))
[1, 2, 3, 4]

你可以這樣嘗試:

def blah(ary, arg):
    arg = map(int, arg.split(":"))
    print ary[arg[0]:arg[1]]

blah([1,2,3,4,5,6],"2:5")

輸出:

[3, 4, 5]

今天看到它發生,我覺得很好奇,注意他們將參數 test_idx作為一個普通范圍傳遞

plot_decision_regions(X=X_combined_std, y=y_combined,
                      classifier=ppn, test_idx=range(105, 150))

那么這到底有什么作用呢?

使用它對Numpy 數組進行切片

ndarray[范圍(105, 150), :]

然而,當我通過復制 ndarray 值來測試這個,實例化它並嘗試自己切片(基本上是創建一個列表)它不會允許我在切片上傳遞該范圍。

[[0.73088538 1.57698181],[0.17316034 0.1348488]]

當您單擊以設置新值時,我從 ndarray 中提取/復制

埃里克 = [[ 0.73088538 1.57698181], [ 0.17316034 0.1348488 ]]

-- 語法錯誤。 無效的語法

必須將逗號作為語法接受並將其實例化為列表 obj

埃里克 = [[ 0.73088538, 1.57698181], [ 0.17316034, 0.1348488 ]]

埃里克[:]

(工作,返回整個事情)

埃里克[范圍(0, 1), :]

-- 類型錯誤。 列表索引必須是積分器或切片,而不是元組

(中斷,我們之前測試過切片是否有效,因此它與范圍有關)

在此處輸入圖片說明

用自制的 Numpy Array 再試一次(劇透,它有效)

erickNpa = np.asarray(erick, dtype=np.float32)
erickNpa[range(0, 1), :]

在此處輸入圖片說明


結論

可以將范圍作為參數傳遞,第一部分所示,在某些時候代碼沒有執行,但這與它正在做的事情的性質有關(使用它來切片列表),但是使用正確的腳手架當使用 Numpy Array 代替時,似乎證明有效。



示例代碼

我還將放置函數 def以防 git 被刪除,即使我鏈接了該行。

def plot_decision_regions(X, y, classifier, test_idx=None, resolution=0.02):

    # setup marker generator and color map
    markers = ('s', 'x', 'o', '^', 'v')
    colors = ('red', 'blue', 'lightgreen', 'gray', 'cyan')
    cmap = ListedColormap(colors[:len(np.unique(y))])

    # plot the decision surface
    x1_min, x1_max = X[:, 0].min() - 1, X[:, 0].max() + 1
    x2_min, x2_max = X[:, 1].min() - 1, X[:, 1].max() + 1
    xx1, xx2 = np.meshgrid(np.arange(x1_min, x1_max, resolution),
                           np.arange(x2_min, x2_max, resolution))
    Z = classifier.predict(np.array([xx1.ravel(), xx2.ravel()]).T)
    Z = Z.reshape(xx1.shape)
    plt.contourf(xx1, xx2, Z, alpha=0.3, cmap=cmap)
    plt.xlim(xx1.min(), xx1.max())
    plt.ylim(xx2.min(), xx2.max())

    for idx, cl in enumerate(np.unique(y)):
        plt.scatter(x=X[y == cl, 0], 
                    y=X[y == cl, 1],
                    alpha=0.8, 
                    c=colors[idx],
                    marker=markers[idx], 
                    label=cl, 
                    edgecolor='black')

    # highlight test examples
    if test_idx:
        # plot all examples
        X_test, y_test = X[test_idx, :], y[test_idx]

        plt.scatter(X_test[:, 0],
                    X_test[:, 1],
                    c='',
                    edgecolor='black',
                    alpha=1.0,
                    linewidth=1,
                    marker='o',
                    s=100, 
                    label='test set')


# Training a perceptron model using the standardized training data:



X_combined_std = np.vstack((X_train_std, X_test_std))
y_combined = np.hstack((y_train, y_test))

plot_decision_regions(X=X_combined_std, y=y_combined,
                      classifier=ppn, test_idx=range(105, 150))
plt.xlabel('petal length [standardized]')
plt.ylabel('petal width [standardized]')
plt.legend(loc='upper left')

plt.tight_layout()
#plt.savefig('images/03_01.png', dpi=300)
plt.show()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM