在 Python 中获取数组与标量的内积
若要获取数组与标量的内积,请在 Python 中使用 numpy.inner() 方法。对于 1-D 数组的普通向量内积,在更高维度上,对上一个轴进行求和乘积。参数是 1 和 b,两个向量。如果 a 和 b 为非标量,则其最后一个维度必须匹配。
步骤
首先,导入所需的库-
import numpy as np
使用 numpy.eye() 创建数组。此方法返回一个 2-D 数组,其中对角线为 1,其他位置为 0 −
arr = np.eye(5)
val 是标量 −
val = 2
检查数据类型 −
print("\nDatatype of Array...\n",arr.dtype)
检查维度 −
print("\nDimensions of Array...\n",arr.ndim)检查形状 −
print("\nShape of Array...\n",arr.shape)若要获取数组与标量的外积,请在 Python 中使用 numpy.outer() 方法 −
print("\nResult (Outer Product)...\n",np.outer(arr, val))若要获取数组与标量的内积,请在 Python 中使用 numpy.inner() 方法 −
print("\nResult (Inner Product)...\n",np.inner(arr, val))
示例
import numpy as np
# Create an array using numpy.eye(). This method returns a 2-D array with ones on the diagonal and zeros elsewhere.
arr = np.eye(5)
# The val is the scalar
val = 2
# Display the array
print("Array...\n",arr)
# Check the datatype
print("\nDatatype of Array...\n",arr.dtype)
# Check the Dimension
print("\nDimensions of Array...\n",arr.ndim)
# Check the Shape
print("\nShape of Array...\n",arr.shape)
# To get the Inner product of an array and a scalar, use the numpy.inner() method in Python
print("\nResult (Inner Product)...\n",np.inner(arr, val))输出
Array... [[1. 0. 0. 0. 0.] [0. 1. 0. 0. 0.] [0. 0. 1. 0. 0.] [0. 0. 0. 1. 0.] [0. 0. 0. 0. 1.]] Datatype of Array... float64 Dimensions of Array... 2 Shape of Array... (5, 5) Result (Inner Product)... [[2. 0. 0. 0. 0.] [0. 2. 0. 0. 0.] [0. 0. 2. 0. 0.] [0. 0. 0. 2. 0.] [0. 0. 0. 0. 2.]]
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
安卓
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP