第二周作业 Python Basics with Numpy

本文介绍了使用Python和Numpy进行科学计算的基础知识,包括关键函数如np.exp、np.log及np.reshape的用法,并实现了几个实用函数如sigmoid、softmax等。此外还探讨了向量化的重要性及其对计算效率的影响。

Python Basics with Numpy (optional assignment)

1 Building basic functions with numpy

Numpy is the main package for scientific computing in Python. It is maintained by a large community (www.numpy.org). In this exercise you will learn several key numpy functions such as np.exp, np.log, and np.reshape. You will need to know how to use these functions for future assignments.

1.1 sigmoid function, np.exp()

Before using np.exp(), you will use math.exp() to implement the sigmoid function. You will then see why np.exp() is preferable to math.exp().

Exercise: Build a function that returns the sigmoid of a real number x. Use math.exp(x) for the exponential function.

Reminder:

sigmoid(x)=11+ex s i g m o i d ( x ) = 1 1 + e − x is sometimes also known as the logistic function. It is a non-linear function used not only in Machine Learning (Logistic Regression), but also in Deep Learning.

To refer to a function belonging to a specific package you could call it using package_name.function(). Run the code below to see an example with math.exp().

# GRADED FUNCTION: basic_sigmoid

import math

def basic_sigmoid(x):
    """
    Compute sigmoid of x.

    Arguments:
    x -- A scalar

    Return:
    s -- sigmoid(x)
    """

    ### START CODE HERE ### (≈ 1 line of code)
    s = 1/(1+math.exp(-x))
    ### END CODE HERE ###

    return s
basic_sigmoid(3)
0.9525741268224334

Expected Output:

** basic_sigmoid(3) **0.9525741268224334

Actually, we rarely use the “math” library in deep learning because the inputs of the functions are real numbers. In deep learning we mostly use matrices and vectors. This is why numpy is more useful.

### One reason why we use "numpy" instead of "math" in Deep Learning ###
x = [1, 2, 3]
basic_sigmoid(x) # you will see this give an error when you run it, because x is a vector.
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-9-2e11097d6860> in <module>()
      1 ### One reason why we use "numpy" instead of "math" in Deep Learning ###
      2 x = [1, 2, 3]
----> 3 basic_sigmoid(x) # you will see this give an error when you run it, because x is a vector.


<ipython-input-7-951c5721dbfa> in basic_sigmoid(x)
     15 
     16     ### START CODE HERE ### (≈ 1 line of code)
---> 17     s = 1/(1+math.exp(-x))
     18     ### END CODE HERE ###
     19 


TypeError: bad operand type for unary -: 'list'

In fact, if x=(x1,x2,...,xn) x = ( x 1 , x 2 , . . . , x n ) is a row vector then np.exp(x) n p . e x p ( x ) will apply the exponential function to every element of x. The output will thus be: np.exp(x)=(ex1,ex2,...,exn) n p . e x p ( x ) = ( e x 1 , e x 2 , . . . , e x n )

import numpy as np

# example of np.exp
x = np.array([1, 2, 3])
print(np.exp(x)) # result is (exp(1), exp(2), exp(3))
[  2.71828183   7.3890561   20.08553692]

Furthermore, if x is a vector, then a Python operation such as s=x+3 s = x + 3 or s=1x s = 1 x will output s as a vector of the same size as x.

# example of vector operation
x = np.array([1, 2, 3])
print (x + 3)
[4 5 6]

Any time you need more info on a numpy function, we encourage you to look at the official documentation.

You can also create a new cell in the notebook and write np.exp? (for example) to get quick access to the documentation.

Exercise: Implement the sigmoid function using numpy.

Instructions: x could now be either a real number, a vector, or a matrix. The data structures we use in numpy to represent these shapes (vectors, matrices…) are called numpy arrays. You don’t need to know more for now.

For xRnsigmoid(x)=sigmoidx1x2...xn=11+ex111+ex2...11+exn(1) (1) For  x ∈ R n ,  s i g m o i d ( x ) = s i g m o i d ( x 1 x 2 . . . x n ) = ( 1 1 + e − x 1 1 1 + e − x 2 . . . 1 1 + e − x n )

# GRADED FUNCTION: sigmoid

import numpy as np # this means you can access numpy functions by writing np.function() instead of numpy.function()

def sigmoid(x):
    """
    Compute the sigmoid of x

    Arguments:
    x -- A scalar or numpy array of any size

    Return:
    s -- sigmoid(x)
    """

    ### START CODE HERE ### (≈ 1 line of code)
    s = 1/(1+np.exp(-x))
    ### END CODE HERE ###

    return s
x = np.array([1, 2, 3])
sigmoid(x)
array([ 0.73105858,  0.88079708,  0.95257413])

Expected Output:

**sigmoid([1,2,3])** array([ 0.73105858, 0.88079708, 0.95257413])

1.2 Sigmoid gradient

As you’ve seen in lecture, you will need to compute gradients to optimize loss functions using backpropagation. Let’s code your first gradient function.

Exercise: Implement the function sigmoid_grad() to compute the gradient of the sigmoid function with respect to its input x. The formula is:

sigmoid_derivative(x)=σ(x)=σ(x)(1σ(x))(2) (2) s i g m o i d _ d e r i v a t i v e ( x ) = σ ′ ( x ) = σ ( x ) ( 1 − σ ( x ) )

You often code this function in two steps:
1. Set s to be the sigmoid of x. You might find your sigmoid(x) function useful.
2. Compute σ(x)=s(1s) σ ′ ( x ) = s ( 1 − s )

# GRADED FUNCTION: sigmoid_derivative

def sigmoid_derivative(x):
    """
    Compute the gradient (also called the slope or derivative) of the sigmoid function with respect to its input x.
    You can store the output of the sigmoid function into variables and then use it to calculate the gradient.

    Arguments:
    x -- A scalar or numpy array

    Return:
    ds -- Your computed gradient.
    """

    ### START CODE HERE ### (≈ 2 lines of code)
    s = 1/(1+np.exp(-x))
    ds = s*(1-s)
    ### END CODE HERE ###

    return ds
x = np.array([1, 2, 3])
print ("sigmoid_derivative(x) = " + str(sigmoid_derivative(x)))
sigmoid_derivative(x) = [ 0.19661193  0.10499359  0.04517666]

Expected Output:

**sigmoid_derivative([1,2,3])** [ 0.19661193 0.10499359 0.04517666]

1.3 Reshaping arrays

Two common numpy functions used in deep learning are np.shape and np.reshape().
- X.shape is used to get the shape (dimension) of a matrix/vector X.
- X.reshape(…) is used to reshape X into some other dimension.

For example, in computer science, an image is represented by a 3D array of shape (length,height,depth=3) ( l e n g t h , h e i g h t , d e p t h = 3 ) . However, when you read an image as the input of an algorithm you convert it to a vector of shape (lengthheight3,1) ( l e n g t h ∗ h e i g h t ∗ 3 , 1 ) . In other words, you “unroll”, or reshape, the 3D array into a 1D vector.

这里写图片描述

Exercise: Implement image2vector() that takes an input of shape (length, height, 3) and returns a vector of shape (length*height*3, 1). For example, if you would like to reshape an array v of shape (a, b, c) into a vector of shape (a*b,c) you would do:

v = v.reshape((v.shape[0]*v.shape[1], v.shape[2])) # v.shape[0] = a ; v.shape[1] = b ; v.shape[2] = c
  • Please don’t hardcode the dimensions of image as a constant. Instead look up the quantities you need with image.shape[0], etc.
# GRADED FUNCTION: image2vector
def image2vector(image):
    """
    Argument:
    image -- a numpy array of shape (length, height, depth)

    Returns:
    v -- a vector of shape (length*height*depth, 1)
    """

    ### START CODE HERE ### (≈ 1 line of code)
    v = image.reshape(image.shape[0]*image.shape[1]*image.shape[2],1)
    ### END CODE HERE ###

    return v
# This is a 3 by 3 by 2 array, typically images will be (num_px_x, num_px_y,3) where 3 represents the RGB values
image = np.array([[[ 0.67826139,  0.29380381],
        [ 0.90714982,  0.52835647],
        [ 0.4215251 ,  0.45017551]],

       [[ 0.92814219,  0.96677647],
        [ 0.85304703,  0.52351845],
        [ 0.19981397,  0.27417313]],

       [[ 0.60659855,  0.00533165],
        [ 0.10820313,  0.49978937],
        [ 0.34144279,  0.94630077]]])

print ("image2vector(image) = " + str(image2vector(image)))
image2vector(image) = [[ 0.67826139]
 [ 0.29380381]
 [ 0.90714982]
 [ 0.52835647]
 [ 0.4215251 ]
 [ 0.45017551]
 [ 0.92814219]
 [ 0.96677647]
 [ 0.85304703]
 [ 0.52351845]
 [ 0.19981397]
 [ 0.27417313]
 [ 0.60659855]
 [ 0.00533165]
 [ 0.10820313]
 [ 0.49978937]
 [ 0.34144279]
 [ 0.94630077]]

Expected Output:

**image2vector(image)** [[ 0.67826139] [ 0.29380381] [ 0.90714982] [ 0.52835647] [ 0.4215251 ] [ 0.45017551] [ 0.92814219] [ 0.96677647] [ 0.85304703] [ 0.52351845] [ 0.19981397] [ 0.27417313] [ 0.60659855] [ 0.00533165] [ 0.10820313] [ 0.49978937] [ 0.34144279] [ 0.94630077]]

1.4 - Normalizing rows

Another common technique we use in Machine Learning and Deep Learning is to normalize our data. It often leads to a better performance because gradient descent converges faster after normalization. Here, by normalization we mean changing x to xx x ‖ x ‖ (dividing each row vector of x by its norm).

For example, if

x=[023644](3) (3) x = [ 0 3 4 2 6 4 ]
then
x=np.linalg.norm(x,axis=1,keepdims=True)=[556](4) (4) ‖ x ‖ = n p . l i n a l g . n o r m ( x , a x i s = 1 , k e e p d i m s = T r u e ) = [ 5 56 ]
and
x_normalized=xx=[02563565645456](5) (5) x _ n o r m a l i z e d = x ‖ x ‖ = [ 0 3 5 4 5 2 56 6 56 4 56 ]
Note that you can divide matrices of different sizes and it works fine: this is called broadcasting and you’re going to learn about it in part 5.

Exercise: Implement normalizeRows() to normalize the rows of a matrix. After applying this function to an input matrix x, each row of x should be a vector of unit length (meaning length 1).

# GRADED FUNCTION: normalizeRows

def normalizeRows(x):
    """
    Implement a function that normalizes each row of the matrix x (to have unit length).

    Argument:
    x -- A numpy matrix of shape (n, m)

    Returns:
    x -- The normalized (by row) numpy matrix. You are allowed to modify x.
    """

    ### START CODE HERE ### (≈ 2 lines of code)
    # Compute x_norm as the norm 2 of x. Use np.linalg.norm(..., ord = 2, axis = ..., keepdims = True)
    x_norm = np.linalg.norm(x,ord=2,axis=1,keepdims=True)

    # Divide x by its norm.
    x = x/x_norm
    ### END CODE HERE ###

    return x
x = np.array([
    [0, 3, 4],
    [1, 6, 4]])
print("normalizeRows(x) = " + str(normalizeRows(x)))
normalizeRows(x) = [[ 0.          0.6         0.8       ]
 [ 0.13736056  0.82416338  0.54944226]]

Expected Output:

**normalizeRows(x)** [[ 0. 0.6 0.8 ] [ 0.13736056 0.82416338 0.54944226]]

Note:
In normalizeRows(), you can try to print the shapes of x_norm and x, and then rerun the assessment. You’ll find out that they have different shapes. This is normal given that x_norm takes the norm of each row of x. So x_norm has the same number of rows but only 1 column. So how did it work when you divided x by x_norm? This is called broadcasting and we’ll talk about it now!

1.5 - Broadcasting and the softmax function

A very important concept to understand in numpy is “broadcasting”. It is very useful for performing mathematical operations between arrays of different shapes. For the full details on broadcasting, you can read the official broadcasting documentation.

Exercise: Implement a softmax function using numpy. You can think of softmax as a normalizing function used when your algorithm needs to classify two or more classes. You will learn more about softmax in the second course of this specialization.

Instructions:
- for xR1×nsoftmax(x)=softmax([x1x2xn])=[ex1jexjex2jexj...exnjexj] for  x ∈ R 1 × n ,  s o f t m a x ( x ) = s o f t m a x ( [ x 1 x 2 … x n ] ) = [ e x 1 ∑ j e x j e x 2 ∑ j e x j . . . e x n ∑ j e x j ]

  • for a matrix xRm×nxij maps to the element in the ith row and jth column of x, thus we have:  for a matrix  x ∈ R m × n ,  x i j  maps to the element in the  i t h  row and  j t h  column of  x , thus we have: 
    softmax(x)=softmaxx11x21xm1x12x22xm2x13x23xm3x1nx2nxmn=ex11jex1jex21jex2jexm1jexmjex12jex1jex22jex2jexm2jexmjex13jex1jex23jex2jexm3jexmjex1njex1jex2njex2jexmnjexmj=softmax(first row of x)softmax(second row of x)...softmax(last row of x) s o f t m a x ( x ) = s o f t m a x [ x 11 x 12 x 13 … x 1 n x 21 x 22 x 23 … x 2 n ⋮ ⋮ ⋮ ⋱ ⋮ x m 1 x m 2 x m 3 … x m n ] = [ e x 11 ∑ j e x 1 j e x 12 ∑ j e x 1 j e x 13 ∑ j e x 1 j … e x 1 n ∑ j e x 1 j e x 21 ∑ j e x 2 j e x 22 ∑ j e x 2 j e x 23 ∑ j e x 2 j … e x 2 n ∑ j e x 2 j ⋮ ⋮ ⋮ ⋱ ⋮ e x m 1 ∑ j e x m j e x m 2 ∑ j e x m j e x m 3 ∑ j e x m j … e x m n ∑ j e x m j ] = ( s o f t m a x (first row of x) s o f t m a x (second row of x) . . . s o f t m a x (last row of x) )
# GRADED FUNCTION: softmax

def softmax(x):
    """Calculates the softmax for each row of the input x.

    Your code should work for a row vector and also for matrices of shape (n, m).

    Argument:
    x -- A numpy matrix of shape (n,m)

    Returns:
    s -- A numpy matrix equal to the softmax of x, of shape (n,m)
    """

    ### START CODE HERE ### (≈ 3 lines of code)
    # Apply exp() element-wise to x. Use np.exp(...).
    x_exp = np.exp(x)

    # Create a vector x_sum that sums each row of x_exp. Use np.sum(..., axis = 1, keepdims = True).
    x_sum = np.sum(x_exp,axis=1,keepdims=True)

    # Compute softmax(x) by dividing x_exp by x_sum. It should automatically use numpy broadcasting.
    s = x_exp/x_sum

    ### END CODE HERE ###

    return s
x = np.array([
    [9, 2, 5, 0, 0],
    [7, 5, 0, 0 ,0]])
print("softmax(x) = " + str(softmax(x)))
softmax(x) = [[  9.80897665e-01   8.94462891e-04   1.79657674e-02   1.21052389e-04
    1.21052389e-04]
 [  8.78679856e-01   1.18916387e-01   8.01252314e-04   8.01252314e-04
    8.01252314e-04]]

Expected Output:

**softmax(x)** [[ 9.80897665e-01 8.94462891e-04 1.79657674e-02 1.21052389e-04 1.21052389e-04] [ 8.78679856e-01 1.18916387e-01 8.01252314e-04 8.01252314e-04 8.01252314e-04]]

Note:
- If you print the shapes of x_exp, x_sum and s above and rerun the assessment cell, you will see that x_sum is of shape (2,1) while x_exp and s are of shape (2,5). x_exp/x_sum works due to python broadcasting.

Congratulations! You now have a pretty good understanding of python numpy and have implemented a few useful functions that you will be using in deep learning.


What you need to remember:
- np.exp(x) works for any np.array x and applies the exponential function to every coordinate
- the sigmoid function and its gradient
- image2vector is commonly used in deep learning
- np.reshape is widely used. In the future, you’ll see that keeping your matrix/vector dimensions straight will go toward eliminating a lot of bugs.
- numpy has efficient built-in functions
- broadcasting is extremely useful

2) Vectorization

In deep learning, you deal with very large datasets. Hence, a non-computationally-optimal function can become a huge bottleneck in your algorithm and can result in a model that takes ages to run. To make sure that your code is computationally efficient, you will use vectorization. For example, try to tell the difference between the following implementations of the dot/outer/elementwise product.

import time

x1 = [9, 2, 5, 0, 0, 7, 5, 0, 0, 0, 9, 2, 5, 0, 0]
x2 = [9, 2, 2, 9, 0, 9, 2, 5, 0, 0, 9, 2, 5, 0, 0]

### CLASSIC DOT PRODUCT OF VECTORS IMPLEMENTATION ###
tic = time.process_time()
dot = 0
for i in range(len(x1)):
    dot+= x1[i]*x2[i]
toc = time.process_time()
print ("dot = " + str(dot) + "\n ----- Computation time = " + str(1000*(toc - tic)) + "ms")

### CLASSIC OUTER PRODUCT IMPLEMENTATION ###
tic = time.process_time()
outer = np.zeros((len(x1),len(x2))) # we create a len(x1)*len(x2) matrix with only zeros
for i in range(len(x1)):
    for j in range(len(x2)):
        outer[i,j] = x1[i]*x2[j]
toc = time.process_time()
print ("outer = " + str(outer) + "\n ----- Computation time = " + str(1000*(toc - tic)) + "ms")

### CLASSIC ELEMENTWISE IMPLEMENTATION ###
tic = time.process_time()
mul = np.zeros(len(x1))
for i in range(len(x1)):
    mul[i] = x1[i]*x2[i]
toc = time.process_time()
print ("elementwise multiplication = " + str(mul) + "\n ----- Computation time = " + str(1000*(toc - tic)) + "ms")

### CLASSIC GENERAL DOT PRODUCT IMPLEMENTATION ###
W = np.random.rand(3,len(x1)) # Random 3*len(x1) numpy array
tic = time.process_time()
gdot = np.zeros(W.shape[0])
for i in range(W.shape[0]):
    for j in range(len(x1)):
        gdot[i] += W[i,j]*x1[j]
toc = time.process_time()
print ("gdot = " + str(gdot) + "\n ----- Computation time = " + str(1000*(toc - tic)) + "ms")
x1 = [9, 2, 5, 0, 0, 7, 5, 0, 0, 0, 9, 2, 5, 0, 0]
x2 = [9, 2, 2, 9, 0, 9, 2, 5, 0, 0, 9, 2, 5, 0, 0]

### VECTORIZED DOT PRODUCT OF VECTORS ###
tic = time.process_time()
dot = np.dot(x1,x2)
toc = time.process_time()
print ("dot = " + str(dot) + "\n ----- Computation time = " + str(1000*(toc - tic)) + "ms")

### VECTORIZED OUTER PRODUCT ###
tic = time.process_time()
outer = np.outer(x1,x2)
toc = time.process_time()
print ("outer = " + str(outer) + "\n ----- Computation time = " + str(1000*(toc - tic)) + "ms")

### VECTORIZED ELEMENTWISE MULTIPLICATION ###
tic = time.process_time()
mul = np.multiply(x1,x2)
toc = time.process_time()
print ("elementwise multiplication = " + str(mul) + "\n ----- Computation time = " + str(1000*(toc - tic)) + "ms")

### VECTORIZED GENERAL DOT PRODUCT ###
tic = time.process_time()
dot = np.dot(W,x1)
toc = time.process_time()
print ("gdot = " + str(dot) + "\n ----- Computation time = " + str(1000*(toc - tic)) + "ms")

As you may have noticed, the vectorized implementation is much cleaner and more efficient. For bigger vectors/matrices, the differences in running time become even bigger.

Note that np.dot() performs a matrix-matrix or matrix-vector multiplication. This is different from np.multiply() and the * operator (which is equivalent to .* in Matlab/Octave), which performs an element-wise multiplication.

2.1 Implement the L1 and L2 loss functions

Exercise: Implement the numpy vectorized version of the L1 loss. You may find the function abs(x) (absolute value of x) useful.

Reminder:
- The loss is used to evaluate the performance of your model. The bigger your loss is, the more different your predictions ( y^ y ^ ) are from the true values ( y y ). In deep learning, you use optimization algorithms like Gradient Descent to train your model and to minimize the cost.
- L1 loss is defined as:

(6)L1(y^,y)=i=0m|y(i)y^(i)|

# GRADED FUNCTION: L1

def L1(yhat, y):
    """
    Arguments:
    yhat -- vector of size m (predicted labels)
    y -- vector of size m (true labels)

    Returns:
    loss -- the value of the L1 loss function defined above
    """

    ### START CODE HERE ### (≈ 1 line of code)
    loss = sum(abs(yhat-y))
    ### END CODE HERE ###

    return loss
yhat = np.array([.9, 0.2, 0.1, .4, .9])
y = np.array([1, 0, 0, 1, 1])
print("L1 = " + str(L1(yhat,y)))
L1 = 1.1

Expected Output:

**L1** 1.1

Exercise: Implement the numpy vectorized version of the L2 loss. There are several way of implementing the L2 loss but you may find the function np.dot() useful. As a reminder, if x=[x1,x2,...,xn] x = [ x 1 , x 2 , . . . , x n ] , then np.dot(x,x) = nj=0x2j ∑ j = 0 n x j 2 .

  • L2 loss is defined as
    L2(y^,y)=i=0m(y(i)y^(i))2(7) (7) L 2 ( y ^ , y ) = ∑ i = 0 m ( y ( i ) − y ^ ( i ) ) 2
# GRADED FUNCTION: L2

def L2(yhat, y):
    """
    Arguments:
    yhat -- vector of size m (predicted labels)
    y -- vector of size m (true labels)

    Returns:
    loss -- the value of the L2 loss function defined above
    """

    ### START CODE HERE ### (≈ 1 line of code)
    loss = sum((yhat-y)**2)
    ### END CODE HERE ###

    return loss
yhat = np.array([.9, 0.2, 0.1, .4, .9])
y = np.array([1, 0, 0, 1, 1])
print("L2 = " + str(L2(yhat,y)))
L2 = 0.43

Expected Output:

**L2** 0.43

Congratulations on completing this assignment. We hope that this little warm-up exercise helps you in the future assignments, which will be more exciting and interesting!


What to remember:
- Vectorization is very important in deep learning. It provides computational efficiency and clarity.
- You have reviewed the L1 and L2 loss.
- You are familiar with many numpy functions such as np.sum, np.dot, np.multiply, np.maximum, etc…

<think>我们正在寻找与CUDA 12.1、NumPy 1.24和PyTorch 2.2.1兼容的OpenCV版本。 由于OpenCV本身是一个独立的库,它需要与CUDA编译才能利用GPU加速。因此,我们需要一个支持CUDA 12.1的OpenCV版本。 注意:OpenCV的官方预编译版本通常不包含CUDA支持。因此,我们通常需要从源代码编译OpenCV以启用CUDA。 但是,我们可以通过以下步骤来确定兼容性: 1. 确定OpenCV版本与CUDA 12.1的兼容性。 2. 检查该OpenCV版本是否支持NumPy 1.24(通常,OpenCV的Python绑定依赖于NumPy,且较新的OpenCV版本支持较新的NumPy版本)。 3. PyTorch 2.2.1与OpenCV没有直接依赖,但我们需要确保在同一个Python环境中它们可以共存。 根据OpenCV的发布历史,OpenCV 4.5.5及以上版本开始支持CUDA 12.x。具体来说: - OpenCV 4.5.5:实验性支持CUDA 12.0 - OpenCV 4.7.0:支持CUDA 12.0(但注意CUDA 12.1可能向后兼容) - OpenCV 4.8.0及以上:对CUDA 12.x有更好的支持。 由于CUDA 12.1是较新的版本,建议使用最新的OpenCV版本(如4.9.0)以确保兼容性。 另外,NumPy 1.24是一个较新的版本,OpenCV 4.x通常要求NumPy>=1.13.3,而最新的OpenCV版本(如4.9.0)可以很好地与NumPy 1.24配合使用。 因此,推荐使用OpenCV 4.9.0(或最新版本)并自行从源代码编译,配置时指定CUDA 12.1。 编译步骤概述: 1. 安装依赖项(包括CUDA 12.1和cuDNN,以及必要的编译工具)。 2. 下载OpenCV源代码(例如4.9.0)。 3. 使用CMake配置,启用CUDA,并设置CUDA_TOOLKIT_ROOT_DIR为CUDA 12.1的安装路径。 4. 编译并安装。 注意:在编译时,确保Python环境(例如使用conda或virtualenv)中已经安装了NumPy 1.24,因为OpenCV的Python绑定会在编译时链接到该环境中的NumPy。 另外,PyTorch 2.2.1与CUDA 12.1的安装可以通过以下命令(来自官方): ```bash conda install pytorch==2.2.1 torchvision==0.17.1 torchaudio==2.2.1 pytorch-cuda=12.1 -c pytorch -c nvidia ``` 或使用pip: ```bash pip3 install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu121 ``` 因此,在同一个环境中安装OpenCV(从源码编译)和PyTorch 2.2.1(通过conda或pip)是可行的。 总结:推荐使用OpenCV 4.9.0(或更高版本)从源码编译,以支持CUDA 12.1,并确保在编译时环境中已安装NumPy 1.24。 如果不想自己编译,也可以寻找第三方预编译的包含CUDA支持的OpenCV包(但可能较难找到与CUDA 12.1完全匹配的预编译版本)。 因此,最终建议:自行编译OpenCV 4.9.0。 编译步骤参考(简化版): 1. 安装依赖: ```bash sudo apt-get update sudo apt-get install -y build-essential cmake git pkg-config libgtk-3-dev \ libavcodec-dev libavformat-dev libswscale-dev libv4l-dev \ libxvidcore-dev libx264-dev libjpeg-dev libpng-dev libtiff-dev \ gfortran openexr libatlas-base-dev python3-dev python3-numpy \ libtbb2 libtbb-dev libdc1394-22-dev ``` 2. 下载OpenCV和opencv_contrib(可选): ```bash wget -O opencv.zip https://github.com/opencv/opencv/archive/refs/tags/4.9.0.zip wget -O opencv_contrib.zip https://github.com/opencv/opencv_contrib/archive/refs/tags/4.9.0.zip unzip opencv.zip unzip opencv_contrib.zip ``` 3. 创建构建目录并进入: ```bash cd opencv-4.9.0 mkdir build cd build ``` 4. 运行CMake(注意:设置Python解释器和NumPy的路径,以及CUDA相关选项): ```bash cmake -D CMAKE_BUILD_TYPE=RELEASE \ -D CMAKE_INSTALL_PREFIX=/usr/local \ -D INSTALL_PYTHON_EXAMPLES=ON \ -D OPENCV_GENERATE_PKGCONFIG=ON \ -D OPENCV_EXTRA_MODULES_PATH=../../opencv_contrib-4.9.0/modules \ -D WITH_CUDA=ON \ -D ENABLE_FAST_MATH=1 \ -D CUDA_FAST_MATH=1 \ -D WITH_CUBLAS=1 \ -D CUDA_TOOLKIT_ROOT_DIR=/usr/local/cuda-12.1 \ -D BUILD_opencv_python3=ON \ -D BUILD_EXAMPLES=ON .. ``` 注意:请根据你的CUDA安装路径调整`CUDA_TOOLKIT_ROOT_DIR`。 5. 编译并安装: ```bash make -j$(nproc) sudo make install ``` 6. 验证安装: ```bash python3 -c "import cv2; print(cv2.__version__)" ``` 注意:编译过程可能需要较长时间,并且确保系统有足够的内存。 如果遇到问题,可以查阅OpenCV官方文档:https://docs.opencv.org/4.9.0/d7/d9f/tutorial_linux_install.html 因此,适配的OpenCV版本是4.9.0(或更新版本),通过从源码编译并启用CUDA 12.1支持。 相关问题: 1. 如何验证OpenCV是否成功启用了CUDA支持? 2. 在编译OpenCV时,如何解决常见的依赖问题? 3. 除了从源码编译,是否有其他方法安装支持CUDA 12.1的OpenCV?</think>### OpenCV版本兼容性分析 根据您的需求(适配CUDA 12.1、NumPy 1.24和PyTorch 2.2.1),以下是兼容性分析和推荐方案: #### 1. **核心兼容性结论** - **推荐OpenCV版本**:**4.9.0**(最新稳定版) - **验证依据**: - **CUDA 12.1支持**:OpenCV从**4.8.0**开始[正式支持CUDA 12.x](https://github.com/opencv/opencv/wiki/CUDA)[^1],4.9.0完全兼容CUDA 12.1的编译和加速功能。 - **NumPy 1.24支持**:OpenCV 4.9.0的Python绑定已适配NumPy 1.24的API变更(如`np.int`等弃用类型)[^2]。 - **PyTorch 2.2.1兼容**:两者均为Python库,无直接冲突,可通过虚拟环境隔离管理。 #### 2. **安装方案** ##### 方案一:源码编译(推荐) ```bash # 安装依赖 sudo apt install build-essential cmake git libgtk2.0-dev pkg-config conda create -n opencv_env python=3.10 numpy=1.24 pytorch=2.2.1 cudatoolkit=12.1 conda activate opencv_env # 下载源码 git clone --branch 4.9.0 https://github.com/opencv/opencv.git git clone --branch 4.9.0 https://github.com/opencv/opencv_contrib.git # 配置编译(关键CUDA选项) cd opencv && mkdir build && cd build cmake \ -D WITH_CUDA=ON \ -D CUDA_ARCH_BIN="8.9" # 适配RTX 40系显卡 \ -D CUDA_TOOLKIT_ROOT_DIR=/usr/local/cuda-12.1 \ -D OPENCV_DNN_CUDA=ON \ -D BUILD_opencv_python3=ON \ -D PYTHON3_EXECUTABLE=$(which python) \ -D OPENCV_EXTRA_MODULES_PATH=../../opencv_contrib/modules .. # 编译安装 make -j$(nproc) sudo make install ``` ##### 方案二:预编译包(快速验证) ```bash pip install opencv-contrib-python-headless==4.9.0.80 ``` > **注意**:预编译包**不包含CUDA支持**,仅适用于快速验证基础功能。 #### 3. **关键验证命令** ```python import cv2, torch, numpy print(cv2.__version__) # 应输出 4.9.0 print(cv2.cuda.getCudaEnabledDeviceCount() > 0) # 检查CUDA支持 print(torch.__version__) # 2.2.1 print(numpy.__version__) # 1.24.x ``` #### 4. **已知注意事项** 1. **CUDA编译依赖**: - 需安装CUDA 12.1和匹配的cuDNN(≥8.9.4) - 若遇`nvcc`错误,添加`-D CUDA_GENERATION=Auto`到CMake[^2] 2. **PyTorch交互**: - 使用`torch.from_numpy(cv2_image)`转换时,需确保内存连续: ```python cv2_image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) # 通道转换 tensor = torch.ascontiguousarray(torch.from_numpy(cv2_image)) ``` --- ### 相关问题 1. 如何验证OpenCV是否正确启用了CUDA加速? 2. 在Windows系统上编译支持CUDA 12.1的OpenCV有哪些特殊步骤? 3. OpenCV与PyTorch混合编程时如何避免内存拷贝开销? 4. 使用Docker部署CUDA版OpenCV的最佳实践是什么? [^1]: OpenCV官方CUDA支持文档: https://docs.opencv.org/4.9.0/d0/d3d/tutorial_gpu_basics_similarity.html [^2]: OpenCV GitHub编译指南: https://github.com/opencv/opencv/wiki/CPU-optimizations-build-options
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值