while inserting in PG DB Error: can't adapt type 'Tensor'
- User
while inserting in PG DB Error: can't adapt type 'Tensor'
- Assistant
The error "can't adapt type 'Tensor'" typically occurs when you attempt to insert a PyTorch
Tensorobject directly into a PostgreSQL database using a Python database adapter likepsycopg2or SQLAlchemy. These adapters don't know how to convert complex Python objects like Tensors into a format that PostgreSQL understands.Why does this happen?
PostgreSQL expects standard data types (e.g., integers, floats, strings, byte arrays) when you insert data. A PyTorch
Tensoris not a primitive type and can't be directly stored in a database without serialization or conversion.
How to fix this?
1. Convert Tensor to a suitable format before insertion:
You have multiple options depending on how you want to store the tensor data:
Option A: Convert Tensor to list (for numeric arrays)
If the tensor is small and you want to store it as an array or JSON:
pythonimport torch import psycopg2 tensor = torch.tensor([1, 2, 3, 4]) tensor_list = tensor.tolist() # Convert to Python list # Now insert tensor_list as JSON or array depending on your column type # For JSON column example: import json json_value = json.dumps(tensor_list) cursor.execute("INSERT INTO my_table (tensor_data) VALUES (%s)", (json_value,))Make sure your target column is of type
jsonorjsonb.
Option B: Serialize Tensor and store as bytea (binary data)
You can serialize the tensor using
torch.save()to a bytes buffer and store it as bytea in PostgreSQL.pythonimport io import torch tensor = torch.randn(3, 3) buffer = io.BytesIO() torch.save(tensor, buffer) buffer.seek(0) tensor_bytes = buffer.read() cursor.execute("INSERT INTO my_table (tensor_data) VALUES (%s)", (psycopg2.Binary(tensor_bytes),))In this case, your column should be of type
bytea.
Option C: Extract numpy array and save as array type if supported
If you want to store it as a PostgreSQL numeric array, convert to numpy array and then use 's support for arrays: