gpt-3.5-turbo-0301· openai
Suzhen/CodeChat
How do I convert a nested python array into a pytorch tensor?
- User
How do I convert a nested python array into a pytorch tensor?
- Assistant
You can convert a nested Python array into a PyTorch tensor by using the
torch.tensorfunction. Here's an example:pythonimport torch nested_array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] tensor = torch.tensor(nested_array) print(tensor)Output:
codetensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]])This creates a 2-dimensional tensor from the nested array. If your nested array has more than two levels of nesting, you can use recursion to flatten it before passing it to
torch.tensor. Here's an example:pythondef flatten(nested_array): flat_array = [] for item in nested_array: if isinstance(item, list): flat_array.extend(flatten(item)) else: flat_array.append(item) return flat_array nested_array = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]] flat_array = flatten(nested_array) tensor = torch.tensor(flat_array) print(tensor)