标签归档:numpy

是否有NumPy函数返回数组中某物的第一个索引?

问题:是否有NumPy函数返回数组中某物的第一个索引?

我知道有一种方法可以让Python列表返回某些内容的第一个索引:

>>> l = [1, 2, 3]
>>> l.index(2)
1

NumPy数组有类似的东西吗?

I know there is a method for a Python list to return the first index of something:

>>> l = [1, 2, 3]
>>> l.index(2)
1

Is there something like that for NumPy arrays?


回答 0

是的,这是给定NumPy数组array和值的答案item,以搜索:

itemindex = numpy.where(array==item)

结果是具有所有行索引,然后是所有列索引的元组。

例如,如果一个数组是二维的,并且它在两个位置包含您的商品,则

array[itemindex[0][0]][itemindex[1][0]]

将等于您的物品,所以

array[itemindex[0][1]][itemindex[1][1]]

numpy.where

Yes, here is the answer given a NumPy array, array, and a value, item, to search for:

itemindex = numpy.where(array==item)

The result is a tuple with first all the row indices, then all the column indices.

For example, if an array is two dimensions and it contained your item at two locations then

array[itemindex[0][0]][itemindex[1][0]]

would be equal to your item and so would

array[itemindex[0][1]][itemindex[1][1]]

numpy.where


回答 1

如果仅需要一个值的第一次出现的索引,则可以使用nonzero(或where,在这种情况下,这等于同一件事):

>>> t = array([1, 1, 1, 2, 2, 3, 8, 3, 8, 8])
>>> nonzero(t == 8)
(array([6, 8, 9]),)
>>> nonzero(t == 8)[0][0]
6

如果您需要每个的第一个索引,显然可以重复执行与上述相同的操作,但是有一个技巧可能会更快。以下是每个子序列的第一个元素的索引:

>>> nonzero(r_[1, diff(t)[:-1]])
(array([0, 3, 5, 6, 7, 8]),)

请注意,它找到了3s的两个子序列和8s的两个子序列的开头:

[ 1,1,1,2,2,3838,8]

因此,它与找到每个值的第一个匹配项略有不同。在您的程序中,您可以使用的排序版本t来获得所需的内容:

>>> st = sorted(t)
>>> nonzero(r_[1, diff(st)[:-1]])
(array([0, 3, 5, 7]),)

If you need the index of the first occurrence of only one value, you can use nonzero (or where, which amounts to the same thing in this case):

>>> t = array([1, 1, 1, 2, 2, 3, 8, 3, 8, 8])
>>> nonzero(t == 8)
(array([6, 8, 9]),)
>>> nonzero(t == 8)[0][0]
6

If you need the first index of each of many values, you could obviously do the same as above repeatedly, but there is a trick that may be faster. The following finds the indices of the first element of each subsequence:

>>> nonzero(r_[1, diff(t)[:-1]])
(array([0, 3, 5, 6, 7, 8]),)

Notice that it finds the beginning of both subsequence of 3s and both subsequences of 8s:

[1, 1, 1, 2, 2, 3, 8, 3, 8, 8]

So it’s slightly different than finding the first occurrence of each value. In your program, you may be able to work with a sorted version of t to get what you want:

>>> st = sorted(t)
>>> nonzero(r_[1, diff(st)[:-1]])
(array([0, 3, 5, 7]),)

回答 2

您还可以将NumPy数组转换为空中列表并获取其索引。例如,

l = [1,2,3,4,5] # Python list
a = numpy.array(l) # NumPy array
i = a.tolist().index(2) # i will return index of 2
print i

它将打印1。

You can also convert a NumPy array to list in the air and get its index. For example,

l = [1,2,3,4,5] # Python list
a = numpy.array(l) # NumPy array
i = a.tolist().index(2) # i will return index of 2
print i

It will print 1.


回答 3

只是添加了一个非常高性能和方便 替代基于np.ndenumerate查找第一个索引:

from numba import njit
import numpy as np

@njit
def index(array, item):
    for idx, val in np.ndenumerate(array):
        if val == item:
            return idx
    # If no item was found return None, other return types might be a problem due to
    # numbas type inference.

这非常快,并且自然可以处理多维数组

>>> arr1 = np.ones((100, 100, 100))
>>> arr1[2, 2, 2] = 2

>>> index(arr1, 2)
(2, 2, 2)

>>> arr2 = np.ones(20)
>>> arr2[5] = 2

>>> index(arr2, 2)
(5,)

这可能比使用或的任何方法都要快得多(因为这会使操作短路)。np.wherenp.nonzero


但是np.argwhere也可以处理优雅与多维数组(您需要手动将它转换到一个元组它不是短路),但如果没有找到匹配它会失败:

>>> tuple(np.argwhere(arr1 == 2)[0])
(2, 2, 2)
>>> tuple(np.argwhere(arr2 == 2)[0])
(5,)

Just to add a very performant and handy alternative based on np.ndenumerate to find the first index:

from numba import njit
import numpy as np

@njit
def index(array, item):
    for idx, val in np.ndenumerate(array):
        if val == item:
            return idx
    # If no item was found return None, other return types might be a problem due to
    # numbas type inference.

This is pretty fast and deals naturally with multidimensional arrays:

>>> arr1 = np.ones((100, 100, 100))
>>> arr1[2, 2, 2] = 2

>>> index(arr1, 2)
(2, 2, 2)

>>> arr2 = np.ones(20)
>>> arr2[5] = 2

>>> index(arr2, 2)
(5,)

This can be much faster (because it’s short-circuiting the operation) than any approach using np.where or np.nonzero.


However np.argwhere could also deal gracefully with multidimensional arrays (you would need to manually cast it to a tuple and it’s not short-circuited) but it would fail if no match is found:

>>> tuple(np.argwhere(arr1 == 2)[0])
(2, 2, 2)
>>> tuple(np.argwhere(arr2 == 2)[0])
(5,)

回答 4

如果要将其用作其他内容的索引,则可以使用布尔索引(如果数组可广播);您不需要显式索引。做到这一点的最简单的绝对方法是根据真值简单地建立索引。

other_array[first_array == item]

任何布尔运算均可:

a = numpy.arange(100)
other_array[first_array > 50]

非零方法也需要布尔值:

index = numpy.nonzero(first_array == item)[0][0]

两个零用于索引的元组(假设first_array为1D),然后是索引数组中的第一项。

If you’re going to use this as an index into something else, you can use boolean indices if the arrays are broadcastable; you don’t need explicit indices. The absolute simplest way to do this is to simply index based on a truth value.

other_array[first_array == item]

Any boolean operation works:

a = numpy.arange(100)
other_array[first_array > 50]

The nonzero method takes booleans, too:

index = numpy.nonzero(first_array == item)[0][0]

The two zeros are for the tuple of indices (assuming first_array is 1D) and then the first item in the array of indices.


回答 5

l.index(x)返回最小的i,使i是列表中x首次出现的索引。

可以放心地假定index()Python 中的函数已实现,以便在找到第一个匹配项后停止,从而获得最佳的平均性能。

为了找到在NumPy数组中的第一个匹配项之后停止的元素,请使用迭代器(ndenumerate)。

In [67]: l=range(100)

In [68]: l.index(2)
Out[68]: 2

NumPy数组:

In [69]: a = np.arange(100)

In [70]: next((idx for idx, val in np.ndenumerate(a) if val==2))
Out[70]: (2L,)

请注意,这两种方法index(),并next在未找到该元素,返回一个错误。使用next,可以在找不到元素的情况下使用第二个参数返回一个特殊值,例如

In [77]: next((idx for idx, val in np.ndenumerate(a) if val==400),None)

NumPy(argmaxwherenonzero)中还有其他函数可用于查找数组中的元素,但是它们都有缺点,即遍历整个数组以查找所有出现的元素,因此没有为查找第一个元素而进行优化。还需要注意的是where,并nonzero返回数组,所以你需要选择得到索引的第一个元素。

In [71]: np.argmax(a==2)
Out[71]: 2

In [72]: np.where(a==2)
Out[72]: (array([2], dtype=int64),)

In [73]: np.nonzero(a==2)
Out[73]: (array([2], dtype=int64),)

时间比较

当搜索的项位于数组的开头%timeit在IPython shell中使用)时,仅检查大型数组的解决方案使用迭代器的解决方案会更快:

In [285]: a = np.arange(100000)

In [286]: %timeit next((idx for idx, val in np.ndenumerate(a) if val==0))
100000 loops, best of 3: 17.6 µs per loop

In [287]: %timeit np.argmax(a==0)
1000 loops, best of 3: 254 µs per loop

In [288]: %timeit np.where(a==0)[0][0]
1000 loops, best of 3: 314 µs per loop

这是NumPy GitHub的未解决问题

另请参阅:Numpy:快速找到价值的第一个索引

l.index(x) returns the smallest i such that i is the index of the first occurrence of x in the list.

One can safely assume that the index() function in Python is implemented so that it stops after finding the first match, and this results in an optimal average performance.

For finding an element stopping after the first match in a NumPy array use an iterator (ndenumerate).

In [67]: l=range(100)

In [68]: l.index(2)
Out[68]: 2

NumPy array:

In [69]: a = np.arange(100)

In [70]: next((idx for idx, val in np.ndenumerate(a) if val==2))
Out[70]: (2L,)

Note that both methods index() and next return an error if the element is not found. With next, one can use a second argument to return a special value in case the element is not found, e.g.

In [77]: next((idx for idx, val in np.ndenumerate(a) if val==400),None)

There are other functions in NumPy (argmax, where, and nonzero) that can be used to find an element in an array, but they all have the drawback of going through the whole array looking for all occurrences, thus not being optimized for finding the first element. Note also that where and nonzero return arrays, so you need to select the first element to get the index.

In [71]: np.argmax(a==2)
Out[71]: 2

In [72]: np.where(a==2)
Out[72]: (array([2], dtype=int64),)

In [73]: np.nonzero(a==2)
Out[73]: (array([2], dtype=int64),)

Time comparison

Just checking that for large arrays the solution using an iterator is faster when the searched item is at the beginning of the array (using %timeit in the IPython shell):

In [285]: a = np.arange(100000)

In [286]: %timeit next((idx for idx, val in np.ndenumerate(a) if val==0))
100000 loops, best of 3: 17.6 µs per loop

In [287]: %timeit np.argmax(a==0)
1000 loops, best of 3: 254 µs per loop

In [288]: %timeit np.where(a==0)[0][0]
1000 loops, best of 3: 314 µs per loop

This is an open NumPy GitHub issue.

See also: Numpy: find first index of value fast


回答 6

对于一维排序数组,使用numpy.searchsorted返回NumPy整数(位置)会更加简单有效。例如,

arr = np.array([1, 1, 1, 2, 3, 3, 4])
i = np.searchsorted(arr, 3)

只要确保数组已经排序

还要检查返回的索引i是否实际上包含被搜索的元素,因为searchsorted的主要目的是查找应该在其中插入元素以保持顺序的索引。

if arr[i] == 3:
    print("present")
else:
    print("not present")

For one-dimensional sorted arrays, it would be much more simpler and efficient O(log(n)) to use numpy.searchsorted which returns a NumPy integer (position). For example,

arr = np.array([1, 1, 1, 2, 3, 3, 4])
i = np.searchsorted(arr, 3)

Just make sure the array is already sorted

Also check if returned index i actually contains the searched element, since searchsorted’s main objective is to find indices where elements should be inserted to maintain order.

if arr[i] == 3:
    print("present")
else:
    print("not present")

回答 7

要根据任何条件建立索引,可以执行以下操作:

In [1]: from numpy import *
In [2]: x = arange(125).reshape((5,5,5))
In [3]: y = indices(x.shape)
In [4]: locs = y[:,x >= 120] # put whatever you want in place of x >= 120
In [5]: pts = hsplit(locs, len(locs[0]))
In [6]: for pt in pts:
   .....:         print(', '.join(str(p[0]) for p in pt))
4, 4, 0
4, 4, 1
4, 4, 2
4, 4, 3
4, 4, 4

这是一个快速执行list.index()的功能的函数,除非找不到该异常不会引发异常。当心-在大型阵列上这可能非常慢。如果您愿意将其用作方法,则可以将其修补到数组上。

def ndindex(ndarray, item):
    if len(ndarray.shape) == 1:
        try:
            return [ndarray.tolist().index(item)]
        except:
            pass
    else:
        for i, subarray in enumerate(ndarray):
            try:
                return [i] + ndindex(subarray, item)
            except:
                pass

In [1]: ndindex(x, 103)
Out[1]: [4, 0, 3]

To index on any criteria, you can so something like the following:

In [1]: from numpy import *
In [2]: x = arange(125).reshape((5,5,5))
In [3]: y = indices(x.shape)
In [4]: locs = y[:,x >= 120] # put whatever you want in place of x >= 120
In [5]: pts = hsplit(locs, len(locs[0]))
In [6]: for pt in pts:
   .....:         print(', '.join(str(p[0]) for p in pt))
4, 4, 0
4, 4, 1
4, 4, 2
4, 4, 3
4, 4, 4

And here’s a quick function to do what list.index() does, except doesn’t raise an exception if it’s not found. Beware — this is probably very slow on large arrays. You can probably monkey patch this on to arrays if you’d rather use it as a method.

def ndindex(ndarray, item):
    if len(ndarray.shape) == 1:
        try:
            return [ndarray.tolist().index(item)]
        except:
            pass
    else:
        for i, subarray in enumerate(ndarray):
            try:
                return [i] + ndindex(subarray, item)
            except:
                pass

In [1]: ndindex(x, 103)
Out[1]: [4, 0, 3]

回答 8

对于一维数组,我建议np.flatnonzero(array == value)[0],这相当于两np.nonzero(array == value)[0][0]np.where(array == value)[0][0],但避免了拆箱1-元件的元组的丑陋。

For 1D arrays, I’d recommend np.flatnonzero(array == value)[0], which is equivalent to both np.nonzero(array == value)[0][0] and np.where(array == value)[0][0] but avoids the ugliness of unboxing a 1-element tuple.


回答 9

从np.where()中选择第一个元素的替代方法是将生成器表达式与枚举一起使用,例如:

>>> import numpy as np
>>> x = np.arange(100)   # x = array([0, 1, 2, 3, ... 99])
>>> next(i for i, x_i in enumerate(x) if x_i == 2)
2

对于二维数组,可以这样做:

>>> x = np.arange(100).reshape(10,10)   # x = array([[0, 1, 2,... 9], [10,..19],])
>>> next((i,j) for i, x_i in enumerate(x) 
...            for j, x_ij in enumerate(x_i) if x_ij == 2)
(0, 2)

这种方法的优势在于,它会在找到第一个匹配项后停止检查数组的元素,而np.where会检查所有元素是否匹配。如果数组中的早期匹配项,则生成器表达式会更快。

An alternative to selecting the first element from np.where() is to use a generator expression together with enumerate, such as:

>>> import numpy as np
>>> x = np.arange(100)   # x = array([0, 1, 2, 3, ... 99])
>>> next(i for i, x_i in enumerate(x) if x_i == 2)
2

For a two dimensional array one would do:

>>> x = np.arange(100).reshape(10,10)   # x = array([[0, 1, 2,... 9], [10,..19],])
>>> next((i,j) for i, x_i in enumerate(x) 
...            for j, x_ij in enumerate(x_i) if x_ij == 2)
(0, 2)

The advantage of this approach is that it stops checking the elements of the array after the first match is found, whereas np.where checks all elements for a match. A generator expression would be faster if there’s match early in the array.


回答 10

NumPy中有很多操作可以组合在一起完成。这将返回等于item的元素的索引:

numpy.nonzero(array - item)

然后,您可以使用列表的第一个元素来获得一个元素。

There are lots of operations in NumPy that could perhaps be put together to accomplish this. This will return indices of elements equal to item:

numpy.nonzero(array - item)

You could then take the first elements of the lists to get a single element.


回答 11

numpy_indexed包(声明,我是它的作者)包含list.index为numpy.ndarray的矢量相当于; 那是:

sequence_of_arrays = [[0, 1], [1, 2], [-5, 0]]
arrays_to_query = [[-5, 0], [1, 0]]

import numpy_indexed as npi
idx = npi.indices(sequence_of_arrays, arrays_to_query, missing=-1)
print(idx)   # [2, -1]

该解决方案具有矢量化的性能,可推广到ndarrays,并具有多种处理缺失值的方法。

The numpy_indexed package (disclaimer, I am its author) contains a vectorized equivalent of list.index for numpy.ndarray; that is:

sequence_of_arrays = [[0, 1], [1, 2], [-5, 0]]
arrays_to_query = [[-5, 0], [1, 0]]

import numpy_indexed as npi
idx = npi.indices(sequence_of_arrays, arrays_to_query, missing=-1)
print(idx)   # [2, -1]

This solution has vectorized performance, generalizes to ndarrays, and has various ways of dealing with missing values.


回答 12

注意:这是针对python 2.7版本的

您可以使用lambda函数来解决此问题,并且它对NumPy数组和列表均有效。

your_list = [11, 22, 23, 44, 55]
result = filter(lambda x:your_list[x]>30, range(len(your_list)))
#result: [3, 4]

import numpy as np
your_numpy_array = np.array([11, 22, 23, 44, 55])
result = filter(lambda x:your_numpy_array [x]>30, range(len(your_list)))
#result: [3, 4]

你可以使用

result[0]

获取过滤元素的第一个索引。

对于python 3.6,请使用

list(result)

代替

result

Note: this is for python 2.7 version

You can use a lambda function to deal with the problem, and it works both on NumPy array and list.

your_list = [11, 22, 23, 44, 55]
result = filter(lambda x:your_list[x]>30, range(len(your_list)))
#result: [3, 4]

import numpy as np
your_numpy_array = np.array([11, 22, 23, 44, 55])
result = filter(lambda x:your_numpy_array [x]>30, range(len(your_list)))
#result: [3, 4]

And you can use

result[0]

to get the first index of the filtered elements.

For python 3.6, use

list(result)

instead of

result

-1在numpy重塑中是什么意思?

问题:-1在numpy重塑中是什么意思?

可以使用参数为-1的整形函数将numpy矩阵整形为向量。但我不知道-1在这里意味着什么。

例如:

a = numpy.matrix([[1, 2, 3, 4], [5, 6, 7, 8]])
b = numpy.reshape(a, -1)

结果b是:matrix([[1, 2, 3, 4, 5, 6, 7, 8]])

有人知道-1在这里意味着什么吗?并且似乎python赋予-1几种含义,例如:array[-1]表示最后一个元素。你能解释一下吗?

A numpy matrix can be reshaped into a vector using reshape function with parameter -1. But I don’t know what -1 means here.

For example:

a = numpy.matrix([[1, 2, 3, 4], [5, 6, 7, 8]])
b = numpy.reshape(a, -1)

The result of b is: matrix([[1, 2, 3, 4, 5, 6, 7, 8]])

Does anyone know what -1 means here? And it seems python assign -1 several meanings, such as: array[-1] means the last element. Can you give an explanation?


回答 0

提供新形状所需满足的标准是“新形状应与原始形状兼容”

numpy允许我们将新形状参数之一设为-1(例如:(2,-1)或(-1,3),但不提供(-1,-1))。它只是意味着它是一个未知的维,我们希望numpy弄清楚。numpy将通过查看 “数组的长度和剩余维数”并确保满足上述条件来解决这个问题

现在看示例。

z = np.array([[1, 2, 3, 4],
         [5, 6, 7, 8],
         [9, 10, 11, 12]])
z.shape
(3, 4)

现在尝试用(-1)重塑形状。结果新形状为(12,)并与原始形状(3,4)兼容

z.reshape(-1)
array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12])

现在尝试用(-1,1)重塑形状。我们将列设置为1,将行设置为unknown。因此我们得到的新形状为(12,1)。又与原始形状(3,4)兼容

z.reshape(-1,1)
array([[ 1],
   [ 2],
   [ 3],
   [ 4],
   [ 5],
   [ 6],
   [ 7],
   [ 8],
   [ 9],
   [10],
   [11],
   [12]])

以上与numpy建议/错误消息一致,reshape(-1,1)用于单个功能;即单列

array.reshape(-1, 1)如果数据具有单一功能,则使用来重塑数据

新形状为(-1,2)。未知行,第2列。我们得到的新形状为(6,2)

z.reshape(-1, 2)
array([[ 1,  2],
   [ 3,  4],
   [ 5,  6],
   [ 7,  8],
   [ 9, 10],
   [11, 12]])

现在尝试使列为未知。新形状为(1,-1)。即,行为1,列未知。我们得到的结果新形状为(1,12)

z.reshape(1,-1)
array([[ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12]])

以上与numpy建议/错误消息一致,reshape(1,-1)用于单个示例;即单排

使用数据array.reshape(1, -1)是否包含单个样本来重塑数据

新形状(2,-1)。第2行,列不明。我们得到的结果新形状为(2,6)

z.reshape(2, -1)
array([[ 1,  2,  3,  4,  5,  6],
   [ 7,  8,  9, 10, 11, 12]])

新形状为(3,-1)。第3行,列不明。我们得到的结果新形状为(3,4)

z.reshape(3, -1)
array([[ 1,  2,  3,  4],
   [ 5,  6,  7,  8],
   [ 9, 10, 11, 12]])

最后,如果我们尝试提供两个未知尺寸,即新形状为(-1,-1)。会抛出错误

z.reshape(-1, -1)
ValueError: can only specify one unknown dimension

The criterion to satisfy for providing the new shape is that ‘The new shape should be compatible with the original shape’

numpy allow us to give one of new shape parameter as -1 (eg: (2,-1) or (-1,3) but not (-1, -1)). It simply means that it is an unknown dimension and we want numpy to figure it out. And numpy will figure this by looking at the ‘length of the array and remaining dimensions’ and making sure it satisfies the above mentioned criteria

Now see the example.

z = np.array([[1, 2, 3, 4],
         [5, 6, 7, 8],
         [9, 10, 11, 12]])
z.shape
(3, 4)

Now trying to reshape with (-1) . Result new shape is (12,) and is compatible with original shape (3,4)

z.reshape(-1)
array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12])

Now trying to reshape with (-1, 1) . We have provided column as 1 but rows as unknown . So we get result new shape as (12, 1).again compatible with original shape(3,4)

z.reshape(-1,1)
array([[ 1],
   [ 2],
   [ 3],
   [ 4],
   [ 5],
   [ 6],
   [ 7],
   [ 8],
   [ 9],
   [10],
   [11],
   [12]])

The above is consistent with numpy advice/error message, to use reshape(-1,1) for a single feature; i.e. single column

Reshape your data using array.reshape(-1, 1) if your data has a single feature

New shape as (-1, 2). row unknown, column 2. we get result new shape as (6, 2)

z.reshape(-1, 2)
array([[ 1,  2],
   [ 3,  4],
   [ 5,  6],
   [ 7,  8],
   [ 9, 10],
   [11, 12]])

Now trying to keep column as unknown. New shape as (1,-1). i.e, row is 1, column unknown. we get result new shape as (1, 12)

z.reshape(1,-1)
array([[ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12]])

The above is consistent with numpy advice/error message, to use reshape(1,-1) for a single sample; i.e. single row

Reshape your data using array.reshape(1, -1) if it contains a single sample

New shape (2, -1). Row 2, column unknown. we get result new shape as (2,6)

z.reshape(2, -1)
array([[ 1,  2,  3,  4,  5,  6],
   [ 7,  8,  9, 10, 11, 12]])

New shape as (3, -1). Row 3, column unknown. we get result new shape as (3,4)

z.reshape(3, -1)
array([[ 1,  2,  3,  4],
   [ 5,  6,  7,  8],
   [ 9, 10, 11, 12]])

And finally, if we try to provide both dimension as unknown i.e new shape as (-1,-1). It will throw an error

z.reshape(-1, -1)
ValueError: can only specify one unknown dimension

回答 1

用于整形数组。

假设我们有一个尺寸为2 x 10 x 10的3维数组:

r = numpy.random.rand(2, 10, 10) 

现在我们要重塑为5 X 5 x 8:

numpy.reshape(r, shape=(5, 5, 8)) 

会做的工作。

请注意,一旦固定了第一个dim = 5和第二个dim = 5,就不需要确定第三维。为了帮助您懒惰,python提供了-1选项:

numpy.reshape(r, shape=(5, 5, -1)) 

将为您提供形状=(5,5,8)的数组。

同样

numpy.reshape(r, shape=(50, -1)) 

将为您提供形状=(50,4)的数组

您可以在http://anie.me/numpy-reshape-transpose-theano-dimshuffle/了解更多信息

Used to reshape an array.

Say we have a 3 dimensional array of dimensions 2 x 10 x 10:

r = numpy.random.rand(2, 10, 10) 

Now we want to reshape to 5 X 5 x 8:

numpy.reshape(r, shape=(5, 5, 8)) 

will do the job.

Note that, once you fix first dim = 5 and second dim = 5, you don’t need to determine third dimension. To assist your laziness, python gives the option of -1:

numpy.reshape(r, shape=(5, 5, -1)) 

will give you an array of shape = (5, 5, 8).

Likewise,

numpy.reshape(r, shape=(50, -1)) 

will give you an array of shape = (50, 4)

You can read more at http://anie.me/numpy-reshape-transpose-theano-dimshuffle/


回答 2

根据the documentation

newshape:int或int的元组

新形状应与原始形状兼容。如果是整数,则结果将是该长度的一维数组。一个形状尺寸可以为-1。在这种情况下,该值是根据数组的长度和其余维来推断的。

According to the documentation:

newshape : int or tuple of ints

The new shape should be compatible with the original shape. If an integer, then the result will be a 1-D array of that length. One shape dimension can be -1. In this case, the value is inferred from the length of the array and remaining dimensions.


回答 3

numpy.reshape(a,newshape,order {})检查以下链接以获取更多信息。 https://docs.scipy.org/doc/numpy/reference/generation/numpy.reshape.html

对于以下示例,您提到的输出将结果向量解释为单行。(-1)表示行数为1。

a = numpy.matrix([[1, 2, 3, 4], [5, 6, 7, 8]])
b = numpy.reshape(a, -1)

输出:

矩阵([[1、2、3、4、5、6、7、8]])

这可以用另一个示例更精确地解释:

b = np.arange(10).reshape((-1,1))

输出:(是一维列式数组)

数组([[0],

   [1],
   [2],
   [3],
   [4],
   [5],
   [6],
   [7],
   [8],
   [9]])

b = np.arange(10).reshape((1,-1))

输出:(是一维行数组)

数组([[0,1,2,3,4,5,6,7,8,9]])

numpy.reshape(a,newshape,order{}) check the below link for more info. https://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html

for the below example you mentioned the output explains the resultant vector to be a single row.(-1) indicates the number of rows to be 1. if the

a = numpy.matrix([[1, 2, 3, 4], [5, 6, 7, 8]])
b = numpy.reshape(a, -1)

output:

matrix([[1, 2, 3, 4, 5, 6, 7, 8]])

this can be explained more precisely with another example:

b = np.arange(10).reshape((-1,1))

output:(is a 1 dimensional columnar array)

array([[0],

   [1],
   [2],
   [3],
   [4],
   [5],
   [6],
   [7],
   [8],
   [9]])

b = np.arange(10).reshape((1,-1))

output:(is a 1 dimensional row array)

array([[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]])


回答 4

这很容易理解。“ -1”代表“未知尺寸”,可以从另一个尺寸推断出来。在这种情况下,如果您这样设置矩阵:

a = numpy.matrix([[1, 2, 3, 4], [5, 6, 7, 8]])

像这样修改矩阵:

b = numpy.reshape(a, -1)

它将对矩阵a调用一些默认操作,这将返回1-d numpy数组/矩阵。

但是,我认为使用这样的代码不是一个好主意。为什么不尝试:

b = a.reshape(1,-1)

它将为您提供相同的结果,并使读者更清楚地理解:将b设置为a的另一种形状。对于a,我们没有多少列(将其设置为-1!),但是我们想要一维数组(将第一个参数设置为1!)。

It is fairly easy to understand. The “-1” stands for “unknown dimension” which can should be infered from another dimension. In this case, if you set your matrix like this:

a = numpy.matrix([[1, 2, 3, 4], [5, 6, 7, 8]])

Modify your matrix like this:

b = numpy.reshape(a, -1)

It will call some deafult operations to the matrix a, which will return a 1-d numpy array/martrix.

However, I don’t think it is a good idea to use code like this. Why not try:

b = a.reshape(1,-1)

It will give you the same result and it’s more clear for readers to understand: Set b as another shape of a. For a, we don’t how much columns it should have(set it to -1!), but we want a 1-dimension array(set the first parameter to 1!).


回答 5

长话短说:您设置了一些尺寸,然后让NumPy设置了其余的尺寸。

(userDim1, userDim2, ..., -1) -->>

(userDim1, userDim1, ..., TOTAL_DIMENSION - (userDim1 + userDim2 + ...))

Long story short: you set some dimensions and let NumPy set the remaining(s).

(userDim1, userDim2, ..., -1) -->>

(userDim1, userDim1, ..., TOTAL_DIMENSION - (userDim1 + userDim2 + ...))

回答 6

这只是意味着您不确定可以提供多少行或列,而您正在让numpy建议要重整的列数或行数。

numpy提供了-1 https://docs.scipy.org/doc/numpy/reference/genic/numpy.reshape.html的最后一个示例

检查下面的代码及其输出以更好地了解(-1):

码:-

import numpy
a = numpy.matrix([[1, 2, 3, 4], [5, 6, 7, 8]])
print("Without reshaping  -> ")
print(a)
b = numpy.reshape(a, -1)
print("HERE We don't know about what number we should give to row/col")
print("Reshaping as (a,-1)")
print(b)
c = numpy.reshape(a, (-1,2))
print("HERE We just know about number of columns")
print("Reshaping as (a,(-1,2))")
print(c)
d = numpy.reshape(a, (2,-1))
print("HERE We just know about number of rows")
print("Reshaping as (a,(2,-1))")
print(d)

输出:-

Without reshaping  -> 
[[1 2 3 4]
 [5 6 7 8]]
HERE We don't know about what number we should give to row/col
Reshaping as (a,-1)
[[1 2 3 4 5 6 7 8]]
HERE We just know about number of columns
Reshaping as (a,(-1,2))
[[1 2]
 [3 4]
 [5 6]
 [7 8]]
HERE We just know about number of rows
Reshaping as (a,(2,-1))
[[1 2 3 4]
 [5 6 7 8]]

It simply means that you are not sure about what number of rows or columns you can give and you are asking numpy to suggest number of column or rows to get reshaped in.

numpy provides last example for -1 https://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html

check below code and its output to better understand about (-1):

CODE:-

import numpy
a = numpy.matrix([[1, 2, 3, 4], [5, 6, 7, 8]])
print("Without reshaping  -> ")
print(a)
b = numpy.reshape(a, -1)
print("HERE We don't know about what number we should give to row/col")
print("Reshaping as (a,-1)")
print(b)
c = numpy.reshape(a, (-1,2))
print("HERE We just know about number of columns")
print("Reshaping as (a,(-1,2))")
print(c)
d = numpy.reshape(a, (2,-1))
print("HERE We just know about number of rows")
print("Reshaping as (a,(2,-1))")
print(d)

OUTPUT :-

Without reshaping  -> 
[[1 2 3 4]
 [5 6 7 8]]
HERE We don't know about what number we should give to row/col
Reshaping as (a,-1)
[[1 2 3 4 5 6 7 8]]
HERE We just know about number of columns
Reshaping as (a,(-1,2))
[[1 2]
 [3 4]
 [5 6]
 [7 8]]
HERE We just know about number of rows
Reshaping as (a,(2,-1))
[[1 2 3 4]
 [5 6 7 8]]

回答 7

import numpy as np
x = np.array([[2,3,4], [5,6,7]]) 

# Convert any shape to 1D shape
x = np.reshape(x, (-1)) # Making it 1 row -> (6,)

# When you don't care about rows and just want to fix number of columns
x = np.reshape(x, (-1, 1)) # Making it 1 column -> (6, 1)
x = np.reshape(x, (-1, 2)) # Making it 2 column -> (3, 2)
x = np.reshape(x, (-1, 3)) # Making it 3 column -> (2, 3)

# When you don't care about columns and just want to fix number of rows
x = np.reshape(x, (1, -1)) # Making it 1 row -> (1, 6)
x = np.reshape(x, (2, -1)) # Making it 2 row -> (2, 3)
x = np.reshape(x, (3, -1)) # Making it 3 row -> (3, 2)
import numpy as np
x = np.array([[2,3,4], [5,6,7]]) 

# Convert any shape to 1D shape
x = np.reshape(x, (-1)) # Making it 1 row -> (6,)

# When you don't care about rows and just want to fix number of columns
x = np.reshape(x, (-1, 1)) # Making it 1 column -> (6, 1)
x = np.reshape(x, (-1, 2)) # Making it 2 column -> (3, 2)
x = np.reshape(x, (-1, 3)) # Making it 3 column -> (2, 3)

# When you don't care about columns and just want to fix number of rows
x = np.reshape(x, (1, -1)) # Making it 1 row -> (1, 6)
x = np.reshape(x, (2, -1)) # Making it 2 row -> (2, 3)
x = np.reshape(x, (3, -1)) # Making it 3 row -> (3, 2)

回答 8

转换的最终结果是,最终数组中的元素数量与初始数组或数据帧的元素数量相同。

-1对应于行或列的未知计数。我们可以将其视为x(未知)。x通过将原始数组中元素的数量除以有序对的其他值-1而获得。

例子

具有reshape(-1,1)的12个元素对应于x= 12/1 = 12行和1列的数组。


具有reshape(1,-1)的12个元素对应于具有1行x= 12/1 = 12列的数组。

The final outcome of the conversion is that the number of elements in the final array is same as that of the initial array or data frame.

-1 corresponds to the unknown count of the row or column. we can think of it as x(unknown). x is obtained by dividing the umber of elements in the original array by the other value of the ordered pair with -1.

Examples

12 elements with reshape(-1,1) corresponds to an array with x=12/1=12 rows and 1 column.


12 elements with reshape(1,-1) corresponds to an array with 1 row and x=12/1=12 columns.


如何将CSV数据读入NumPy中的记录数组?

问题:如何将CSV数据读入NumPy中的记录数组?

我不知道是否有一个CSV文件的内容导入到一个记录阵列直接的方式,很多的方式是R的read.table()read.delim()read.csv()家庭的进口数据与R的数据帧?

还是使用csv.reader()然后应用类似内容的最佳方法numpy.core.records.fromrecords()

I wonder if there is a direct way to import the contents of a CSV file into a record array, much in the way that R’s read.table(), read.delim(), and read.csv() family imports data to R’s data frame?

Or is the best way to use csv.reader() and then apply something like numpy.core.records.fromrecords()?


回答 0

您可以genfromtxt()通过将delimiterkwarg 设置为逗号来使用Numpy的方法。

from numpy import genfromtxt
my_data = genfromtxt('my_file.csv', delimiter=',')

有关该功能的更多信息,请参见其相应的文档

You can use Numpy’s genfromtxt() method to do so, by setting the delimiter kwarg to a comma.

from numpy import genfromtxt
my_data = genfromtxt('my_file.csv', delimiter=',')

More information on the function can be found at its respective documentation.


回答 1

我会read_csvpandas库中推荐该功能:

import pandas as pd
df=pd.read_csv('myfile.csv', sep=',',header=None)
df.values
array([[ 1. ,  2. ,  3. ],
       [ 4. ,  5.5,  6. ]])

这提供了一个熊猫DataFrame-允许许多有用的数据操作功能,而numpy记录数组无法直接使用这些功能

DataFrame是二维标记的数据结构,具有可能不同类型的列。您可以将其视为电子表格或SQL表…


我也建议genfromtxt。但是,由于该问题要求记录数组,而不是普通数组,因此dtype=None需要将参数添加到genfromtxt调用中:

给定一个输入文件,myfile.csv

1.0, 2, 3
4, 5.5, 6

import numpy as np
np.genfromtxt('myfile.csv',delimiter=',')

给出一个数组:

array([[ 1. ,  2. ,  3. ],
       [ 4. ,  5.5,  6. ]])

np.genfromtxt('myfile.csv',delimiter=',',dtype=None)

给出一个记录数组:

array([(1.0, 2.0, 3), (4.0, 5.5, 6)], 
      dtype=[('f0', '<f8'), ('f1', '<f8'), ('f2', '<i4')])

这样的优点是可以轻松导入具有多种数据类型(包括字符串)的文件。

I would recommend the read_csv function from the pandas library:

import pandas as pd
df=pd.read_csv('myfile.csv', sep=',',header=None)
df.values
array([[ 1. ,  2. ,  3. ],
       [ 4. ,  5.5,  6. ]])

This gives a pandas DataFrame – allowing many useful data manipulation functions which are not directly available with numpy record arrays.

DataFrame is a 2-dimensional labeled data structure with columns of potentially different types. You can think of it like a spreadsheet or SQL table…


I would also recommend genfromtxt. However, since the question asks for a record array, as opposed to a normal array, the dtype=None parameter needs to be added to the genfromtxt call:

Given an input file, myfile.csv:

1.0, 2, 3
4, 5.5, 6

import numpy as np
np.genfromtxt('myfile.csv',delimiter=',')

gives an array:

array([[ 1. ,  2. ,  3. ],
       [ 4. ,  5.5,  6. ]])

and

np.genfromtxt('myfile.csv',delimiter=',',dtype=None)

gives a record array:

array([(1.0, 2.0, 3), (4.0, 5.5, 6)], 
      dtype=[('f0', '<f8'), ('f1', '<f8'), ('f2', '<i4')])

This has the advantage that file with multiple data types (including strings) can be easily imported.


回答 2

我定时了

from numpy import genfromtxt
genfromtxt(fname = dest_file, dtype = (<whatever options>))

import csv
import numpy as np
with open(dest_file,'r') as dest_f:
    data_iter = csv.reader(dest_f,
                           delimiter = delimiter,
                           quotechar = '"')
    data = [data for data in data_iter]
data_array = np.asarray(data, dtype = <whatever options>)

在460万行,约70列的数据上,发现NumPy路径花费了2分16秒,而csv-list理解方法花费了13秒。

我建议使用csv-list理解方法,因为它很可能依赖于预编译的库,而不像NumPy那样依赖于解释器。我怀疑pandas方法会有类似的解释器开销。

I timed the

from numpy import genfromtxt
genfromtxt(fname = dest_file, dtype = (<whatever options>))

versus

import csv
import numpy as np
with open(dest_file,'r') as dest_f:
    data_iter = csv.reader(dest_f,
                           delimiter = delimiter,
                           quotechar = '"')
    data = [data for data in data_iter]
data_array = np.asarray(data, dtype = <whatever options>)

on 4.6 million rows with about 70 columns and found that the NumPy path took 2 min 16 secs and the csv-list comprehension method took 13 seconds.

I would recommend the csv-list comprehension method as it is most likely relies on pre-compiled libraries and not the interpreter as much as NumPy. I suspect the pandas method would have similar interpreter overhead.


回答 3

您也可以尝试使用recfromcsv()哪种方法可以猜测数据类型并返回格式正确的记录数组。

You can also try recfromcsv() which can guess data types and return a properly formatted record array.


回答 4

当我尝试使用NumPy和Pandas两种方式时,使用Pandas有很多优点:

  • 快点
  • 减少CPU使用率
  • 与NumPy genfromtxt相比1/3的RAM使用量

这是我的测试代码:

$ for f in test_pandas.py test_numpy_csv.py ; do  /usr/bin/time python $f; done
2.94user 0.41system 0:03.05elapsed 109%CPU (0avgtext+0avgdata 502068maxresident)k
0inputs+24outputs (0major+107147minor)pagefaults 0swaps

23.29user 0.72system 0:23.72elapsed 101%CPU (0avgtext+0avgdata 1680888maxresident)k
0inputs+0outputs (0major+416145minor)pagefaults 0swaps

test_numpy_csv.py

from numpy import genfromtxt
train = genfromtxt('/home/hvn/me/notebook/train.csv', delimiter=',')

test_pandas.py

from pandas import read_csv
df = read_csv('/home/hvn/me/notebook/train.csv')

资料档案:

du -h ~/me/notebook/train.csv
 59M    /home/hvn/me/notebook/train.csv

使用NumPy和pandas版本:

$ pip freeze | egrep -i 'pandas|numpy'
numpy==1.13.3
pandas==0.20.2

As I tried both ways using NumPy and Pandas, using pandas has a lot of advantages:

  • Faster
  • Less CPU usage
  • 1/3 RAM usage compared to NumPy genfromtxt

This is my test code:

$ for f in test_pandas.py test_numpy_csv.py ; do  /usr/bin/time python $f; done
2.94user 0.41system 0:03.05elapsed 109%CPU (0avgtext+0avgdata 502068maxresident)k
0inputs+24outputs (0major+107147minor)pagefaults 0swaps

23.29user 0.72system 0:23.72elapsed 101%CPU (0avgtext+0avgdata 1680888maxresident)k
0inputs+0outputs (0major+416145minor)pagefaults 0swaps

test_numpy_csv.py

from numpy import genfromtxt
train = genfromtxt('/home/hvn/me/notebook/train.csv', delimiter=',')

test_pandas.py

from pandas import read_csv
df = read_csv('/home/hvn/me/notebook/train.csv')

Data file:

du -h ~/me/notebook/train.csv
 59M    /home/hvn/me/notebook/train.csv

With NumPy and pandas at versions:

$ pip freeze | egrep -i 'pandas|numpy'
numpy==1.13.3
pandas==0.20.2

回答 5

您可以使用以下代码将CSV文件数据发送到数组中:

import numpy as np
csv = np.genfromtxt('test.csv', delimiter=",")
print(csv)

You can use this code to send CSV file data into an array:

import numpy as np
csv = np.genfromtxt('test.csv', delimiter=",")
print(csv)

回答 6

使用 numpy.loadtxt

一个非常简单的方法。但这要求所有元素都是浮点数(int等)

import numpy as np 
data = np.loadtxt('c:\\1.csv',delimiter=',',skiprows=0)  

Using numpy.loadtxt

A quite simple method. But it requires all the elements being float (int and so on)

import numpy as np 
data = np.loadtxt('c:\\1.csv',delimiter=',',skiprows=0)  

回答 7

这是最简单的方法:

import csv with open('testfile.csv', newline='') as csvfile: data = list(csv.reader(csvfile))

现在,数据中的每个条目都是一条记录,表示为一个数组。因此,您拥有一个2D阵列。它节省了我很多时间。

This is the easiest way:

import csv with open('testfile.csv', newline='') as csvfile: data = list(csv.reader(csvfile))

Now each entry in data is a record, represented as an array. So you have a 2D array. It saved me so much time.


回答 8

我尝试了这个:

import pandas as p
import numpy as n

closingValue = p.read_csv("<FILENAME>", usecols=[4], dtype=float)
print(closingValue)

I tried this:

import pandas as p
import numpy as n

closingValue = p.read_csv("<FILENAME>", usecols=[4], dtype=float)
print(closingValue)

回答 9

我建议使用表格(pip3 install tables)。您可以将.csv文件保存为.h5使用熊猫(pip3 install pandas),

import pandas as pd
data = pd.read_csv("dataset.csv")
store = pd.HDFStore('dataset.h5')
store['mydata'] = data
store.close()

然后,您可以轻松地以较少的时间(即使是处理大量数据)将数据加载到NumPy数组中

import pandas as pd
store = pd.HDFStore('dataset.h5')
data = store['mydata']
store.close()

# Data in NumPy format
data = data.values

I would suggest using tables (pip3 install tables). You can save your .csv file to .h5 using pandas (pip3 install pandas),

import pandas as pd
data = pd.read_csv("dataset.csv")
store = pd.HDFStore('dataset.h5')
store['mydata'] = data
store.close()

You can then easily, and with less time even for huge amount of data, load your data in a NumPy array.

import pandas as pd
store = pd.HDFStore('dataset.h5')
data = store['mydata']
store.close()

# Data in NumPy format
data = data.values

回答 10

这项工作令人着迷…

import csv
with open("data.csv", 'r') as f:
    data = list(csv.reader(f, delimiter=";"))

import numpy as np
data = np.array(data, dtype=np.float)

This work as a charm…

import csv
with open("data.csv", 'r') as f:
    data = list(csv.reader(f, delimiter=";"))

import numpy as np
data = np.array(data, dtype=np.float)

Mlcourse.ai-开放机器学习课程

mlcourse.ai是一门开放的机器学习课程,由OpenDataScience (ods.ai),由Yury Kashnitsky (yorko)尤里拥有应用数学博士学位和卡格尔竞赛大师学位,他的目标是设计一门理论与实践完美平衡的ML课程。因此,你可以在课堂上复习数学公式,并与Kaggle Inclass竞赛一起练习。目前,该课程正处于自定步模式检查一下详细的Roadmap引导您完成自定进度的课程。ai

奖金:此外,您还可以购买带有最佳非演示版本的奖励作业包mlcourse.ai任务。选择“Bonus Assignments” tier请参阅主页上的交易详情mlcourse.ai

镜子(🇬🇧-仅限):mlcourse.ai(主站点)、Kaggle Dataset(与Kaggle笔记本相同的笔记本)

自定

这个Roadmap将指导您度过11周的mlCourse.ai课程。每周,从熊猫到梯度助推,都会给出阅读什么文章、看什么讲座、完成什么作业的指示。

内容

这是medium.com上发表的文章列表🇬🇧,habr.com🇷🇺还提到了中文笔记本。🇨🇳并给出了指向Kaggle笔记本(英文)的链接。图标是可点击的

  1. 用PANDA软件进行探索性数据分析🇬🇧🇷🇺🇨🇳Kaggle Notebook
  2. 用Python进行可视化数据分析🇬🇧🇷🇺🇨🇳,Kaggle笔记本电脑:part1part2
  3. 分类、决策树和k近邻🇬🇧🇷🇺🇨🇳Kaggle Notebook
  4. 线性分类与回归🇬🇧🇷🇺🇨🇳,Kaggle笔记本电脑:part1part2part3part4part5
  5. 套袋与随机林🇬🇧🇷🇺🇨🇳,Kaggle笔记本电脑:part1part2part3
  6. 特征工程与特征选择🇬🇧🇷🇺🇨🇳Kaggle Notebook
  7. 无监督学习:主成分分析与聚类🇬🇧🇷🇺🇨🇳Kaggle Notebook
  8. Vowpal Wabbit:用千兆字节的数据学习🇬🇧🇷🇺🇨🇳Kaggle Notebook
  9. 用Python进行时间序列分析,第一部分🇬🇧🇷🇺🇨🇳使用Facebook Prophet预测未来,第2部分🇬🇧🇨🇳卡格尔笔记本:part1part2
  10. 梯度增压🇬🇧🇷🇺🇨🇳Kaggle Notebook

讲座

视频上传到thisYouTube播放列表。引言,videoslides

  1. 用熊猫进行探索性数据分析,video
  2. 可视化,EDA的主要情节,video
  3. 诊断树:theorypractical part
  4. Logistic回归:theoretical foundationspractical part(《爱丽丝》比赛中的基线)
  5. 合奏和随机森林-part 1分类指标-part 2预测客户付款的业务任务示例-part 3
  6. 线性回归和正则化-theory,Lasso&Ridge,LTV预测-practice
  7. 无监督学习-Principal Component AnalysisClustering
  8. 用于分类和回归的随机梯度下降-part 1,第2部分TBA
  9. 用Python(ARIMA,PERPHET)进行时间序列分析-video
  10. 梯度增压:基本思路-part 1、XgBoost、LightGBM和CatBoost+Practice背后的关键理念-part 2

作业

以下是演示作业。此外,在“Bonus Assignments” tier您可以访问非演示作业

  1. 用熊猫进行探索性数据分析,nbviewerKaggle Notebooksolution
  2. 分析心血管疾病数据,nbviewerKaggle Notebooksolution
  3. 带有玩具任务和UCI成人数据集的决策树,nbviewerKaggle Notebooksolution
  4. 讽刺检测,Kaggle Notebooksolution线性回归作为一个最优化问题,nbviewerKaggle Notebook
  5. Logistic回归和随机森林在信用评分问题中的应用nbviewerKaggle Notebooksolution
  6. 在回归任务中探索OLS、LASSO和随机森林nbviewerKaggle Notebooksolution
  7. 无监督学习,nbviewerKaggle Notebooksolution
  8. 实现在线回归,nbviewerKaggle Notebooksolution
  9. 时间序列分析,nbviewerKaggle Notebooksolution
  10. 在比赛中超越底线,Kaggle Notebook

卡格尔竞赛

  1. 如果可以,请抓住我:通过网页会话跟踪检测入侵者。Kaggle Inclass
  2. Dota 2获胜者预测。Kaggle Inclass

引用mlCourse.ai

如果你碰巧引用了mlcourse.ai在您的工作中,您可以使用此BibTeX记录:

