精华内容
下载资源
问答
  • 2021-07-16 20:19:02

    np.arange()

    np.arange()函数返回一个有终点和起点的固定步长的排列,如[1,2,3,4,5],起点是1,终点是6,步长为1。
    参数个数情况: np.arange()函数分为一个参数,两个参数,三个参数三种情况

    1. 一个参数时,参数值为终点,起点取默认值0,步长取默认值1。
    2. 两个参数时,第一个参数为起点,第二个参数为终点,步长取默认值1。
    3. 三个参数时,第一个参数为起点,第二个参数为终点,第三个参数为步长。其中步长支持小数
       
    # 一个参数 默认起点0,步长为1 输出:[0 1 2 3 4 5]
    a = np.arange(5)
    
    # 两个参数 默认步长为1 输出[3 4 5]
    a = np.arange(3,6)
    
    # 三个参数 起点为0,终点为3,步长为0.5 输出[ 0.   0.5   1.   1.5   2.   2.5]
    a = np.arange(0, 3, 0.5)

    当使用非整数步长(如0.1)时,结果往往不一致。这些情况下最好使用linspace。

    >>> np.linspace(2.0, 3.0, num=5)
    array([ 2.  ,  2.25,  2.5 ,  2.75,  3.  ])
    >>> np.linspace(2.0, 3.0, num=5, endpoint=False)
    array([ 2. ,  2.2,  2.4,  2.6,  2.8])
    >>> np.linspace(2.0, 3.0, num=5, retstep=True)
    (array([ 2.  ,  2.25,  2.5 ,  2.75,  3.  ]), 0.25)

    range()

    函数语法:
    range(stop)
    range(start, stop[, step])

    参数说明:

    • start: 计数从 start 开始。默认是从 0 开始。例如range(5)等价于range(0, 5);
    • stop: 计数到 stop 结束,但不包括 stop。例如:range(0, 5) 是[0, 1, 2, 3, 4]没有5
    • step:步长,默认为1。例如:range(0, 5) 等价于 range(0, 5, 1)
    >>>range(5)
    range(0, 5)
    >>> for i in range(5):
    ...     print(i)
    ... 
    0
    1
    2
    3
    4
    >>> list(range(5))
    [0, 1, 2, 3, 4]
    >>> list(range(0))
    []

    有两个参数或三个参数的情况(第二种构造方法):

    >>>list(range(0, 30, 5))
    [0, 5, 10, 15, 20, 25]
    >>> list(range(0, 10, 2))
    [0, 2, 4, 6, 8]
    >>> list(range(0, -10, -1))
    [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
    >>> list(range(1, 0))
    []

    注意range()和np.arange()区别

    arange()是Numpy中的函数,它和python自带函数range()的功能貌似比较相同。但是range()和np.arange()有一些区别:

    1. range()和np.arange()的返回类型不同,range()返回的是range这个object,而np.arange()返回的是ndarray类型;
    2. range()不支持步长为小数,而np.arange()支持步长(step)为小数;
    3. range()和np.arange()都可用于迭代;
    4. range()和np.arange()都有三个参数,以第一个参数为起点,第三个参数为步长,截止到第二个参数之前的不包括第二个参数的数据序列。
    5. range()可用于迭代,而np.arange()作用远不止于此,它是一个序列,可被当做向量使用。
       
    更多相关内容
  • np.arange() 详细教程

    千次阅读 2020-11-27 08:37:24
    NumPyis the fundamental Python library for numerical computing.... NumPy offers a lot ofarray creation routinesfor different circumstances.arange()is one such function based onnumerical ranges. It...

    NumPy is the fundamental Python library for numerical computing. Its most important type is an array type called ndarray. NumPy offers a lot of array creation routines for different circumstances. arange() is one such function based on numerical ranges. It’s often referred to as np.arange() because np is a widely used abbreviation for NumPy.

    Creating NumPy arrays is important when you’re working with other Python libraries that rely on them, like SciPyPandas, Matplotlib, scikit-learn, and more. NumPy is suitable for creating and working with arrays because it offers useful routines, enables performance boosts, and allows you to write concise code.

    By the end of this article, you’ll know:

    • What np.arange() is
    • How to use np.arange()
    • How np.arange() compares to the Python built-in class range
    • Which routines are similar to np.arange()

    Let’s see np.arange() in action!

    Free Bonus: Click here to get access to a free NumPy Resources Guide that points you to the best tutorials, videos, and books for improving your NumPy skills.

     

     Remove ads

    Return Value and Parameters of np.arange()

    NumPy arange() is one of the array creation routines based on numerical ranges. It creates an instance of ndarray with evenly spaced values and returns the reference to it.

    You can define the interval of the values contained in an array, space between them, and their type with four parameters of arange():

    numpy.arange([start, ]stop, [step, ], dtype=None) -> numpy.ndarray
    

    The first three parameters determine the range of the values, while the fourth specifies the type of the elements:

    1. start is the number (integer or decimal) that defines the first value in the array.
    2. stop is the number that defines the end of the array and isn’t included in the array.
    3. step is the number that defines the spacing (difference) between each two consecutive values in the array and defaults to 1.
    4. dtype is the type of the elements of the output array and defaults to None.

    step can’t be zero. Otherwise, you’ll get a ZeroDivisionError. You can’t move away anywhere from start if the increment or decrement is 0.

    If dtype is omitted, arange() will try to deduce the type of the array elements from the types of startstop, and step.

    You can find more information on the parameters and the return value of arange() in the official documentation.

    Range Arguments of np.arange()

    The arguments of NumPy arange() that define the values contained in the array correspond to the numeric parameters startstop, and step. You have to pass at least one of them.

    The following examples will show you how arange() behaves depending on the number of arguments and their values.

    Providing All Range Arguments

    When working with NumPy routines, you have to import NumPy first:

    >>>

    >>> import numpy as np
    

    Now, you have NumPy imported and you’re ready to apply arange().

    Let’s see a first example of how to use NumPy arange():

    >>>

    >>> np.arange(start=1, stop=10, step=3)
    array([1, 4, 7])
    

    In this example, start is 1. Therefore, the first element of the obtained array is 1step is 3, which is why your second value is 1+3, that is 4, while the third value in the array is 4+3, which equals 7.

    Following this pattern, the next value would be 10 (7+3), but counting must be ended beforestop is reached, so this one is not included.

    You can pass startstop, and step as positional arguments as well:

    >>>

    >>> np.arange(1, 10, 3)
    array([1, 4, 7])
    

    This code sample is equivalent to, but more concise than the previous one.

    The value of stop is not included in an array. That’s why you can obtain identical results with different stop values:

    >>>

    >>> np.arange(1, 8, 3)
    array([1, 4, 7])
    

    This code sample returns the array with the same values as the previous two. You can get the same result with any value of stop strictly greater than 7 and less than or equal to 10.

    However, if you make stop greater than 10, then counting is going to end after 10 is reached:

    >>>

    >>> np.arange(1, 10.1, 3)
    array([ 1.,  4.,  7., 10.])
    

    In this case, you get the array with four elements that includes 10.

    Notice that this example creates an array of floating-point numbers, unlike the previous one. That’s because you haven’t defined dtype, and arange() deduced it for you. You’ll learn more about this later in the article.

    You can see the graphical representations of these three examples in the figure below:

    NumPy arange() in action

    start is shown in green, stop in red, while step and the values contained in the arrays are blue.

    As you can see from the figure above, the first two examples have three values (14, and 7) counted. They don’t allow 10 to be included. In the third example, stop is larger than 10, and it is contained in the resulting array.

     

     Remove ads

    Providing Two Range Arguments

    You can omit step. In this case, arange() uses its default value of 1. The following two statements are equivalent:

    >>>

    >>> np.arange(start=1, stop=10, step=1)
    array([1, 2, 3, 4, 5, 6, 7, 8, 9])
    >>> np.arange(start=1, stop=10)
    array([1, 2, 3, 4, 5, 6, 7, 8, 9])
    

    The second statement is shorter. step, which defaults to 1, is what’s usually intuitively expected.

    Using arange() with the increment 1 is a very common case in practice. Again, you can write the previous example more concisely with the positional arguments start and stop:

    >>>

    >>> np.arange(1, 10)
    array([1, 2, 3, 4, 5, 6, 7, 8, 9])
    

    This is an intuitive and concise way to invoke arange(). Using the keyword arguments in this example doesn’t really improve readability.

    Note: If you provide two positional arguments, then the first one is start and the second is stop.

    Providing One Range Argument

    You have to provide at least one argument to arange(). To be more precise, you have to provide start.

    But what happens if you omit stop? How does arange() knows when to stop counting? In this case, the array starts at 0 and ends before the value of start is reached! Again, the default value of step is 1.

    In other words, arange() assumes that you’ve provided stop (instead of start) and that startis 0 and step is 1.

    Let’s see an example where you want to start an array with 0, increasing the values by 1, and stop before 10:

    >>>

    >>> np.arange(start=0, stop=10, step=1)
    array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
    >>> np.arange(0, 10, 1)
    array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
    >>> np.arange(start=0, stop=10)
    array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
    >>> np.arange(0, 10)
    array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
    

    These code samples are okay. They work as shown in the previous examples. There’s an even shorter and cleaner, but still intuitive, way to do the same thing. You can just provide a single positional argument:

    >>>

    >>> np.arange(10)  # Stop is 10, start is 0, and step is 1!
    array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
    

    This is the most usual way to create a NumPy array that starts at zero and has an increment of one.

    Note: The single argument defines where the counting stops. The output array starts at 0 and has an increment of 1.

    If you try to explicitly provide stop without start, then you’ll get a TypeError:

    >>>

    >>> np.arange(stop=10)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: arange() missing required argument 'start' (pos 1)
    

    You got the error because arange() doesn’t allow you to explicitly avoid the first argument that corresponds to start. If you provide a single argument, then it has to be start, but arange() will use it to define where the counting stops.

     

     Remove ads

    Providing Negative Arguments

    If you provide negative values for start or both start and stop, and have a positive step, then arange() will work the same way as with all positive arguments:

    >>>

    >>> np.arange(-5, -1)
    array([-5, -4, -3, -2])
    >>> np.arange(-8, -2, 2)
    array([-8, -6, -4])
    >>> np.arange(-5, 6, 4)
    array([-5, -1,  3])
    

    This behavior is fully consistent with the previous examples. The counting begins with the value of start, incrementing repeatedly by step, and ending before stop is reached.

    Counting Backwards

    Sometimes you’ll want an array with the values decrementing from left to right. In such cases, you can use arange() with a negative value for step, and with a start greater than stop:

    >>>

    >>> np.arange(5, 1, -1)
    array([5, 4, 3, 2])
    >>> np.arange(7, 0, -3)
    array([7, 4, 1])
    

    In this example, notice the following pattern: the obtained array starts with the value of the first argument and decrements for step towards the value of the second argument.

    In the last statement, start is 7, and the resulting array begins with this value. step is -3 so the second value is 7+(−3), that is 4. The third value is 4+(−3), or 1. Counting stops here since stop (0) is reached before the next value (-2).

    You can see the graphical representations of this example in the figure below:

    NumPy arange() in action

    Again, start is shown in green, stop in red, while step and the values contained in the array are blue.

    This time, the arrows show the direction from right to left. That’s because start is greater than stopstep is negative, and you’re basically counting backwards.

    The previous example produces the same result as the following:

    >>>

    >>> np.arange(1, 8, 3)[::-1]
    array([7, 4, 1])
    >>> np.flip(np.arange(1, 8, 3))
    array([7, 4, 1])
    

    However, the variant with the negative value of step is more elegant and concise.

    Getting Empty Arrays

    There are several edge cases where you can obtain empty NumPy arrays with arange(). These are regular instances of numpy.ndarray without any elements.

    If you provide equal values for start and stop, then you’ll get an empty array:

    >>>

    >>> np.arange(2, 2)
    array([], dtype=int64)
    

    This is because counting ends before the value of stop is reached. Since the value of start is equal to stop, it can’t be reached and included in the resulting array as well.

    One of the unusual cases is when start is greater than stop and step is positive, or when start is less than stop and step is negative:

    >>>

    >>> np.arange(8, 2, 1)
    array([], dtype=int64)
    >>> np.arange(2, 8, -1)
    array([], dtype=int64)
    

    As you can see, these examples result with empty arrays, not with errors.

     

     Remove ads

    Data Types of np.arange()

    The types of the elements in NumPy arrays are an important aspect of using them. When working with arange(), you can specify the type of elements with the parameter dtype.

    Note: Here are a few important points about the types of the elements contained in NumPy arrays:

    • All elements in a NumPy array are of the same type called dtype (short for data type).
    • NumPy dtypes allow for more granularity than Python’s built-in numeric types.
    • In some cases, NumPy dtypes have aliases that correspond to the names of Python built-in types.
    • Usually, NumPy routines can accept Python numeric types and vice versa.
    • Some NumPy dtypes have platform-dependent definitions.

    If you want to learn more about the dtypes of NumPy arrays, then please read the official documentation.

    You are free to omit dtype. In this case, arange() will try to deduce the dtype of the resulting array. It depends on the types of startstop, and step, as you can see in the following example:

    >>>

    >>> x = np.arange(5)
    >>> x
    array([0, 1, 2, 3, 4])
    >>> x.dtype
    dtype('int64')
    >>> x.itemsize  # In bytes
    8
    

    Here, there is one argument (5) that defines the range of values. Its type is int. That’s why the dtype of the array x will be one of the integer types provided by NumPy. In this case, NumPy chooses the int64 dtype by default. This is a 64-bit (8-bytes) integer type.

    The array in the previous example is equivalent to this one:

    >>>

    >>> x = np.arange(5, dtype=int)
    >>> x
    array([0, 1, 2, 3, 4])
    >>> x.dtype
    dtype('int64')
    

    The argument dtype=int doesn’t refer to Python int. It translates to NumPy int64 or simply np.int.

    NumPy offers you several integer fixed-sized dtypes that differ in memory and limits:

    • np.int8: 8-bit signed integer (from -128 to 127)
    • np.uint8: 8-bit unsigned integer (from 0 to 255)
    • np.int16: 16-bit signed integer (from -32768 to 32767)
    • np.uint16: 16-bit unsigned integer (from 0 to 65535)
    • np.int32: 32-bit signed integer (from -2**31 to 2**31-1)
    • np.uint32: 32-bit unsigned integer (from 0 to 2**32-1)
    • np.int64: 64-bit signed integer (from -2**63 to 2**63-1)
    • np.uint64: 64-bit unsigned integer (from 0 to 2**64-1)

    If you want other integer types for the elements of your array, then just specify dtype:

    >>>

    >>> x = np.arange(5, dtype=np.int32)
    >>> x
    array([0, 1, 2, 3, 4], dtype=int32)
    >>> x.dtype
    dtype('int32')
    >>> x.itemsize  # In bytes
    4
    

    Now the resulting array has the same values as in the previous case, but the types and sizes of the elements differ. The argument dtype=np.int32 (or dtype='int32') forces the size of each element of x to be 32 bits (4 bytes).

    When your argument is a decimal number instead of integer, the dtype will be some NumPy floating-point type, in this case float64:

    >>>

    >>> y = np.arange(5.0)
    >>> y
    array([0., 1., 2., 3., 4.])
    >>> y.dtype
    dtype('float64')
    

    The values of the elements are the same in the last four examples, but the dtypes differ.

    Generally, when you provide at least one floating-point argument to arange(), the resulting array will have floating-point elements, even when other arguments are integers:

    >>>

    >>> np.arange(1, 5.1)
    array([1., 2., 3., 4., 5.])
    >>> np.arange(1, 5.1).dtype
    dtype('float64')
    >>> np.arange(0, 9, 1.5)
    array([0. , 1.5, 3. , 4.5, 6. , 7.5])
    >>> np.arange(0, 9, 1.5).dtype
    dtype('float64')
    

    In the examples above, start is an integer, but the dtype is np.float64 because stop or stepare floating-point numbers.

    If you specify dtype, then arange() will try to produce an array with the elements of the provided data type:

    >>>

    >>> y = np.arange(5, dtype=float)
    >>> y
    array([0., 1., 2., 3., 4.])
    >>> y.dtype
    dtype('float64')
    

    The argument dtype=float here translates to NumPy float64, that is np.float. It doesn’trefer to Python float. Fixed-size aliases for float64 are np.float64 and np.float_.

    When you need a floating-point dtype with lower precision and size (in bytes), you can explicitly specify that:

    >>>

    >>> z = np.arange(5, dtype=np.float32)
    >>> z
    array([0., 1., 2., 3., 4.], dtype=float32)
    >>> z.dtype
    dtype('float32')
    

    Using dtype=np.float32 (or dtype='float32') makes each element of the array z 32 bits (4 bytes) large. The size of each element of y is 64 bits (8 bytes):

    >>>

    >>> y.itemsize  # In bytes
    8
    >>> z.itemsize  # In bytes
    4
    

    The difference between the elements of y and z, and generally between np.float64 and np.float32, is the memory used and the precision: the first is larger and more precise than the latter.

    In many cases, you won’t notice this difference. However, sometimes it’s important. For example, TensorFlow uses float32 and int32. Similarly, when you’re working with images, even smaller types like uint8 are used.

    When step is not an integer, the results might be inconsistent due to the limitations of floating-point arithmetic.

     

     Remove ads

    Beyond Simple Ranges With np.arange()

    You can conveniently combine arange() with operators (like +-*/**, and so on) and other NumPy routines (such as abs() or sin()) to produce the ranges of output values:

    >>>

    >>> x = np.arange(5)
    >>> x
    array([0, 1, 2, 3, 4])
    >>> 2**x
    array([ 1,  2,  4,  8, 16])
    >>> y = np.arange(-1, 1.1, 0.5)
    >>> y
    array([-1. , -0.5,  0. ,  0.5,  1. ])
    >>> np.abs(y)
    array([1. , 0.5, 0. , 0.5, 1. ])
    >>> z = np.arange(10)
    >>> np.sin(z)
    array([ 0.        ,  0.84147098,  0.90929743,  0.14112001, -0.7568025 ,
           -0.95892427, -0.2794155 ,  0.6569866 ,  0.98935825,  0.41211849])
    

    This is particularly suitable when you want to create a plot in Matplotlib.

    If you need a multidimensional array, then you can combine arange() with .reshape() or similar functions and methods:

    >>>

    >>> a = np.arange(6).reshape((2, 3))
    >>> a
    array([[0, 1, 2],
           [3, 4, 5]])
    >>> a.shape
    (2, 3)
    >>> a.ndim
    2
    

    That’s how you can obtain the ndarray instance with the elements [0, 1, 2, 3, 4, 5] and reshape it to a two-dimensional array.

    Comparison of range and np.arange()

    Python has a built-in class range, similar to NumPy arange() to some extent. range and np.arange() have important distinctions related to application and performance. You’ll see their differences and similarities.

    The main difference between the two is that range is a built-in Python class, while arange()is a function that belongs to a third-party library (NumPy).

    In addition, their purposes are different! Generally, range is more suitable when you need to iterate using the Python for loop. If you want to create a NumPy array, and apply fast loops under the hood, then arange() is a much better solution.

    Parameters and Outputs

    Both range and arange() have the same parameters that define the ranges of the obtained numbers:

    • start
    • stop
    • step

    You apply these parameters similarly, even in the cases when start and stop are equal.

    However, when working with range:

    • You have to provide integer arguments. Otherwise, you’ll get a TypeError.
    • You can’t specify the type of the yielded numbers. It’s always int.

    range and arange() also differ in their return types:

    • range creates an instance of this class that has the same features as other sequences (like list and tuple), such as membership, concatenation, repetition, slicing, comparison, length check, and more.
    • arange() returns an instance of NumPy ndarray.

    Creating Sequences

    You can apply range to create an instance of list or tuple with evenly spaced numbers within a predefined range. You might find comprehensions particularly suitable for this purpose.

    However, creating and manipulating NumPy arrays is often faster and more elegant than working with lists or tuples.

    Let’s compare the performance of creating a list using the comprehension against an equivalent NumPy ndarray with arange():

    >>>

    >>> import timeit
    >>> n = 1
    >>> timeit.timeit(f'x = [i**2 for i in range({n})]')
    >>> timeit.timeit(f'x = np.arange({n})**2', setup='import numpy as np')
    

    Repeating this code for varying values of n yielded the following results on my machine:

    Size: nTime Per Loop: rangeTime Per Loop: arange()Ratio
    1497 ns1.14 µs0.41
    102.24 µs1.28 µs1.74
    10020.0 µs1.37 µs14.6
    1,000211 µs2.92 µs72.3

    These results might vary, but clearly you can create a NumPy array much faster than a list, except for sequences of very small lengths. (The application often brings additional performance benefits!)

    This is because NumPy performs many operations, including looping, on the C-level. In addition, NumPy is optimized for working with vectors and avoids some Python-related overhead.

     

     Remove ads

    Python for Loops

    If you need values to iterate over in a Python for loop, then range is usually a better solution. According to the official Python documentation:

    The advantage of the range type over a regular list or tuple is that a range object will always take the same (small) amount of memory, no matter the size of the range it represents (as it only stores the startstop and step values calculating individual items and subranges as needed). (Source)

    range is often faster than arange() when used in Python for loops, especially when there’s a possibility to break out of a loop soon. This is because range generates numbers in the lazy fashion, as they are required, one at a time.

    In contrast, arange() generates all the numbers at the beginning.

    For more information about range, you can check The Python range() Function (Guide) and the official documentation.

    Other Routines Based on Numerical Ranges

    In addition to arange(), you can apply other NumPy array creation routines based on numerical ranges:

    • linspace() is similar to arange() in that it returns evenly spaced numbers. But you can specify the number of values to generate as well as whether to include the endpoint and whether to create multiple arrays at once.
    • logspace() and geomspace() are similar to linspace(), except the returned numbers are spaced evenly on the logarithmic scale.
    • meshgrid()ogrid(), and mgrid() return grids of points represented as arrays.

    All these functions have their specifics and use cases. You can choose the appropriate one according to your needs.

    As you already saw, NumPy contains more routines to create instances of ndarray.

    Quick Summary

    To use NumPy arange(), you need to import numpy first:

    >>>

    >>> import numpy as np
    

    Here’s a table with a few examples that summarize how to use NumPy arange(). It could be helpful to memorize various uses:

    ExampleResult
    np.arange(start=1, stop=10, step=3)array([1, 4, 7])
    np.arange(1, 10, 3)array([1, 4, 7])
    np.arange(1, 10, 3, dtype=float)array([1., 4., 7.])
    np.arange(1.0, 10, 3)array([1., 4., 7.])
    np.arange(0, 1.1, 0.5)array([0. , 0.5, 1. ])
    np.arange(2, 6)array([2, 3, 4, 5])
    np.arange(5)array([0, 1, 2, 3, 4])
    np.arange(-8, -2, 2)array([-8, -6, -4])
    np.arange(7, 0, -3)array([7, 4, 1])
    np.arange(8, 2)array([])

    Don’t forget that you can also influence the memory used for your arrays by specifying NumPy dtypes with the parameter dtype.

    Conclusion

    You now know how to use NumPy arange(). The function np.arange() is one of the fundamental NumPy routines often used to create instances of NumPy ndarray. It has four arguments:

    1. start: the first value of the array
    2. stop: where the array ends
    3. step: the increment or decrement
    4. dtype: the type of the elements of the array

    You also learned how NumPy arange() compares with the Python built-in class range when you’re creating sequences and generating values to iterate over.

    You saw that there are other NumPy array creation routines based on numerical ranges, such as linspace()logspace()meshgrid(), and so on.

    If you have questions or comments, please put them in the comment section below.

    展开全文
  • np.arange()用法,Python numpy.arange()用法

    千次阅读 2021-06-21 10:30:01
    np.arange([start, ]stop, [step, ]dtype=None) start : 起始值,默认值为0,Optional(可选)。 end : 结束值(不含)。 step : 步长,默认值为1,Optional(可选)。 dtype :Optional(可选),默认为None,从其他...

    numpy常用函数之arange函数

    np.arange([start, ]stop, [step, ]dtype=None)

    start : 起始值,默认值为0,Optional(可选)。
    end : 结束值(不含)。
    step : 步长,默认值为1
    dtype :默认为None,从其他输入值中推测,Optional(可选)。。

    用法:分为一个参数,两个参数,三个参数三种情况

    1. 一个参数时:

    (1)参数值 为 终点
    (2)起点 取 默认值0
    (3)步长 取 默认值1
    import numpy 
    print(numpy.arange(6)) #从 0 到 5 ,不包括 6
    
    [0 1 2 3 4 5]
    

    2. 两个参数时:

    (1)第一个参数为起点
    (2)第二个参数为终点(不包括)
    (3)步长取默认值 1
      注:包前不包后
    print(numpy.arange(6, 10)) #从 6 到 9,不包括10,[6,9)
     
    [6 7 8 9]
    

    3. 三个参数时

    (1)第一个参数为起点
    (2)第二个参数为终点
    (3)第三个参数为步长
       注: 步长支持小数
    print( numpy.arange( 6 , 20 , 2 ) )  # 起点是 5,终点是 20,步长为 2
     
    
    [ 6  8 10 12 14 16 18]
    
    print( np.arange( 6 , 20 , 1.5 ) )  #步长支持小数
    
    [ 6.   7.5  9.  10.5 12.  13.5 15.  16.5 18.  19.5]
    
    
    展开全文
  • 1.公式 logistic回归函数的公式: logistic回归函数的导数公式: σ'(x) = σ(x) * ( 1 - σ(x) ) 2.np.arange()函数画图 使用np.arange()函数画图的代码: import numpy as np import matplotlib.pyplot as plt x1...

    1.公式

    logistic回归函数的公式:

    logistic回归函数的导数公式:

    σ'(x) = σ(x) * ( 1 - σ(x) )

    2.np.arange()函数画图

    使用np.arange()函数画图的代码:

    import numpy as np
    import matplotlib.pyplot as plt
    
    x1 = np.arange(-1000,1000,0.001)
    
    y1 = 1.0/(1+np.exp(-x1))
    
    yg1 = y1*(1-y1)
    
    plt.plot(x1,y1)
    
    plt.plot(x1,yg1)
    

    Logistic函数图像如下:

    导数图像如下:

    这跟我想象的很不一样,为什么??

    3.np.linspace()函数画图

    使用np.linspace()函数画图的代码:

    x2 = np.linspace(-10,10,1000)
    
    y2 = 1.0/(1+np.exp(-x2))
    
    yg2 = y2*(1-y2)
    
    plt.plot(x2,y2)
    
    plt.plot(x2,yg2)

     Logistic函数图像如下:

     导数图像如下:

    这才是我们常见的效果图。

    4.分析

    仔细琢磨,两者取点的方式是没有问题的,但是两者取点的个数不一样(在坐标中画图其实是很多个取值(x,y)的点的连线)。

    于是,修改np.arange()的点,取少一些点,步长为1:

    x1 = np.arange(-10,10,1)

    可以隐约看到折线,修改步长为0.1:

    x1 = np.arange(-10,10,0.1)

    原来是图片展示的时候y轴和x轴的取值问题,怪不得需要进行数据的归一化处理

    进一步验证,np.linspace()函数多取一些值,取10000个点

    x2 = np.linspace(-100,100,10000)

    得到之前一样的效果,由于图像显示大小的原因(python画图的默认幕布大小),取的点太多了,图像在x轴方向被压缩,趋于直线。

    5.总结

    • 不管用什么方法,画图的时候一定要注意显示幕布的x轴和y轴的比例,不合适的话需要调整
    • 在不调整图像显示大小的情况下,需要相应的修改坐标轴取值范围和个数,建议使用np.linspace()方法,可以直接控制取值个数

    说明:记录学习笔记,如果错误欢迎指正!写文章不易,转载请联系我。

    展开全文
  • python 中 np.arange()的使用

    千次阅读 2022-04-02 19:57:04
    np.arange() : 函数返回一个有终点和起点的固定步长的排列,如[0, 1, 2, 3, 4, 5, 6, 7],起点是0,终点是7,步长为1。 参数个数情况: np.arange()函数分为一个参数,两个参数,三个参数三种情况: 一个参数时,...
  • np.arange()用法总结

    2021-09-05 23:28:05
    np.arange()返回一个有起点和终点的固定步长的排列(即为等差数列)。 用法 np.arange([start, ]stop, [step, ]dtype = None) 当输入参数为一个时,输入的为终点值,默认起点值为0,步长为1 例子 import numpy as ...
  • np.arange()用法

    千次阅读 2021-01-29 20:11:01
    np.arange() 函数返回一个有终点和起点的固定步长的排列,如[1,2,3,4,5],起点是1,终点是6,步长为1。 参数个数情况: np.arange()函数分为一个参数,两个参数,三个参数三种情况 1)一个参数时,参数值为终点,...
  • np.arange()函数用法

    千次阅读 2021-07-15 11:50:24
    x = np.arange(6) 结果:[0 1 2 3 4 5] #填入二个参数,起点为参数a,终点为参数b,步长为1。 x = np.arange(2, 6) 结果:[3 4 5 6 7 8] #填入三个参数,起点为参数a,终点为参数b,步长为c。 x = np.arange(1, 6, ...
  • 近期在调试深度学习相关的代码时,经常隔三差五遇到range()、np.arange()、np.linspace()、np.logspace()一系列的函数,每次遇到后,当时貌似理解了,但是过段时间又忘了,并且这几个函数看起来还长的差不多,虽然...
  • numpy库常用函数——np.arange()函数

    千次阅读 2021-04-14 09:23:13
    np.arange([start, ]stop, [step, ]dtype=None) 参数解释: start:起点值;可忽略不写,默认从0开始 stop:终点值;生成的元素不包括结束值 step:步长;可忽略不写,默认步长为1 dtype:默认为None,设置显示元素的...
  • np.arange()的用法,size和shape的功能

    千次阅读 2020-10-22 20:51:44
    x_arange = 0.041 * np.arange(20, 25, 1) print(x_arange.size) #5 print(x_arange.shape) #(5,) x = np.arange(5) print(x) [0 1 2 3 4]
  • 一、np.linespace()函数用法: 生成指定范围内指定个数的一维数组: def linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None): 1.在指定的间隔[“start”,“stop”]内均匀地返回数字。 2....
  • np.linspace() np.logspace() np.arange() 区别

    千次阅读 2017-12-23 17:18:33
    np.linspace() np.logspace() np.arange() 区别 1. np.linspace() 生成(start,stop)区间指定元素个数num的list,均匀分布 Signature: np.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=...
  • python np.arange 步长0.1的问题需要注意

    千次阅读 2021-04-22 09:53:13
    两个小测试: 1)count输出什么?... for i in np.arange(y_min, y_max, step): count += 1 print('i:', count, i) 答案是:count = 10 如图 2)count输出是什么? import numpy as np .
  • 这种情况下,就可以通过numpy.arange()函数实现,具体如下: numpy.arange() 返回值:返回一个有起点和终点的可固定小数步长的排列; 参数: 一个参数时,参数值为终点,起点取默认值0,步长取默认值1; 两个...
  • numpy函数之np.arange()

    千次阅读 2020-11-01 21:06:53
    np.arange(10) 此函数生成了用0到9的十个数字的序列 形式2(2个参数) np.arange(3,10) 此函数生成了用3到9的六个(9-3=6)数字的序列(左闭右开) 形式3(3个参数) 注意:前两个函数的默认间隔都为1,形式3的作用就是...
  • np.arange函数的使用

    万次阅读 多人点赞 2019-05-13 19:02:48
    np.arange函数的使用 返回值: np.arange()函数返回一个序列 参数: 有三种情况 1.只有一个参数的时候,默认从0开始到输入的参数,产生序列,步进为默认的1 2.有两个参数的时候,序列中的元素从第一个参数到第二个...
  • numpy.arange numpy.arange([start, ]stop, [step, ]dtype=None) Return evenly spaced values within a given interval. Values are generated within the half-open interval [start, stop) (in other word...
  • range()和np.arange()的区别

    千次阅读 2019-11-24 22:55:54
    range(start, end, step),返回一个range.object(迭代值),起始值为start,终止值为end,但不含终止值,步长为step。只能创建int型list。 这是一个通用的函数来创建包含算术级数的列表。它最常用于for循环。参数...
  • Python基础:np.arange()函数

    万次阅读 2019-04-24 14:04:51
    Python基础:np.arange()函数numpy.arange ()函数的参数:新的改变功能快捷键合理的创建标题,有助于目录的生成如何改变文本的样式插入链接与图片如何插入一段漂亮的代码片生成一个适合你的列表创建一个表格设定...
  • numpy.arange(start,stop,step,dtype)分别表示(开始,结束,步长,数据类型datatype) np.linspace(start,stop,num,endpoint,retstep,dtype)分别表示(开始,结束,个数,结束点,步长,类型) retstep...
  • range()、np.arange()总结

    千次阅读 2019-06-17 15:51:12
    range()和xrange()函数 在 python 2.x 版本中,同时存在range() 和xrange() 函数,其中,range() 返回值是一个列表,xrange() 返回值是一个迭代器; 在 python 3.x 版本中,取消了xrange() 的定义,仅保留了range...
  • python机器学习基础之np.arange函数

    千次阅读 2019-06-25 14:17:00
    np.arange()函数返回一个有终点和起点的固定步长的排列,如[1,2,3,4,5],起点是1,终点是5,步长为1。 2.参数个数情况: np.arange()函数分为一个参数,两个参数,三个参数三种情况 1)一个参数时,参数值为...
  • np.arange()函数

    千次阅读 2018-11-13 22:27:23
    np.arange()函数返回一个有终点和起点的固定步长的排列 参数个数情况: np.arange()函数分为一个参数,两个参数,三个参数三种情况 1)一个参数时,参数值为终点,起点取默认值0,步长取默认值1。 2)两个参数时,第...
  • Python:range()和np.arange()区别

    万次阅读 2018-10-30 20:26:05
    range()返回的是range object,而np.arange()返回的是numpy.ndarray() range尽可用于迭代,而np.arange作用远不止于此,它是一个序列,可被当做向量使用。 range()不支持步长为小数,np.arange()支持步长为小数 两者...
  • import numpy as np # 1.如何从数组np.arange(15)中提取5到10之间的所有数字? a = np.arange(5,11) print(a) [ 5 6 7 8 9 10]

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 230,123
精华内容 92,049
关键字:

np.arange