How to use the slice syntax #982
|
How can I write code equivalent to the following python code? tensor = torch.ones(4, 4)
print('First row: ',tensor[0])
print('First column: ', tensor[:, 0])
print('Last column:', tensor[..., -1])
tensor[:,1] = 0
print(tensor) |
Replies: 4 comments 2 replies
|
That depends on whether you're using .NET FX or .NET Core, since we don't have System.Range in the former. Assuming that you're using .NET Core: var tensor = torch.ones(4, 4);
Console.WriteLine($"First row: {tensor[0].str()}");
Console.WriteLine($"First column: {tensor[.., 0].str()}");
Console.WriteLine($"Last column: {tensor[TensorIndex.Ellipsis, ^1].str()");
tensor[..,1] = 0;
Console.WriteLine(tensor.str());The See the TorchSharp C# tutorials for more details: https://github.com/dotnet/TorchSharpExamples/tree/main/tutorials/CSharp |
|
That said, I and didn't realize this, but you can just use -1 instead of ^1. So: Console.WriteLine($"Last column: {tensor[TensorIndex.Ellipsis, -1].str()}"); |
|
The System.Index issue has been addressed in 0.99.6 |
|
It seems that F#'s slice syntax can be managed by implementing type torch.Tensor with
member t.GetSlice(startIdx: int option, endIdx: int option) =
match startIdx, endIdx with
| Some s, Some e -> t[torch.TensorIndex.Slice(s, e)]
| Some s, None -> t[torch.TensorIndex.Slice(s)]
| None, Some e -> t[torch.TensorIndex.Slice(System.Nullable(), e)]
| None, None -> t[torch.TensorIndex.Slice()]
member t.SetSlice(startIdx: int option, endIdx: int option, v: torch.Tensor) =
match startIdx, endIdx with
| Some s, Some e -> t[torch.TensorIndex.Slice(s, e)] <- v
| Some s, None -> t[torch.TensorIndex.Slice(s)] <- v
| None, Some e -> t[torch.TensorIndex.Slice(System.Nullable(), e)] <- v
| None, None -> t[torch.TensorIndex.Slice()] <- v
let t = torch.arange(24).view(4, 3, 2)
t[1..3] <- torch.tensor(1)
printfn $"{t.str()}" |
That depends on whether you're using .NET FX or .NET Core, since we don't have System.Range in the former. Assuming that you're using .NET Core:
The
str()is necessary, because the defaultToString()function does not print all the values, just the metadata. There's an overloadedToString()that does the right thing, but I chose thestr()extension method just for brevity's sake.See the TorchSharp C# tutorials for more deta…