使用Python计算数组和字母向量的外积

使用Python计算数组和字母向量的外积

给定两个向量a = [a0, a1, …, aM]和b = [b0, b1, …, bN],外积定义如下:

[[a0*b0 a0*b1 ... a0*bN ]
[a1*b0 .
[ ... .
[aM*b0     aM*bN ]]

使用Python的numpy.outer()方法可以获得数组与字母向量的外积。

第一个参数a是第一个输入向量。如果输入不是一维的,则会被平铺。第二个参数b是第二个输入向量。如果输入不是一维的,则会被平铺。第三个参数out是存储结果的位置。

步骤:

首先,导入所需的库 –

import numpy as np

使用array()方法创建两个numpy一维数组。第一个数组是字母的向量。第二个数组是整数数组−

arr1 = np.array(['p', 'q', 'r', 's'], dtype=object)
arr2 = np.array([2, 3, 1, 3])

显示数组 –

print("Array1...\n",arr1)
print("\nArray2...\n",arr2)

检查两个数组的尺寸 –

print("\nDimensions of Array1...\n",arr1.ndim)
print("\nDimensions of Array2...\n",arr2.ndim)

检查两个数组的形状 –

print("\nShape of Array1...\n",arr1.shape)
print("\nShape of Array2...\n",arr2.shape)

使用numpy.outer()方法来获取数组与字母向量的外积。

print("\nResult (Outer Product)...\n",np.outer(arr1, arr2))

示例

import numpy as np

# Creating two numpy One-Dimensional arrays using the array() method
# The 1st array is a vector of letters
# The 2nd array is an integer array
arr1 = np.array(['p', 'q', 'r', 's'], dtype=object)
arr2 = np.array([2, 3, 1, 3])

# Display the arrays
print("Array1...\n",arr1)
print("\nArray2...\n",arr2)

# Check the Dimensions of both the arrays
print("\nDimensions of Array1...\n",arr1.ndim)
print("\nDimensions of Array2...\n",arr2.ndim)

# Check the Shape of both the arrays
print("\nShape of Array1...\n",arr1.shape)
print("\nShape of Array2...\n",arr2.shape)

# To get the Outer product of an array with vector of letters, use the numpy.outer() method in Python
print("\nResult (Outer Product)...\n",np.outer(arr1, arr2))

输出

Array1...
['p' 'q' 'r' 's']

Array2...
[2 3 1 3]

Dimensions of Array1...
1

Dimensions of Array2...
1

Shape of Array1...
(4,)

Shape of Array2...
(4,)

Result (Outer Product)...
[['pp' 'ppp' 'p' 'ppp']
['qq' 'qqq' 'q' 'qqq']
['rr' 'rrr' 'r' 'rrr']
['ss' 'sss' 's' 'sss']]

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程