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)


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM