2
이진 파일에서 numpy 배열을 저장하고로드하고 싶습니다. 이를 위해 두 가지 작은 기능을 만들었습니다. 각 바이너리 파일은 주어진 매트릭스의 차원을 포함해야합니다.이진 파일에서 numpy 배열을 저장 /로드하십시오.
def saveArrayToFile(data, fileName):
with open(fileName, 'w') as file:
a = array.array('f')
nSamples, ndim = data.shape
a.extend([nSamples, ndim]) # write number of elements and dimensions
a.fromstring(data.tostring())
a.tofile(file)
def readArrayFromFile(fileName):
_featDesc = np.fromfile(fileName, 'f')
_ndesc = int(_featDesc[0])
_ndim = int(_featDesc[1])
_featDesc = _featDesc[2:]
_featDesc = _featDesc.reshape([_ndesc, _ndim])
return _featDesc, _ndesc, _ndim
기능을 사용하는 방법에 대한 예는 다음
myarr=np.array([[7, 4],[3, 9],[1, 3]])
saveArrayToFile(myarr,'myfile.txt')
_featDesc, _ndesc, _ndim = readArrayFromFile('myfile.txt')
그러나, 에러 메시지 '에 ValueError : 새로운 어레이의 전체 크기는 불변이어야'가 도시된다. 내 배열의 크기는 MxN 및 MxM 일 수 있습니다. 어떤 제안이라도 환영받는 것 이상입니다. 문제는 saveArrayToFile 함수에 있다고 생각합니다.
행복을 빌며,
하비에르
감사합니다. 그러나 실제로 배열의 MxN 차원을 파일에 저장해야합니다. – Javier
파일 이름을 'myfile_MxN.npy'와 같이 지정하는 것으로 충분합니까? – unutbu
@Javier : 전체 파일을 읽지 않고 데이터를 가져 오려면 왜 파일의 처음 몇 바이트에 배열의 크기를 저장해야하는지 이해할 수 있습니다. 그러나,'_featDesc, _ndesc, _ndim = readArrayFromFile ('myfile.txt')'는 전체 파일을 읽는 것을 제안합니다 (헤더 비트가 보이지 않음). 그렇다면 단순히'arr = np.load (...)'를 사용하고'_ndesc, _ndim = arr.shape'을 사용하지 않을까요? – unutbu