python如何将 数组文件 存储为json文件以及对于json文件的读取

简介

最近项目中要用到PCA计算,PCA从文件中读取数据,然后再写入数据

code

#encoding = utf-8
import numpy as np
import json
from sklearn.decomposition import PCA
from sklearn.datasets import load_iris
from json import JSONEncoder
fileName = "projector.json"
with open(fileName,‘r‘,encoding=‘utf-8‘) as file:
    data=json.load(file)
    #<class ‘dict‘>,JSON文件读入到内存以后,就是一个Python中的字典。
    # 字典是支持嵌套的,
    # print(data)
X = data["data"]
pca = PCA(n_components=3)
pca.fit(X)
newX=pca.transform(X)
new_item = {‘image_path‘: newX}
data = []
data.append(new_item)
class NumpyArrayEncoder(JSONEncoder):
    def default(self, obj):
        if isinstance(obj, np.ndarray):
            return obj.tolist()
        return JSONEncoder.default(self, obj)
encodedNumpyData = json.dumps(data, cls=NumpyArrayEncoder)
with open(‘pathpoints.json‘, ‘w+‘) as jsonFile:
    jsonFile.write(encodedNumpyData)

相关推荐