简体   繁体   English

python map如何与torch.tensor一起使用?

[英]How does python map works with torch.tensor?

I am now in python so I am trying to understand this line from pytorch tutorial . 我现在在python中,所以我试图从pytorch教程中了解这一行。

x_train, y_train, x_valid, y_valid = map(
    torch.tensor, (x_train, y_train, x_valid, y_valid)
)

I understand how map works on a single element 我了解地图如何在单个元素上工作

def sqr(a):
    return a * a

a = [1, 2, 3, 4]    

a = map(sqr, a)
print(list(a))

And here I need to use list(a) to convert map object back to list. 在这里,我需要使用list(a)将地图对象转换回list。

But what I don't understand, is how does it work on multiple variables? 但是我不明白的是,它如何在多个变量上工作?

If I try to do this 如果我尝试这样做

def sqr(a):
    return a * a


a = [1, 2, 3, 4]
b = [1, 3, 5, 7]

a, b = map(sqr, (a, b))
print(list(a))
print(list(b))

I get an error: TypeError: can't multiply sequence by non-int of type 'list' 我收到一个错误: TypeError: can't multiply sequence by non-int of type 'list'

Please clarify this for me Thank you 请为我澄清一下谢谢

map works on a single the same way it works on list/tuple of lists, it fetches an element of the given input regardless what is it. map工作方式与处理列表/列表元组的方式相同,无论它是什么,它都会获取给定输入的元素。

The reason why torch.tensor works, is that it accepts a list as input. torch.tensor起作用的原因是,它接受列表作为输入。

If you unfold the following line you provided: 如果展开以下行,则提供了以下内容:

x_train, y_train, x_valid, y_valid = map(
    torch.tensor, (x_train, y_train, x_valid, y_valid)
)

it's the same as doing: 这和做的一样:

x_train, y_train, x_valid, y_valid = [torch.tensor(x_train), torch.tensor(y_train), torch.tensor(x_valid), torch.tensor(y_valid)]

On other hand, your sqr function does not accept lists. 另一方面,您的sqr函数不接受列表。 It expects a scalar type to square, which is not the case for your a an b , they are lists. 它期望标量类型为平方,而ab则不是这种情况,它们是列表。

However, if you change sqr to: 但是,如果将sqr更改为:

def sqr(a):
    return [s * s for s in a]


a = [1, 2, 3, 4]
b = [1, 3, 5, 7]

a, b = map(sqr, (a, b))

or as suggested by @Jean, a, b = map(sqr, x) for x in (a, b) 或如@Jean所建议, a, b = map(sqr, x) for x in (a, b)

It will work. 它会工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM