You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

main.py 7.0 kB

2 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  1. import os
  2. import fire
  3. import joblib
  4. import zipfile
  5. import numpy as np
  6. from sklearn import svm
  7. from shutil import copyfile, rmtree
  8. import learnware
  9. from learnware.market import EasyMarket, BaseUserInfo
  10. from learnware.market import database_ops
  11. from learnware.learnware import Learnware
  12. import learnware.specification as specification
  13. from learnware.utils import get_module_by_module_path
  14. curr_root = os.path.dirname(os.path.abspath(__file__))
  15. semantic_specs = [
  16. {
  17. "Data": {"Values": ["Tabular"], "Type": "Class"},
  18. "Task": {"Values": ["Classification"], "Type": "Class"},
  19. "Device": {"Values": ["GPU"], "Type": "Tag"},
  20. "Scenario": {"Values": ["Business"], "Type": "Tag"},
  21. "Description": {"Values": "", "Type": "String"},
  22. "Name": {"Values": "learnware_1", "Type": "String"},
  23. }
  24. ]
  25. user_senmantic = {
  26. "Data": {"Values": ["Tabular"], "Type": "Class"},
  27. "Task": {
  28. "Values": ["Classification"],
  29. "Type": "Class",
  30. },
  31. "Device": {"Values": ["GPU"], "Type": "Tag"},
  32. "Scenario": {"Values": ["Business"], "Type": "Tag"},
  33. "Description": {"Values": "", "Type": "String"},
  34. "Name": {"Values": "", "Type": "String"},
  35. }
  36. class LearnwareMarketWorkflow:
  37. def _init_learnware_market(self):
  38. """initialize learnware market"""
  39. learnware.init()
  40. np.random.seed(2023)
  41. easy_market = EasyMarket(market_id="workflow_by_code", rebuild=True)
  42. return easy_market
  43. def prepare_learnware_randomly(self, learnware_num=10):
  44. self.zip_path_list = []
  45. for i in range(learnware_num):
  46. dir_path = os.path.join(curr_root, "learnware_pool", "svm_%d" % (i))
  47. os.makedirs(dir_path, exist_ok=True)
  48. print("Preparing Learnware: %d" % (i))
  49. data_X = np.random.randn(5000, 20) * i
  50. data_y = np.random.randn(5000)
  51. data_y = np.where(data_y > 0, 1, 0)
  52. clf = svm.SVC(kernel="linear")
  53. clf.fit(data_X, data_y)
  54. joblib.dump(clf, os.path.join(dir_path, "svm.pkl"))
  55. spec = specification.utils.generate_rkme_spec(X=data_X, gamma=0.1, cuda_idx=0)
  56. spec.save(os.path.join(dir_path, "svm.json"))
  57. init_file = os.path.join(dir_path, "__init__.py")
  58. copyfile(
  59. os.path.join(curr_root, "learnware_example/example_init.py"), init_file
  60. ) # cp example_init.py init_file
  61. yaml_file = os.path.join(dir_path, "learnware.yaml")
  62. copyfile(os.path.join(curr_root, "learnware_example/example.yaml"), yaml_file) # cp example.yaml yaml_file
  63. zip_file = dir_path + ".zip"
  64. # zip -q -r -j zip_file dir_path
  65. with zipfile.ZipFile(zip_file, "w") as zip_obj:
  66. for foldername, subfolders, filenames in os.walk(dir_path):
  67. for filename in filenames:
  68. file_path = os.path.join(foldername, filename)
  69. zip_info = zipfile.ZipInfo(filename)
  70. zip_info.compress_type = zipfile.ZIP_STORED
  71. with open(file_path, "rb") as file:
  72. zip_obj.writestr(zip_info, file.read())
  73. rmtree(dir_path) # rm -r dir_path
  74. self.zip_path_list.append(zip_file)
  75. def test_upload_delete_learnware(self, learnware_num=5, delete=False):
  76. easy_market = self._init_learnware_market()
  77. self.prepare_learnware_randomly(learnware_num)
  78. print("Total Item:", len(easy_market))
  79. for idx, zip_path in enumerate(self.zip_path_list):
  80. semantic_spec = semantic_specs[0]
  81. semantic_spec["Name"]["Values"] = "learnware_%d" % (idx)
  82. semantic_spec["Description"]["Values"] = "test_learnware_number_%d" % (idx)
  83. easy_market.add_learnware(zip_path, semantic_spec)
  84. print("Total Item:", len(easy_market))
  85. curr_inds = easy_market._get_ids()
  86. print("Available ids After Uploading Learnwares:", curr_inds)
  87. if delete:
  88. for learnware_id in curr_inds:
  89. easy_market.delete_learnware(learnware_id)
  90. easy_market.delete_learnware(learnware_id)
  91. curr_inds = easy_market._get_ids()
  92. print("Available ids After Deleting Learnwares:", curr_inds)
  93. return easy_market
  94. def test_search_semantics(self, learnware_num=5):
  95. easy_market = self.test_upload_delete_learnware(learnware_num, delete=False)
  96. print("Total Item:", len(easy_market))
  97. test_folder = os.path.join(curr_root, "test_semantics")
  98. idx, zip_path = 1, self.zip_path_list[1]
  99. unzip_dir = os.path.join(test_folder, f"{idx}")
  100. # unzip -o -q zip_path -d unzip_dir
  101. if os.path.exists(unzip_dir):
  102. rmtree(unzip_dir)
  103. os.makedirs(unzip_dir, exist_ok=True)
  104. with zipfile.ZipFile(zip_path, "r") as zip_obj:
  105. zip_obj.extractall(path=unzip_dir)
  106. user_info = BaseUserInfo(id="user_0", semantic_spec=user_senmantic)
  107. _, single_learnware_list, _ = easy_market.search_learnware(user_info)
  108. print("User info:", user_info.get_semantic_spec())
  109. print(f"search result of user{idx}:")
  110. for learnware in single_learnware_list:
  111. print("Choose learnware:", learnware.id, learnware.get_specification().get_semantic_spec())
  112. rmtree(test_folder) # rm -r test_folder
  113. def test_stat_search(self, learnware_num=5):
  114. easy_market = self.test_upload_delete_learnware(learnware_num, delete=False)
  115. print("Total Item:", len(easy_market))
  116. test_folder = os.path.join(curr_root, "test_stat")
  117. for idx, zip_path in enumerate(self.zip_path_list):
  118. unzip_dir = os.path.join(test_folder, f"{idx}")
  119. # unzip -o -q zip_path -d unzip_dir
  120. if os.path.exists(unzip_dir):
  121. rmtree(unzip_dir)
  122. os.makedirs(unzip_dir, exist_ok=True)
  123. with zipfile.ZipFile(zip_path, "r") as zip_obj:
  124. zip_obj.extractall(path=unzip_dir)
  125. user_spec = specification.rkme.RKMEStatSpecification()
  126. user_spec.load(os.path.join(unzip_dir, "svm.json"))
  127. user_info = BaseUserInfo(
  128. id="user_0", semantic_spec=user_senmantic, stat_info={"RKMEStatSpecification": user_spec}
  129. )
  130. sorted_score_list, single_learnware_list, mixture_learnware_list = easy_market.search_learnware(user_info)
  131. print(f"search result of user{idx}:")
  132. for score, learnware in zip(sorted_score_list, single_learnware_list):
  133. print(f"score: {score}, learnware_id: {learnware.id}")
  134. mixture_id = " ".join([learnware.id for learnware in mixture_learnware_list])
  135. print(f"mixture_learnware: {mixture_id}\n")
  136. rmtree(test_folder) # rm -r test_folder
  137. if __name__ == "__main__":
  138. fire.Fire(LearnwareMarketWorkflow)

基于学件范式,全流程地支持学件上传、检测、组织、查搜、部署和复用等功能。同时,该仓库作为北冥坞系统的引擎,支撑北冥坞系统的核心功能。