对齐Python列表以模拟一维内核卷积

问题描述 投票:0回答:1

我有两个Python列表,一个在概念上代表一维内核,另一个列表是要卷积的一系列值:

listA = [1, 2, 3, 4, 5, 6]

# Visualize it as if it was a Pandas dataframe:
+-----------------------+
| a | b | c | i | j | k |
+-----------------------+
| 1 | 2 | 3 | 4 | 5 | 6 |
+-----------------------+

kernel = [2, 4, 2]

我想做的是将内核乘以listA上相应的3个值,并使内核的中心与给定值对齐。示例:

# Kernel centered at listA.b
+-----------------------+
| a | b | c | i | j | k |
+-----------------------+
| 1 | 2 | 3 | 4 | 5 | 6 |
+-----------------------+
+-----------+
| 2 | 4 | 2 |
+-----------+

# Kernel centered at listA.c
+-----------------------+
| a | b | c | i | j | k |
+-----------------------+
| 1 | 2 | 3 | 4 | 5 | 6 |
+-----------------------+
    +-----------+
    | 2 | 4 | 2 |
    +-----------+

# Kernel centered at listA.k
#  -> note that the kernel is too big, so some of the values
#     run off listA. This is the expected behavior
+-----------------------+
| a | b | c | i | j | k |
+-----------------------+
| 1 | 2 | 3 | 4 | 5 | 6 |
+-----------------------+
                +-------+
                | 2 | 4 |
                +-------+

我如何执行此对齐?

python linear-algebra convolution
1个回答
0
投票

请查看是否有帮助,

# unpadded list
listA = [1, 2, 3, 4, 5, 6]

# 1x3 kernel
kernelA = [2, 4, 2]

# 1x5 kernel
kernelB = [1, 1, 1, 1, 1]


#kernel = kernelA
kernel = kernelB
loopVal = len(kernel) >> 1
#print(loopVal)


"""
# padded list on both sides
listB = listA.copy()
for i in range(0, loopVal):
    listB.insert(0, 0)
    listB.append(0)
print(listB)
print()
"""

# Full padded list on one side
listB = listA.copy()
for i in range(0, len(kernel) - 1):
    listB.append(0)
print(listB)
print()



## Does not use padded list
#sample = listA

## uses padded list
sample = listB


output = []
for i in range(loopVal, len(sample) - loopVal):
    tmp = 0
    for j in range(0, len(kernel)):
        print(sample[i - loopVal + j], kernel[j])
        tmp += sample[i - loopVal + j] * kernel[j]
    output.append(tmp)
    print(tmp)

print()
print("1D convolution output:")
print(output)

输出:

[1, 2, 3, 4, 5, 6, 0, 0, 0, 0]

1 1
2 1
3 1
4 1
5 1
15
2 1
3 1
4 1
5 1
6 1
20
3 1
4 1
5 1
6 1
0 1
18
4 1
5 1
6 1
0 1
0 1
15
5 1
6 1
0 1
0 1
0 1
11
6 1
0 1
0 1
0 1
0 1
6

1D convolution output:
[15, 20, 18, 15, 11, 6]
© www.soinside.com 2019 - 2024. All rights reserved.