-
2021-07-16 20:19:02
np.arange()
np.arange()函数返回一个有终点和起点的固定步长的排列,如[1,2,3,4,5],起点是1,终点是6,步长为1。
参数个数情况: np.arange()函数分为一个参数,两个参数,三个参数三种情况- 一个参数时,参数值为终点,起点取默认值0,步长取默认值1。
- 两个参数时,第一个参数为起点,第二个参数为终点,步长取默认值1。
- 三个参数时,第一个参数为起点,第二个参数为终点,第三个参数为步长。其中步长支持小数
# 一个参数 默认起点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()有一些区别:
- range()和np.arange()的返回类型不同,range()返回的是range这个object,而np.arange()返回的是ndarray类型;
- range()不支持步长为小数,而np.arange()支持步长(step)为小数;
- range()和np.arange()都可用于迭代;
- range()和np.arange()都有三个参数,以第一个参数为起点,第三个参数为步长,截止到第二个参数之前的不包括第二个参数的数据序列。
- range()可用于迭代,而np.arange()作用远不止于此,它是一个序列,可被当做向量使用。
更多相关内容 -
np.arange() 详细教程
2020-11-27 08:37:24NumPyis 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 asnp.arange()
becausenp
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 SciPy, Pandas, 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 classrange
- 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.
Return Value and Parameters of
np.arange()
NumPy
arange()
is one of the array creation routines based on numerical ranges. It creates an instance ofndarray
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:
start
is the number (integer or decimal) that defines the first value in the array.stop
is the number that defines the end of the array and isn’t included in the array.step
is the number that defines the spacing (difference) between each two consecutive values in the array and defaults to1
.dtype
is the type of the elements of the output array and defaults toNone
.
step
can’t be zero. Otherwise, you’ll get aZeroDivisionError
. You can’t move away anywhere fromstart
if the increment or decrement is0
.If
dtype
is omitted,arange()
will try to deduce the type of the array elements from the types ofstart
,stop
, andstep
.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 parametersstart
,stop
, andstep
. 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
is1
. Therefore, the first element of the obtained array is1
.step
is3
, which is why your second value is 1+3, that is4
, while the third value in the array is 4+3, which equals7
.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
start
,stop
, andstep
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 differentstop
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 than7
and less than or equal to10
.However, if you make
stop
greater than10
, then counting is going to end after10
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
, andarange()
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:
start
is shown in green,stop
in red, whilestep
and the values contained in the arrays are blue.As you can see from the figure above, the first two examples have three values (
1
,4
, and7
) counted. They don’t allow10
to be included. In the third example,stop
is larger than10
, and it is contained in the resulting array.Providing Two Range Arguments
You can omit
step
. In this case,arange()
uses its default value of1
. 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 to1
, is what’s usually intuitively expected.Using
arange()
with the increment1
is a very common case in practice. Again, you can write the previous example more concisely with the positional argumentsstart
andstop
:>>>
>>> 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 isstop
.Providing One Range Argument
You have to provide at least one argument to
arange()
. To be more precise, you have to providestart
.But what happens if you omit
stop
? How doesarange()
knows when to stop counting? In this case, the array starts at0
and ends before the value ofstart
is reached! Again, the default value ofstep
is1
.In other words,
arange()
assumes that you’ve providedstop
(instead ofstart
) and thatstart
is0
andstep
is1
.Let’s see an example where you want to start an array with
0
, increasing the values by1
, and stop before10
:>>>
>>> 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 of1
.If you try to explicitly provide
stop
withoutstart
, then you’ll get aTypeError
:>>>
>>> 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 tostart
. If you provide a single argument, then it has to bestart
, butarange()
will use it to define where the counting stops.Providing Negative Arguments
If you provide negative values for
start
or bothstart
andstop
, and have a positivestep
, thenarange()
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 bystep
, and ending beforestop
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 forstep
, and with astart
greater thanstop
:>>>
>>> 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
is7
, and the resulting array begins with this value.step
is-3
so the second value is 7+(−3), that is4
. The third value is 4+(−3), or1
. Counting stops here sincestop
(0
) is reached before the next value (-2
).You can see the graphical representations of this example in the figure below:
Again,
start
is shown in green,stop
in red, whilestep
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 thanstop
,step
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 ofnumpy.ndarray
without any elements.If you provide equal values for
start
andstop
, 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 ofstart
is equal tostop
, it can’t be reached and included in the resulting array as well.One of the unusual cases is when
start
is greater thanstop
andstep
is positive, or whenstart
is less thanstop
andstep
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.
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 parameterdtype
.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 ofstart
,stop
, andstep
, 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 isint
. That’s why the dtype of the arrayx
will be one of the integer types provided by NumPy. In this case, NumPy chooses theint64
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 Pythonint
. It translates to NumPyint64
or simplynp.int
.NumPy offers you several integer fixed-sized dtypes that differ in memory and limits:
np.int8
: 8-bit signed integer (from-128
to127
)np.uint8
: 8-bit unsigned integer (from0
to255
)np.int16
: 16-bit signed integer (from-32768
to32767
)np.uint16
: 16-bit unsigned integer (from0
to65535
)np.int32
: 32-bit signed integer (from-2**31
to2**31-1
)np.uint32
: 32-bit unsigned integer (from0
to2**32-1
)np.int64
: 64-bit signed integer (from-2**63
to2**63-1
)np.uint64
: 64-bit unsigned integer (from0
to2**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
(ordtype='int32'
) forces the size of each element ofx
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 isnp.float64
becausestop
orstep
are floating-point numbers.If you specify
dtype
, thenarange()
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 NumPyfloat64
, that isnp.float
. It doesn’trefer to Pythonfloat
. Fixed-size aliases forfloat64
arenp.float64
andnp.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
(ordtype='float32'
) makes each element of the arrayz
32 bits (4 bytes) large. The size of each element ofy
is 64 bits (8 bytes):>>>
>>> y.itemsize # In bytes 8 >>> z.itemsize # In bytes 4
The difference between the elements of
y
andz
, and generally betweennp.float64
andnp.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
andint32
. Similarly, when you’re working with images, even smaller types likeuint8
are used.When
step
is not an integer, the results might be inconsistent due to the limitations of floating-point arithmetic.Beyond Simple Ranges With
np.arange()
You can conveniently combine
arange()
with operators (like+
,-
,*
,/
,**
, and so on) and other NumPy routines (such asabs()
orsin()
) 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
andnp.arange()
Python has a built-in class
range
, similar to NumPyarange()
to some extent.range
andnp.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, whilearange()
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 Pythonfor
loop. If you want to create a NumPy array, and apply fast loops under the hood, thenarange()
is a much better solution.Parameters and Outputs
Both
range
andarange()
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
andstop
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
andarange()
also differ in their return types:range
creates an instance of this class that has the same features as other sequences (likelist
andtuple
), such as membership, concatenation, repetition, slicing, comparison, length check, and more.arange()
returns an instance of NumPyndarray
.
Creating Sequences
You can apply
range
to create an instance oflist
ortuple
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 NumPyndarray
witharange()
:>>>
>>> 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: n
Time Per Loop: range
Time Per Loop: arange()
Ratio 1 497 ns 1.14 µs 0.41 10 2.24 µs 1.28 µs 1.74 100 20.0 µs 1.37 µs 14.6 1,000 211 µs 2.92 µs 72.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.
Python
for
LoopsIf you need values to iterate over in a Python
for
loop, thenrange
is usually a better solution. According to the official Python documentation:The advantage of the
range
type over a regularlist
ortuple
is that arange
object will always take the same (small) amount of memory, no matter the size of the range it represents (as it only stores thestart
,stop
andstep
values calculating individual items and subranges as needed). (Source)range
is often faster thanarange()
when used in Pythonfor
loops, especially when there’s a possibility to break out of a loop soon. This is becauserange
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 toarange()
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()
andgeomspace()
are similar tolinspace()
, except the returned numbers are spaced evenly on the logarithmic scale.meshgrid()
,ogrid()
, andmgrid()
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 importnumpy
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:Example Result 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 functionnp.arange()
is one of the fundamental NumPy routines often used to create instances of NumPyndarray
. It has four arguments:start
: the first value of the arraystop
: where the array endsstep
: the increment or decrementdtype
: the type of the elements of the array
You also learned how NumPy
arange()
compares with the Python built-in classrange
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.
- What
-
np.arange()用法,Python numpy.arange()用法
2021-06-21 10:30:01np.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
: 步长,默认值为1dtype
:默认为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]
-
np.arange()和np.linspace()绘制logistic回归图像时得到不同的结果?
2021-12-22 10:18:511.公式 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:04np.arange() : 函数返回一个有终点和起点的固定步长的排列,如[0, 1, 2, 3, 4, 5, 6, 7],起点是0,终点是7,步长为1。 参数个数情况: np.arange()函数分为一个参数,两个参数,三个参数三种情况: 一个参数时,... -
np.arange()用法总结
2021-09-05 23:28:05np.arange()返回一个有起点和终点的固定步长的排列(即为等差数列)。 用法 np.arange([start, ]stop, [step, ]dtype = None) 当输入参数为一个时,输入的为终点值,默认起点值为0,步长为1 例子 import numpy as ... -
np.arange()用法
2021-01-29 20:11:01np.arange() 函数返回一个有终点和起点的固定步长的排列,如[1,2,3,4,5],起点是1,终点是6,步长为1。 参数个数情况: np.arange()函数分为一个参数,两个参数,三个参数三种情况 1)一个参数时,参数值为终点,... -
np.arange()函数用法
2021-07-15 11:50:24x = 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, ... -
【Python】range()、np.arange()、np.linspace()、np.logspace()的使用和区别
2019-08-27 19:41:08近期在调试深度学习相关的代码时,经常隔三差五遇到range()、np.arange()、np.linspace()、np.logspace()一系列的函数,每次遇到后,当时貌似理解了,但是过段时间又忘了,并且这几个函数看起来还长的差不多,虽然... -
numpy库常用函数——np.arange()函数
2021-04-14 09:23:13np.arange([start, ]stop, [step, ]dtype=None) 参数解释: start:起点值;可忽略不写,默认从0开始 stop:终点值;生成的元素不包括结束值 step:步长;可忽略不写,默认步长为1 dtype:默认为None,设置显示元素的... -
np.arange()的用法,size和shape的功能
2020-10-22 20:51:44x_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()函数和np.arange()函数用法:
2020-11-24 21:51:25一、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:33np.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 . -
python 中np.arange()生成(起点、终点、可小数步长)的排列
2022-03-20 14:18:42这种情况下,就可以通过numpy.arange()函数实现,具体如下: numpy.arange() 返回值:返回一个有起点和终点的可固定小数步长的排列; 参数: 一个参数时,参数值为终点,起点取默认值0,步长取默认值1; 两个... -
numpy函数之np.arange()
2020-11-01 21:06:53np.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:48np.arange函数的使用 返回值: np.arange()函数返回一个序列 参数: 有三种情况 1.只有一个参数的时候,默认从0开始到输入的参数,产生序列,步进为默认的1 2.有两个参数的时候,序列中的元素从第一个参数到第二个... -
numpy重新学习系列(10)---如何用np.arange生成均匀间隔分布的array
2019-10-31 20:12:06numpy.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:54range(start, end, step),返回一个range.object(迭代值),起始值为start,终止值为end,但不含终止值,步长为step。只能创建int型list。 这是一个通用的函数来创建包含算术级数的列表。它最常用于for循环。参数... -
Python基础:np.arange()函数
2019-04-24 14:04:51Python基础:np.arange()函数numpy.arange ()函数的参数:新的改变功能快捷键合理的创建标题,有助于目录的生成如何改变文本的样式插入链接与图片如何插入一段漂亮的代码片生成一个适合你的列表创建一个表格设定... -
python np.arange,np.linspace和np.logspace之间的区别
2017-11-26 20:56:35numpy.arange(start,stop,step,dtype)分别表示(开始,结束,步长,数据类型datatype) np.linspace(start,stop,num,endpoint,retstep,dtype)分别表示(开始,结束,个数,结束点,步长,类型) retstep... -
range()、np.arange()总结
2019-06-17 15:51:12range()和xrange()函数 在 python 2.x 版本中,同时存在range() 和xrange() 函数,其中,range() 返回值是一个列表,xrange() 返回值是一个迭代器; 在 python 3.x 版本中,取消了xrange() 的定义,仅保留了range... -
python机器学习基础之np.arange函数
2019-06-25 14:17:00np.arange()函数返回一个有终点和起点的固定步长的排列,如[1,2,3,4,5],起点是1,终点是5,步长为1。 2.参数个数情况: np.arange()函数分为一个参数,两个参数,三个参数三种情况 1)一个参数时,参数值为... -
np.arange()函数
2018-11-13 22:27:23np.arange()函数返回一个有终点和起点的固定步长的排列 参数个数情况: np.arange()函数分为一个参数,两个参数,三个参数三种情况 1)一个参数时,参数值为终点,起点取默认值0,步长取默认值1。 2)两个参数时,第... -
Python:range()和np.arange()区别
2018-10-30 20:26:05range()返回的是range object,而np.arange()返回的是numpy.ndarray() range尽可用于迭代,而np.arange作用远不止于此,它是一个序列,可被当做向量使用。 range()不支持步长为小数,np.arange()支持步长为小数 两者... -
如何从数组np.arange(15)中提取5到10之间的所有数字?
2020-03-20 09:52:36import numpy as np # 1.如何从数组np.arange(15)中提取5到10之间的所有数字? a = np.arange(5,11) print(a) [ 5 6 7 8 9 10]