@misc{mlcourse_ai,
    author = {Kashnitsky, Yury},
    title = {mlcourse.ai – Open Machine Learning Course},
    year = {2020},
    publisher = {GitHub},
    journal = {GitHub repository},
    howpublished = {\url{https://github.com/Yorko/mlcourse.ai}},
}

社区

讨论在#mlCourse_ai世界上最重要的一条航道OpenDataScience (ods.ai)松懈团队

课程是免费的,但你可以通过承诺以下内容来支持组织者Patreon(每月支持)或一次性付款Ko-fi


Numpy-使用Python进行科学计算的基础软件包

NumPy是使用Python进行科学计算所需的基本软件包

它提供:

  • 功能强大的N维数组对象
  • 复杂的(广播)功能
  • 集成C/C++和Fortran代码的工具
  • 有用的线性代数、傅里叶变换和随机数功能

测试:

NumPy需要pytest然后,可以使用以下命令在安装后运行测试:

python -c 'import numpy; numpy.test()'

呼吁捐款

NumPy项目欢迎您的专业知识和热情!

小的改进或修复总是值得赞赏的;问题被标记为“good
first issue”
可能是一个很好的起点。如果您正在考虑对源代码做出更大的贡献,请通过mailing
list
第一

编写代码并不是为NumPy做贡献的唯一方式。您还可以:

  • 审核拉式请求
  • 分流问题
  • 开发教程、演示文稿和其他教育材料
  • 维护和改进our website
  • 为我们的品牌资产和促销材料开发平面设计
  • 翻译网站内容
  • 帮助推广和接纳新的贡献者
  • 撰写拨款建议书,并协助其他筹款工作。

如果你不确定从哪里开始,或者你的技能如何适用,那就伸出援手吧!您可以在邮件列表上提问,也可以在GitHub上通过打开新问题或对已打开的相关问题发表评论来询问

我们首选的沟通渠道都是公开的,但如果您想先私下与我们交谈,请联系我们的社区协调员,地址为numpy-team@googlegroups.com或在松弛上(写入numpy-team@googlegroups.com以获取邀请)

我们还有一个两周一次的社区电话会议,详情在邮件列表上公布。我们非常欢迎您的加入

如果您刚开始为开源做出贡献,this
guide
帮助解释成功参与的原因、内容和方式

Data-science-ipython-notebooks-数据科学Python笔记本:深度学习

数据-科学-IPython-笔记本

索引

深度学习

演示深度学习功能的IPython笔记本

张量流教程

其他TensorFlow教程:

笔记本电脑 描述
tsf-basics 在TensorFlow中学习基本操作,TensorFlow是Google提供的各种感知和语言理解任务的库
tsf-linear 在TensorFlow中实现线性回归
tsf-logistic 在TensorFlow中实现Logistic回归
tsf-nn 在TensorFlow中实现最近邻居
tsf-alex 在TensorFlow中实现AlexNet
tsf-cnn 卷积神经网络在TensorFlow中的实现
tsf-mlp 在TensorFlow中实现多层感知器
tsf-rnn 递归神经网络在TensorFlow中的实现
tsf-gpu 了解TensorFlow中的基本多GPU计算
tsf-gviz 了解TensorFlow中的图形可视化
tsf-lviz 了解TensorFlow中的损耗可视化

张量流练习

笔记本电脑 描述
tsf-not-mnist 通过为TensorFlow中的培训、开发和测试创建带有格式化数据集的Pickle,了解简单的数据管理
tsf-fully-connected 在TensorFlow中使用Logistic回归和神经网络逐步训练更深更精确的模型
tsf-regularization 通过训练全连通网络对TensorFlow中的notMNIST字符进行分类来探索正则化技术
tsf-convolutions 在TensorFlow中创建卷积神经网络
tsf-word2vec 在TensorFlow中对Text8数据训练跳格模型
tsf-lstm 在TensorFlow中对Text8数据训练LSTM字符模型

Theano-教程

笔记本电脑 描述
theano-intro Theano简介,它允许您高效地定义、优化和计算涉及多维数组的数学表达式。它可以使用GPU并执行高效的符号微分
theano-scan 学习扫描,这是一种在Theano图中执行循环的机制
theano-logistic 在Theano中实现Logistic回归
theano-rnn 递归神经网络在Theano中的实现
theano-mlp 在Theano中实现多层感知器

Keras-教程

笔记本电脑 描述
角膜 KERAS是一个用Python编写的开源神经网络库。它可以在TensorFlow或Theano上运行
setup 了解教程目标以及如何设置Kera环境
intro-deep-learning-ann 介绍使用KERAS和人工神经网络(ANN)进行深度学习
theano 通过使用权重矩阵和梯度了解Theano
keras-otto 通过观看卡格尔·奥托挑战赛了解凯拉斯
ann-mnist 基于KERAS的MNIST人工神经网络的简单实现
conv-nets 使用KERAS了解卷积神经网络(CNN)
conv-net-1 使用KERA识别MNIST中的手写数字-第1部分
conv-net-2 使用KERA识别MNIST中的手写数字-第2部分
keras-models 将预先培训的型号(如VGG16、VGG19、ResNet50和Inception v3)与KERA配合使用
auto-encoders 了解有关KERAS自动编码器的信息
rnn-lstm 使用KERAS了解递归神经网络(RNN)
lstm-sentence-gen 了解与KERA配合使用长短期内存(LSTM)网络的RNN

深度学习-其他

笔记本电脑 描述
deep-dream 基于Caffe的计算机视觉程序,使用卷积神经网络来查找和增强图像中的图案

科学工具包-学习

演示SCRICKIT学习功能的IPython笔记本

笔记本电脑 描述
intro 介绍笔记本到SCRICKIT-学习。Scikit-Learning添加了对大型多维数组和矩阵的Python支持,以及对这些数组进行操作的高级数学函数库的大型库
knn 在SCRICKIT-LEARN中实现k-近邻
linear-reg 在SCRICKIT-LEARCH中实现线性回归
svm 在SCRKIT-LEARN中实现带核和不带核的支持向量机分类器
random-forest 在SCRICKIT-LEARN中实现随机森林分类器和回归器
k-means 在SCRICIT-LEARN中实现k-均值聚类
pca 主成分分析在SCRICIT-LEARCH中的实现
gmm 在SCRICIT-LEARN中实现高斯混合模型
validation 在SCRICKIT-LEARN中实现验证和模型选择

统计推理法

演示使用SciPy功能进行统计推断的IPython笔记本

笔记本电脑 描述
尖刺的 SciPy是构建在Python的Numpy扩展上的数学算法和便利函数的集合。它为用户提供用于操作和可视化数据的高级命令和类,从而大大增强了交互式Python会话的功能
effect-size 通过分析男性和女性的身高差异,探索量化效应大小的统计数据。使用行为危险因素监测系统(BRFSS)的数据来估计美国成年女性和男性的平均身高和标准偏差
sampling 利用BRFSS数据分析美国男女平均体重探索随机抽样
hypothesis 通过分析头胎婴儿与其他婴儿的差异来探索假设检验

熊猫

演示熊猫功能的IPython笔记本

笔记本电脑 描述
pandas 用Python编写的用于数据操作和分析的软件库。提供用于操作数值表和时间序列的数据结构和操作
github-data-wrangling 通过分析中的GitHub数据,了解如何加载、清理、合并和要素工程Viz回购
Introduction-to-Pandas 熊猫简介
Introducing-Pandas-Objects 了解熊猫对象
Data Indexing and Selection 了解有关熊猫中的数据索引和选择的信息
Operations-in-Pandas 了解有关在熊猫中操作数据的信息
Missing-Values 了解有关处理熊猫中丢失的数据的信息
Hierarchical-Indexing 了解有关熊猫中的分层索引的信息
Concat-And-Append 了解有关组合数据集的信息:在熊猫中合并和追加
Merge-and-Join 了解有关组合数据集的信息:在熊猫中合并和连接
Aggregation-and-Grouping 了解有关在熊猫中聚合和分组的信息
Pivot-Tables 了解有关熊猫中的透视表的信息
Working-With-Strings 了解有关熊猫中的矢量化字符串操作的信息
Working-with-Time-Series 了解有关在熊猫中使用时间序列的信息
Performance-Eval-and-Query 了解高性能熊猫:熊猫中的eval()和query()

Matplotlib

演示matplotlib功能的IPython笔记本

笔记本电脑 描述
matplotlib Python 2D绘图库,以各种硬拷贝格式和跨平台交互环境生成出版物质量数据
matplotlib-applied 将matplotlib可视化应用于Kaggle比赛以进行探索性数据分析。了解如何创建条形图、直方图、子图2格网、归一化图、散点图、子图和核密度估计图
Introduction-To-Matplotlib Matplotlib简介
Simple-Line-Plots 了解有关Matplotlib中的简单线条图的信息
Simple-Scatter-Plots 了解有关Matplotlib中的简单散点图的信息
Errorbars.ipynb 了解有关在Matplotlib中可视化错误的信息
Density-and-Contour-Plots 了解Matplotlib中的密度和等高线绘图
Histograms-and-Binnings 了解有关Matplotlib中的直方图、二进制和密度的信息
Customizing-Legends 了解有关在Matplotlib中自定义地块图例的信息
Customizing-Colorbars 了解有关在Matplotlib中自定义色带的信息
Multiple-Subplots 了解有关Matplotlib中的多个子图的信息
Text-and-Annotation 了解有关Matplotlib中的文本和注记的信息
Customizing-Ticks 了解有关在Matplotlib中自定义刻度的信息
Settings-and-Stylesheets 了解有关自定义Matplotlib的信息:配置和样式表
Three-Dimensional-Plotting 了解有关在Matplotlib中进行三维打印的信息
Geographic-Data-With-Basemap 了解有关在Matplotlib中使用底图的地理数据的信息
Visualization-With-Seaborn 了解有关海运可视化的信息

麻木的

演示NumPy功能的IPython笔记本

笔记本电脑 描述
numpy 添加了对大型多维数组和矩阵的Python支持,以及对这些数组进行运算的大型高级数学函数库
Introduction-to-NumPy NumPy简介
Understanding-Data-Types 了解有关Python中的数据类型的信息
The-Basics-Of-NumPy-Arrays 了解NumPy阵列的基础知识
Computation-on-arrays-ufuncs 了解有关NumPy数组的计算:泛函
Computation-on-arrays-aggregates 了解有关聚合的信息:NumPy中的最小值、最大值以及介于两者之间的所有内容
Computation-on-arrays-broadcasting 了解有关数组计算的信息:在NumPy中广播
Boolean-Arrays-and-Masks 了解有关NumPy中的比较、掩码和布尔逻辑的信息
Fancy-Indexing 了解NumPy中的奇特索引
Sorting 了解有关在NumPy中对数组进行排序的信息
Structured-Data-NumPy 了解结构化数据:NumPy的结构化数组

Python-Data

IPython笔记本,演示面向数据分析的Python功能

笔记本电脑 描述
data structures 使用元组、列表、字典、集学习Python基础知识
data structure utilities 学习Python操作,如切片、范围、xrange、二等分、排序、排序、反转、枚举、压缩、列表理解
functions 了解更高级的Python功能:函数作为对象、lambda函数、闭包、*args、**kwargs curying、生成器、生成器表达式、itertools
datetime 了解如何使用Python日期和时间:datetime、strftime、strptime、timeDelta
logging 了解有关使用RotatingFileHandler和TimedRotatingFileHandler进行Python日志记录的信息
pdb 了解如何使用交互式源代码调试器在Python中进行调试
unit tests 了解如何在Python中使用NOSE单元测试进行测试

Kaggle-and-Business分析

中使用的IPython笔记本kaggle竞争和业务分析

笔记本电脑 描述
titanic 预测泰坦尼克号上的生还者。学习数据清理、探索性数据分析和机器学习
churn-analysis 预测客户流失。练习逻辑回归、梯度增强分类器、支持向量机、随机森林和k近邻。包括对念力矩阵、ROC图、特征重要性、预测概率和校准/识别的讨论

电光

演示电光和HDFS功能的IPython笔记本

笔记本电脑 描述
spark 内存集群计算框架,对于某些应用程序速度最高可提高100倍,并且非常适合机器学习算法
hdfs 在大型群集中跨计算机可靠地存储非常大的文件

MapReduce-Python

演示使用mrjob功能的Hadoop MapReduce的IPython笔记本

笔记本电脑 描述
mapreduce-python 在Python中运行MapReduce作业,在本地或Hadoop群集上执行作业。演示Python代码中的Hadoop流以及单元测试和mrjob用于分析Elastic MapReduce上的Amazon S3存储桶日志的配置文件。Disco是另一个基于python的替代方案。

AWS

演示Amazon Web服务(AWS)和AWS工具功能的IPython笔记本

另请查看:

  • SAWS:增强型AWS命令行界面(CLI)
  • Awesome AWS:库、开源Repos、指南、博客和其他资源的精选列表
笔记本电脑 描述
boto 针对Python的官方AWS SDK
s3cmd 通过命令行与S3交互
s3distcp 组合较小的文件,并通过接受模式和目标文件将它们聚合在一起。S3DistCp还可用于将大量数据从S3传输到您的Hadoop群集
s3-parallel-put 将多个文件并行上传到S3
redshift 充当建立在大规模并行处理(MPP)技术之上的快速数据仓库
kinesis 通过每秒处理数千个数据流的能力实时流式传输数据
lambda 运行代码以响应事件,自动管理计算资源

命令

IPython笔记本,演示Linux、Git等的各种命令行

笔记本电脑 描述
linux 类UNIX且大多兼容POSIX的计算机操作系统。磁盘使用情况、拆分文件、grep、sed、curl、查看正在运行的进程、终端语法突出显示和Vim
anaconda 发布用于大规模数据处理、预测分析和科学计算的Python编程语言,旨在简化包管理和部署
ipython notebook 基于Web的交互式计算环境,您可以在其中将代码执行、文本、数学、绘图和富媒体组合到单个文档中
git 强调速度、数据完整性并支持分布式非线性工作流的分布式修订控制系统
ruby 用于与AWS命令行和Jekyll交互,Jekyll是可托管在GitHub页面上的博客框架
jekyll 简单、支持博客的静电站点生成器,适用于个人、项目或组织站点。呈现Markdown或Textile and Liquid模板,并生成一个完整的静电网站,准备好由Apache HTTP Server、NGINX或其他Web服务器提供服务
pelican 基于Python的Jekyll替代方案
django 高级Python Web框架,鼓励快速开发和干净、实用的设计。它对共享报告/分析和博客很有用。较轻的替代方案包括PyramidFlaskTornado,以及Bottle

杂项

演示各种功能的IPython笔记本

笔记本电脑 描述
regex 数据争论中有用的正则表达式小抄
algorithmia Algorithmia是一个算法市场。本笔记本展示了4种不同的算法:人脸检测、内容摘要、潜在狄利克雷分配和光学字符识别

笔记本-安装

python

Anaconda是Python编程语言的免费发行版,用于大规模数据处理、预测分析和科学计算,旨在简化包管理和部署

按照说明进行安装Anaconda或者更轻的miniconda

设备-设置

有关设置数据分析开发环境的详细说明、脚本和工具,请参阅dev-setup回购

跑步-笔记本

要查看交互式内容或修改IPython笔记本中的元素,必须首先克隆或下载存储库,然后再运行笔记本。有关IPython笔记本的更多信息可以找到here.

$ git clone https://github.com/donnemartin/data-science-ipython-notebooks.git
$ cd data-science-ipython-notebooks
$ jupyter notebook

使用Python 2.7.x测试的笔记本电脑

学分

贡献

欢迎投稿!有关错误报告或请求,请submit an issue

联系方式-信息

请随时与我联系,讨论任何问题、问题或评论

许可证

这个存储库包含各种内容;有些是由Donne Martin开发的,有些是来自第三方的。第三方内容在这些方提供的许可下分发

由Donne Martin开发的内容按照以下许可证分发:

我在开放源码许可下向您提供此存储库中的代码和资源。因为这是我的个人存储库,您获得的我的代码和资源的许可证来自我,而不是我的雇主(Facebook)

Copyright 2015 Donne Martin

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

PythonDataScienceHandbook-Python数据科学手册:Jupyter笔记本全文

如何使用本书

关于

本书是使用Python3.5编写和测试的,尽管其他Python版本(包括Python2.7)几乎可以在所有情况下运行

本书介绍了在Python中使用数据所必需的核心库:特别是IPythonNumPyPandasMatplotlibScikit-Learn,以及相关的软件包。假设您熟悉作为一种语言的Python;如果您需要快速介绍该语言本身,请参阅免费的配套项目,A Whirlwind Tour of Python:这是一本针对研究人员和科学家的快节奏Python语言入门教程

看见Index.ipynb有关可与正文一起使用的笔记本的索引,请参阅

软件

书中的代码使用Python 3.5进行了测试,但大多数(但不是全部)也可以在Python 2.7和其他较早的Python版本中正常运行

中列出了我用来运行书中代码的包requirements.txt(请注意,其中一些确切的版本号可能在您的平台上不可用:您可能需要调整它们以供您自己使用)。要使用以下命令安装需求,请执行以下操作conda,请在命令行中运行以下命令:

$ conda install --file requirements.txt

要创建名为的独立环境,请执行以下操作PDSH对于Python 3.5和所有必需的软件包版本,请运行以下命令:

$ conda create -n PDSH python=3.5 --file requirements.txt

中可以阅读有关使用Conda环境的更多信息Managing Environments部分的CONDA文档

许可证

代码

此存储库中的代码(包括上面列出的笔记本中的所有代码示例)发布在MIT license有关更多信息,请访问Open Source Initiative

文本

这本书的正文内容在CC-BY-NC-ND license欲了解更多信息,请访问Creative Commons

Pytorch-强GPU加速的Python中的张量和动态神经网络

PyTorch是一个Python软件包,提供了两个高级功能。

张量计算(如NumPy),具有强大的GPU加速能力,建立在基于磁带的autograd系统上的深度神经网络,在需要的时候,你可以重复使用你最喜欢的Python包,如NumPy、SciPy和Cython,来扩展PyTorch。

系统 3.6 3.7 3.8
Linux CPU
Linux GPU
Windows CPU/GPU
Linux(Ppc64le)CPU
Linux(Ppc64le)GPU
Linux(Aarch64)CPU

另请参阅ci.pytorch.org HUD

更多关于PyTorch的信息

在粒度级别上,PyTorch是一个由以下组件组成的库:

组件 描述
火炬 像NumPy这样的张量器库,具有强大的GPU支持
torch.autograd 基于磁带的自动区分库,支持TORCH中的所有可微分张量操作
torch.jit 从PyTorch代码创建可序列化和可优化模型的编译堆栈(TorchScript)
torch.nn 与Autograd深度集成的神经网络库,旨在实现最大的灵活性
torch.multiprocessing Python多处理,但具有跨进程共享火炬张量的神奇内存。适用于数据加载和HogWild培训
torch.utils 为方便起见,DataLoader和其他实用程序功能

通常,PyTorch用作以下任一用途:

  • 替代NumPy使用GPU的功能
  • 提供最大灵活性和速度的深度学习研究平台

进一步阐述:

一种支持GPU的张量库

如果您使用NumPy,则您使用的是张量(也称为(Ndarray)

PyTorch提供的张量既可以在CPU上运行,也可以在GPU上运行,从而将计算速度大幅提高

我们提供各种各样的张量例程来加速和满足您的科学计算需求,例如切片、索引、数学运算、线性代数、约简。而且他们跑得很快!

动态神经网络:基于磁带的自动评分

PyTorch有一种构建神经网络的独特方式:使用和重放磁带录音机

大多数框架,如TensorFlow、Theano、Caffe和CNTK都有静电的世界观。人们必须建立一个神经网络,并一次又一次地重复使用相同的结构。改变网络的行为方式意味着必须从头开始

对于PyTorch,我们使用一种称为反向模式自动区分的技术,该技术允许您在没有延迟或开销的情况下任意更改网络的行为方式。我们的灵感来自于几篇关于这一主题的研究论文,以及目前和过去的工作,如手电筒-自动分级自动评分链条

虽然这种技术不是PyTorch独有的,但它是迄今为止最快的实现之一。你在疯狂的研究中获得了最快的速度和最好的灵活性

Python优先

PyTorch不是到单一C++框架的Python绑定。它是为深度集成到Python而构建的。你可以像以前一样自然地使用它NumPy/科学Py/科学工具包-学习等。您可以用Python本身编写新的神经网络层,使用您喜欢的库并使用包,如CythonNumba我们的目标是不在适当的地方重新发明轮子。

势在必行的经验

PyTorch被设计为直观、线性的思想,并且易于使用。当您执行一行代码时,它就会被执行。没有异步的世界观。当您进入调试器或接收错误消息和堆栈跟踪时,理解它们很简单。堆栈跟踪准确地指向定义代码的位置。我们希望您永远不要因为错误的堆栈跟踪或异步且不透明的执行引擎而花费数小时调试您的代码

快速精益

PyTorch的框架开销最小。我们集成了加速库,如英特尔MKL和NVIDIA(CuDNNNCCL)以最大限度地提高速度。在核心上,其CPU和GPU张量以及神经网络后端(TH、THC、THNN、THCUNN)已经成熟,并且经过多年的测试

因此,PyTorch是相当快的-无论您运行的是小型神经网络还是大型神经网络

与Torch或某些替代方案相比,PyTorch中的内存使用效率非常高。我们已经为GPU编写了自定义内存分配器,以确保您的深度学习模型具有最高的内存效率。这使您能够训练比以前更大的深度学习模型

无痛延长

编写新的神经网络模块,或者与PyTorch的张量API接口,设计得简单明了,抽象最少

您可以使用Torch API在Python中编写新的神经网络图层或者您最喜欢的基于NumPy的库,如SciPy

如果您想用C/C++编写您的层,我们提供了一个方便的扩展API,它是高效的,并且具有最少的样板。不需要编写包装器代码。你可以看到此处提供教程这里有一个例子

安装

二进制文件

通过conda或pip轮从二进制文件安装的命令在我们的网站上提供:https://pytorch.org

NVIDIA Jetson平台

NVIDIA的Jetson Nano、Jetson TX2和Jetson AGX Xavier的Python轮可通过以下URL获得:

它们需要JetPack 4.2和更高版本,以及@达斯蒂-内华达州维护它们

来自源

如果从源代码安装,则需要Python 3.6.2或更高版本和C++14编译器。此外,我们强烈建议您安装蟒蛇环境。您将获得一个高质量的BLAS库(MKL),并且无论您的Linux发行版是什么,您都可以获得受控的依赖项版本

一旦你有了蟒蛇已安装,以下是说明

如果要使用CUDA支持进行编译,请安装

如果要禁用CUDA支持,请导出环境变量USE_CUDA=0其他可能有用的环境变量可以在setup.py

如果您正在为NVIDIA的Jetson平台(Jetson Nano、TX1、TX2、AGX Xavier)构建,请参阅以下安装PyTorch for Jetson Nano的说明此处提供

如果要使用ROCM支持进行编译,请安装

  • AMD ROCM4.0及更高版本的安装
  • ROCM目前仅支持Linux系统

如果要禁用ROCM支持,请导出环境变量USE_ROCM=0其他可能有用的环境变量可以在setup.py

安装依赖项

常见

conda install astunparse numpy ninja pyyaml mkl mkl-include setuptools cmake cffi typing_extensions future six requests dataclasses

在Linux上

# CUDA only: Add LAPACK support for the GPU if needed
conda install -c pytorch magma-cuda110  # or the magma-cuda* that matches your CUDA version from https://anaconda.org/pytorch/repo

在MacOS上

# Add these packages if torch.distributed is needed
conda install pkg-config libuv

在Windows上

# Add these packages if torch.distributed is needed.
# Distributed package support on Windows is a prototype feature and is subject to changes.
conda install -c conda-forge libuv=1.39

获取PyTorch源代码

git clone --recursive https://github.com/pytorch/pytorch
cd pytorch
# if you are updating an existing checkout
git submodule sync
git submodule update --init --recursive --jobs 0

安装PyTorch

在Linux上

export CMAKE_PREFIX_PATH=${CONDA_PREFIX:-"$(dirname $(which conda))/../"}
python setup.py install

请注意,如果您正在为ROCM编译,则必须首先运行此命令:

python tools/amd_build/build_amd.py

请注意,如果您使用的是Python,您可能会遇到链接器导致的错误:

build/temp.linux-x86_64-3.7/torch/csrc/stub.o: file not recognized: file format not recognized
collect2: error: ld returned 1 exit status
error: command 'g++' failed with exit status 1

这是由以下原因引起的ld从Conda环境跟踪系统ld您应该使用较新版本的Python来修复此问题。推荐的Python版本为3.6.10+、3.7.6+和3.8.1+

在MacOS上

export CMAKE_PREFIX_PATH=${CONDA_PREFIX:-"$(dirname $(which conda))/../"}
MACOSX_DEPLOYMENT_TARGET=10.9 CC=clang CXX=clang++ python setup.py install

每个CUDA版本仅支持一个特定的XCode版本。据报道,以下组合可与PyTorch配合使用

CUDA版 Xcode版本
10.0 Xcode 9.4
10.1 Xcode 10.1

在Windows上

选择正确的Visual Studio版本

在Visual Studio的新版本中有时会出现回归,因此最好使用相同的Visual Studio版本16.8.5作为Pytorch CI。虽然PyTorch CI使用Visual Studio BuildTools,但您可以使用Visual Studio Enterprise、Professional或Community

如果您想构建遗留的python代码,请参阅在遗留代码和CUDA的基础上构建

使用CPU构建

使用CPU构建相当容易

有关OpenMP的说明:所需的OpenMP实施是英特尔OpenMP(IOMP)。为了链接到iomp,您需要手动下载库并通过调整设置构建环境CMAKE_INCLUDE_PATHLIB该说明这里是设置MKL和英特尔OpenMP的示例。如果没有这些CMake配置,将使用Microsoft Visual C OpenMP运行时(vcomp

使用CUDA构建

NVTX是使用CUDA构建Pytorch所必需的。NVTX是CUDA分布式的一部分,被称为“NSight Compute”。要将其安装到已安装的CUDA上,请再次运行CUDA安装并选中相应的复选框。确保在Visual Studio之后安装带Night Compute的CUDA

目前支持VS 2017/2019,支持忍者作为CMake的生成器。如果ninja.exe在以下位置检测到PATH,则使用忍者作为默认生成器,否则将使用VS 2017/2019
如果选择忍者作为生成器,则会选择最新的MSVC作为底层工具链

其他库,如岩浆oneDNN,也称为MKLDNN或DNNL,以及Sccache是经常需要的。请参阅安装帮助器要安装它们,请执行以下操作

您可以参考build_pytorch.bat其他一些环境变量配置的脚本

cmd

:: [Optional] If you want to build with the VS 2017 generator for old CUDA and PyTorch, please change the value in the next line to `Visual Studio 15 2017`.
:: Note: This value is useless if Ninja is detected. However, you can force that by using `set USE_NINJA=OFF`.
set CMAKE_GENERATOR=Visual Studio 16 2019

:: Read the content in the previous section carefully before you proceed.
:: [Optional] If you want to override the underlying toolset used by Ninja and Visual Studio with CUDA, please run the following script block.
:: "Visual Studio 2019 Developer Command Prompt" will be run automatically.
:: Make sure you have CMake >= 3.12 before you do this when you use the Visual Studio generator.
set CMAKE_GENERATOR_TOOLSET_VERSION=14.27
set DISTUTILS_USE_SDK=1
for /f "usebackq tokens=*" %i in (`"%ProgramFiles(x86)%\Microsoft Visual Studio\Installer\vswhere.exe" -version [15^,16^) -products * -latest -property installationPath`) do call "%i\VC\Auxiliary\Build\vcvarsall.bat" x64 -vcvars_ver=%CMAKE_GENERATOR_TOOLSET_VERSION%

:: [Optional] If you want to override the CUDA host compiler
set CUDAHOSTCXX=C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.27.29110\bin\HostX64\x64\cl.exe

python setup.py install
调整生成选项(可选)

您可以通过执行以下操作来调整cmake变量的配置(无需首先构建)。例如,可以通过这样的步骤来调整CuDNN或BLAS的预先检测的目录

在Linux上

export CMAKE_PREFIX_PATH=${CONDA_PREFIX:-"$(dirname $(which conda))/../"}
python setup.py build --cmake-only
ccmake build  # or cmake-gui build

在MacOS上

export CMAKE_PREFIX_PATH=${CONDA_PREFIX:-"$(dirname $(which conda))/../"}
MACOSX_DEPLOYMENT_TARGET=10.9 CC=clang CXX=clang++ python setup.py build --cmake-only
ccmake build  # or cmake-gui build

Docker镜像

使用预构建映像

您还可以从Docker Hub获取预构建的坞站映像,并使用Docker v19.03+运行

docker run --gpus all --rm -ti --ipc=host pytorch/pytorch:latest

请注意,PyTorch使用共享内存在进程之间共享数据,因此如果使用Torch多处理(例如,对于多线程数据加载器),运行容器的默认共享内存段大小是不够的,您应该使用以下两种方法之一来增加共享内存大小--ipc=host--shm-size命令行选项用于nvidia-docker run

自己打造形象

注:必须使用18.06以上的坞站版本构建

这个Dockerfile用于构建支持CUDA 11.1和cuDNN V8的映像。你可以通过PYTHON_VERSION=x.yMake Variable指定Miniconda要使用的Python版本,或将其保留为未设置为使用默认版本

make -f docker.Makefile
# images are tagged as docker.io/${your_docker_username}/pytorch

构建文档

要构建各种格式的文档,您需要狮身人面像以及阅读文档的主题

cd docs/
pip install -r requirements.txt

然后,您可以通过运行以下命令来生成文档make <format>docs/文件夹。跑make要获取所有可用输出格式的列表,请执行以下操作

如果运行Katex错误npm install katex如果它持续存在,请尝试npm install -g katex

以前的版本

早期PyTorch版本的安装说明和二进制文件可在以下位置找到我们的网站

快速入门

帮助您入门的三点建议:

资源

沟通

发布和贡献

PyTorch有90天的发布周期(主要版本)。如果您通过以下方式遇到错误,请通知我们提交问题

我们感谢所有的贡献。如果您计划回馈错误修复,请在不做任何进一步讨论的情况下这样做

如果您计划为核心贡献新的功能、实用程序功能或扩展,请先打开一个问题并与我们讨论该功能。未经讨论发送PR可能最终导致拒绝PR,因为我们可能会将核心带到与您可能意识到的方向不同的方向

要了解更多关于为Pytorch做出贡献的信息,请参阅我们的投稿页面

团队

PyTorch是一个社区驱动的项目,有几个熟练的工程师和研究人员参与其中

PyTorch目前由亚当·帕兹克萨姆·格罗斯苏史密斯·钦塔拉格雷戈里·查南(Gregory Chanan)主要贡献来自于数以百计的各种形式和手段的人才。值得一提的是:特雷弗·基林(Trevor Killeen)、萨桑克·奇拉姆库尔蒂(Sasank Chilamkurthy)、谢尔盖·扎戈鲁伊科(Sergey Zagoruyko)、亚当·莱勒(Adam Lerer)、弗朗西斯科·马萨(Francisco Massa)、阿利汗·特贾尼(Alykhan Tejani)、卢卡·安提加(Luca Antiga)、阿尔班·德斯迈森(Alban Desmaison)、安德烈亚斯·科普夫(Andreas Koepf)、詹姆斯·布拉德伯里(James Bradbury)、林泽明、田远东、纪尧姆·兰普尔(Guillaume Lample

注:此项目与哈伯金/火炬同名同姓。休是Torch社区的一位有价值的贡献者,并在Torch和PyTorch的许多事情上提供了帮助

许可证

PyTorch具有BSD样式的许可证,可以在许可证

PythonDataScienceHandbook-Python数据科学手册:Jupyter笔记本全文

Python Data Science Handbook

该存储库包含完整的Python数据科学手册,其形式为(免费!)Jupyter笔记本

如何使用本书

  • 请访问https://jakevdp.github.io/PythonDataScienceHandbook/在线阅读整本书
  • 使用此存储库的笔记本目录中提供的Jupyter笔记本运行代码
  • 使用Google Colab启动这些笔记本的可执行版本:
  • 使用活页夹使用以下笔记本启动实时笔记本服务器:
  • 通过O‘Reilly Media购买印刷书籍

关于

本书是使用Python3.5编写和测试的,尽管其他Python版本(包括Python2.7)几乎可以在所有情况下运行

本书介绍了在Python中使用数据所必需的核心库:特别是IPython、NumPy、Pandas、Matplotlib、Scikit-Learning和相关包。假设您熟悉Python作为一种语言;如果您需要快速介绍该语言本身,请参阅免费的配套项目-Python旋风之旅:这是针对研究人员和科学家的快速Python语言介绍

请参见Index.ipynb以获取可与文本一起使用的笔记本的索引

软件

书中的代码使用Python 3.5进行了测试,但大多数(但不是全部)也可以在Python 2.7和其他较早的Python版本中正常运行

我用来运行这本书中的代码的包列在Requirements.txt中(请注意,其中一些确切的版本号在您的平台上可能不可用:您可能必须调整它们以供您自己使用)。要使用CONDA安装需求,请在命令行运行以下命令:

$ conda install --file requirements.txt

要使用Python 3.5和所有必需的软件包版本创建名为pdsh的独立环境,请运行以下命令:

$ conda create -n PDSH python=3.5 --file requirements.txt

您可以在Conda文档的管理环境一节中阅读有关使用Conda环境的更多信息

许可证

代码

此存储库中的代码,包括上面列出的笔记本中的所有代码示例,都是在MIT许可下发布的。阅读更多关于开放源码计划的内容

文本

本书的文本内容在CC-by-NC-ND许可下发布。在知识共享网站上阅读更多内容