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.

README.md 25 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  1. <div align=center>
  2. <img src="./docs/_static/img/logo/logo.svg" width="420" height="auto" style="max-width: 100%;"/>
  3. <br/>
  4. <br/>
  5. </div>
  6. <div align="center">
  7. <a href="https://pypi.org/project/learnware/#files">
  8. <img alt="Python Versions" src="https://img.shields.io/pypi/pyversions/learnware.svg?logo=python&logoColor=white">
  9. </a>
  10. <a href="https://pypi.org/project/learnware/#files">
  11. <img alt="Platform" src="https://img.shields.io/badge/platform-linux%20%7C%20windows-lightgrey">
  12. </a>
  13. <a href="https://pypi.org/project/learnware/#history">
  14. <img alt="PypI Versions" src="https://img.shields.io/pypi/v/learnware">
  15. </a>
  16. <a href="https://img.shields.io/pypi/dm/example-package">
  17. <img alt="PyPI Downloads" src="https://img.shields.io/pypi/dm/example-package">
  18. </a>
  19. <a href="https://learnware.readthedocs.io/en/latest/?badge=latest">
  20. <img alt="Documentation Status" src="https://readthedocs.org/projects/learnware/badge/?version=latest">
  21. </a>
  22. <a href="LICENSE">
  23. <img alt="License" src="https://img.shields.io/pypi/l/learnware">
  24. </a>
  25. </div>
  26. <div>
  27. <h3 align="center">
  28. <a href="README_zh.md">中文</a> |
  29. <b>English</b>
  30. </h3>
  31. </div>
  32. # Introduction
  33. _Learnware_ paradigm was proposed by Professor Zhi-Hua Zhou in 2016 [1, 2]. In the _learnware paradigm_, developers worldwide can share models with the _learnware dock system_, which effectively searches for and reuse learnware(s) to help users solve machine learning tasks efficiently without starting from scratch.
  34. The `learnware` package provides a fundamental implementation of the central concepts and procedures within the learnware paradigm. Its well-structured design ensures high scalability and facilitates the seamless integration of additional features and techniques in the future.
  35. In addition, the `learnware` package serves as the engine for the [Beimingwu System](https://bmwu.cloud) and can be effectively employed for conducting experiments related to learnware.
  36. [1] Zhi-Hua Zhou. Learnware: on the future of machine learning. _Frontiers of Computer Science_, 2016, 10(4): 589–590 <br/>
  37. [2] Zhi-Hua Zhou. Machine Learning: Development and Future. _Communications of CCF_, 2017, vol.13, no.1 (2016 CNCC keynote)
  38. ## Learnware Paradigm
  39. A learnware consists of a high-performance machine learning model and specifications that characterize the model, i.e., "Learnware = Model + Specification". These specifications, encompassing both semantic and statistical aspects, detail the model's functionality and statistical information, making it easier for future users to identify and reuse these models.
  40. <div align="center">
  41. <img src="./docs/_static/img/learnware_market.svg" width="700" height="auto" style="max-width: 100%;" />
  42. </div>
  43. The above diagram illustrates the learnware paradigm, which consists of two distinct stages:
  44. - `Submitting Stage`: Developers voluntarily submit various learnwares to the learnware doc system, and the system conducts quality checks and further organization of these learnwares.
  45. - `Deploying Stage`: When users submit task requirements, the learnware doc system automatically selects whether to recommend a single learnware or a combination of multiple learnwares and provides efficient deployment methods. Whether it’s a single learnware or a combination of multiple learnwares, the system offers convenient learnware reuse interfaces.
  46. ## Framework and Infrastructure Design
  47. <div align="center">
  48. <img src="./docs/_static/img/learnware_framework.svg" width="700" height="auto" style="max-width: 100%;"/>
  49. </div>
  50. The architecture is designed based on the guidelines including _decoupling_, _autonomy_, _reusability_, and _scalability_. The above diagram illustrates the framework from the perspectives of both modules and workflows.
  51. - At the workflow level, the `learnware` package consists of `Submitting Stage` and `Deploying Stage`.
  52. <div align=center>
  53. | Module | Workflow |
  54. | ---- | ---- |
  55. | `Submitting Stage` | The developers submit learnwares to the learnware market, which conducts usability checks and further organization of these learnwares. |
  56. | `Deploying Stage` | The learnware market recommends learnwares according to users’ task requirements and provides efficient reuse and deployment methods. |
  57. </div>
  58. - At the module level, the `learnware` package is a platform that consists of `Learnware`, `Market`, `Specification`, `Model`, `Reuse`, and `Interface` modules.
  59. <div align=center>
  60. | Module | Description |
  61. | ---- | ---- |
  62. | `Learnware` | The specific learnware, consisting of specification module, and user model module. |
  63. | `Market` | Designed for learnware organization, identification, and usability testing. |
  64. | `Specification` | Generating and storing statistical and semantic information of learnware, which can be used for learnware search and reuse. |
  65. | `Model` | Including the base model and the model container, which can provide unified interfaces and automatically create isolated runtime environments. |
  66. | `Reuse` | Including the data-free reuser, data-dependent reuser, and aligner, which can deploy and reuse learnware for user tasks. |
  67. | `Interface` | The interface for network communication with the `Beimingwu` backend.|
  68. </div>
  69. # Quick Start
  70. ## Installation
  71. Learnware is currently hosted on [PyPI](https://pypi.org/project/learnware/). You can easily install `learnware` by following these steps:
  72. ```bash
  73. pip install learnware
  74. ```
  75. In the `learnware` package, besides the base classes, many core functionalities such as "learnware specification generation" and "learnware deployment" rely on the `torch` library. Users have the option to manually install `torch`, or they can directly use the following command to install the `learnware` package:
  76. ```bash
  77. pip install learnware[full]
  78. ```
  79. **Note:** However, it's crucial to note that due to the potential complexity of the user's local environment, installing `learnware[full]` does not guarantee that `torch` will successfully invoke `CUDA` in the user's local setting.
  80. ## Prepare Learnware
  81. In the `learnware` package, each learnware is encapsulated in a `zip` package, which should contain at least the following four files:
  82. - `learnware.yaml`: learnware configuration file.
  83. - `__init__.py`: methods for using the model.
  84. - `stat.json`: the statistical specification of the learnware. Its filename can be customized and recorded in learnware.yaml.
  85. - `environment.yaml` or `requirements.txt`: specifies the environment for the model.
  86. To facilitate the construction of a learnware, we provide a [Learnware Template](https://www.bmwu.cloud/static/learnware-template.zip) that users can use as a basis for building their own learnware. We've also detailed the format of the learnware `zip` package in [Learnware Preparation](https://learnware.readthedocs.io/en/latest/workflows/upload.html#prepare-learnware).
  87. ## Learnware Package Workflow
  88. Users can start a `learnware` workflow according to the following steps:
  89. ### Initialize a Learnware Market
  90. You can initialize a basic `Learnware Market` named "demo" using the code snippet below:
  91. ```python
  92. from learnware.market import instantiate_learnware_market
  93. # instantiate a demo market
  94. demo_market = instantiate_learnware_market(market_id="demo", name="easy", rebuild=True)
  95. ```
  96. ### Upload Learnware
  97. Before uploading your learnware to the `Learnware Market`, you'll need to create a semantic specification, `semantic_spec`. This involves selecting or inputting values for semantic tags to describe the features of your task and model.
  98. For instance, the following code illustrates the semantic specification for a Scikit-Learn type model. This model is tailored for education scenarios and performs classification tasks on tabular data:
  99. ```python
  100. from learnware.specification import generate_semantic_spec
  101. semantic_spec = generate_semantic_spec(
  102. name="demo_learnware",
  103. data_type="Table",
  104. task_type="Classification",
  105. library_type="Scikit-learn",
  106. scenarios="Education",
  107. license="MIT",
  108. )
  109. ```
  110. After preparing the semantic specification, you can insert your learnware into the learnware market using a single line of code:
  111. ```python
  112. demo_market.add_learnware(zip_path, semantic_spec)
  113. ```
  114. Here, `zip_path` is the file path of your learnware `zip` package.
  115. ### Semantic Specification Search
  116. To identify learnwares that align with your task's purpose, you'll need to provide a semantic specification, `user_semantic`, that outlines your task's characteristics. The `Learnware Market` will then perform an initial search based on `user_semantic`, which filters learnwares by considering the semantic information of your task.
  117. ```python
  118. # construct user_info, which includes a semantic specification
  119. user_info = BaseUserInfo(id="user", semantic_spec=semantic_spec)
  120. # search_learnware: performs semantic specification search when user_info doesn't include a statistical specification
  121. search_result = demo_market.search_learnware(user_info)
  122. single_result = search_results.get_single_results()
  123. # single_result: the List of Tuple[Score, Learnware] returned by semantic specification search
  124. print(single_result)
  125. ```
  126. ### Statistical Specification Search
  127. If you generate and provide a statistical specification file `rkme.json`, the `Learnware Market` will conduct learnware identification based on statistical information, and return more targeted models. Using the API we provided, you can easily generate this statistical specification locally.
  128. For example, the code below executes learnware search when using Reduced Kernel Mean Embedding (RKME) as the statistical specification:
  129. ```python
  130. import learnware.specification as specification
  131. user_spec = specification.RKMETableSpecification()
  132. # unzip_path: directory for unzipped learnware zipfile
  133. user_spec.load(os.path.join(unzip_path, "rkme.json"))
  134. user_info = BaseUserInfo(
  135. semantic_spec=user_semantic, stat_info={"RKMETableSpecification": user_spec}
  136. )
  137. search_result = demo_market.search_learnware(user_info)
  138. single_result = search_results.get_single_results()
  139. multiple_result = search_results.get_multiple_results()
  140. # search_item.score: based on MMD distances, sorted in descending order
  141. # search_item.learnware.id: id of learnwares, sorted by scores in descending order
  142. for search_item in single_result:
  143. print(f"score: {search_item.score}, learnware_id: {search_item.learnware.id}")
  144. # mixture_item.learnwares: collection of learnwares whose combined use is beneficial
  145. # mixture_item.score: score assigned to the combined set of learnwares in `mixture_item.learnwares`
  146. for mixture_item in multiple_result:
  147. print(f"mixture_score: {mixture_item.score}\n")
  148. mixture_id = " ".join([learnware.id for learnware in mixture_item.learnwares])
  149. print(f"mixture_learnware: {mixture_id}\n")
  150. ```
  151. ### Reuse Learnwares
  152. We offer two data-free methods `JobSelectorReuser` and `AveragingReuser` for reusing a given list of learnwares. Please substitute ``test_x`` in the code snippet below with your own testing data:
  153. ```python
  154. from learnware.reuse import JobSelectorReuser, AveragingReuser
  155. # using job selector reuser to reuse the searched learnwares to make prediction
  156. reuse_job_selector = JobSelectorReuser(learnware_list=mixture_item.learnwares)
  157. job_selector_predict_y = reuse_job_selector.predict(user_data=test_x)
  158. # using averaging ensemble reuser to reuse the searched learnwares to make prediction
  159. reuse_ensemble = AveragingReuser(learnware_list=mixture_item.learnwares)
  160. ensemble_predict_y = reuse_ensemble.predict(user_data=test_x)
  161. ```
  162. We also provide two data-dependent methods: `EnsemblePruningReuser` and `FeatureAugmentReuser`, when the user has minor labeled data for refining a given list of learnwares. Here's an example for adopting multiple returned learnwares by labeled data to solve classification tasks:
  163. ```python
  164. from learnware.reuse import EnsemblePruningReuser, FeatureAugmentReuser
  165. # Use ensemble pruning reuser to reuse the searched learnwares to make prediction
  166. # (train_x, train_y) is the small amount of labeled data
  167. # `mode` has two options "classification" and "regression"
  168. reuse_ensemble = EnsemblePruningReuser(learnware_list=mixture_item.learnwares, mode="classification")
  169. reuse_ensemble.fit(train_x, train_y)
  170. ensemble_pruning_predict_y = reuse_ensemble.predict(user_data=test_x)
  171. # Use feature augment reuser to reuse the searched learnwares to make prediction
  172. reuse_feature_augment = FeatureAugmentReuser(learnware_list=mixture_item.learnwares, mode="classification")
  173. reuse_feature_augment.fit(train_x, train_y)
  174. feature_augment_predict_y = reuse_feature_augment.predict(user_data=test_x)
  175. ```
  176. ### Auto Workflow Example
  177. The `learnware` package also offers automated workflow examples. This includes preparing learnwares, uploading and deleting learnwares from the market, and searching for learnwares using both semantic and statistical specifications. To experience the basic workflow of the `learnware` package, the users can run `test/test_workflow/test_workflow.py` to try the basic workflow of `learnware`.
  178. # Experiments and Examples
  179. We build various types of experimental scenarios and conduct extensive empirical study to evaluate the baseline algorithms for specification generation, learnware identification, and reuse on tabular, image, and text data.
  180. ## Environment
  181. For all experiments, we used a single Linux server. Details on the specifications are listed in the table below. All processors were used for training and evaluating.
  182. <div align=center>
  183. | System | GPU | CPU |
  184. |----------------------|--------------------|--------------------------|
  185. | Ubuntu 20.04.4 LTS | Nvidia Tesla V100S | Intel(R) Xeon(R) Gold 6240R |
  186. </div>
  187. ## Tabular Scenario Experiments
  188. On various tabular datasets, we initially evaluate the performance of identifying and reusing learnwares from the learnware market that share the same feature space as the user's tasks. Additionally, since tabular tasks often come from heterogeneous feature spaces, we also assess the identification and reuse of learnwares from different feature spaces.
  189. ### Settings
  190. Our study utilize three public datasets in the field of sales forecasting: [Predict Future Sales (PFS)](https://www.kaggle.com/c/competitive-data-science-predict-future-sales/data), [M5 Forecasting (M5)](https://www.kaggle.com/competitions/m5-forecasting-accuracy/data), and [Corporacion](https://www.kaggle.com/competitions/favorita-grocery-sales-forecasting/data). To enrich the data, we apply diverse feature engineering methods to these datasets. Then we divide each dataset by store and further split the data for each store into training and test sets. A LightGBM is trained on each Corporacion and PFS training set, while the test sets and M5 datasets are reversed to construct user tasks. This results in an experimental market consisting of 265 learnwares, encompassing five types of feature spaces and two types of label spaces. All these learnwares have been uploaded to the [Beimingwu system](https://bmwu.cloud/).
  191. ### Baseline algorithms
  192. The most basic way to reuse a learnware is Top-1 reuser, which directly uses the single learnware chosen by RKME specification. Besides, we implement two data-free reusers and two data-dependent reusers that works on single or multiple helpful learnwares identified from the market. When users have no labeled data, JobSelector reuser selects different learnwares for different samples by training a job selector classifier; AverageEnsemble reuser uses an ensemble method to make predictions. In cases where users possess both test data and limited labeled training data, EnsemblePruning reuser selectively ensembles a subset of learnwares to choose the ones that are most suitable for the user’s task; FeatureAugment reuser regards each received learnware as a feature augmentor, taking its output as a new feature and then builds a simple model on the augmented feature set. JobSelector and FeatureAugment are only effective for tabular data, while others are also useful for text and image data.
  193. ### Homogeneous Cases
  194. In the homogeneous cases, the 53 stores within the PFS dataset function as 53 individual users. Each store utilizes its own test data as user data and applies the same feature engineering approach used in the learnware market. These users could subsequently search for homogeneous learnwares within the market that possessed the same feature spaces as their tasks.
  195. We conduct a comparison among different baseline algorithms when the users have no labeled data or limited amounts of labeled data. The average losses over all users are illustrated in the table below. It shows that unlabeled methods are much better than random choosing and deploying one learnware from the market.
  196. <div align=center>
  197. | Setting | MSE |
  198. |-----------------------------------|--------|
  199. | Mean in Market (Single) | 0.897 |
  200. | Best in Market (Single) | 0.756 |
  201. | Top-1 Reuse (Single) | 0.830 |
  202. | Job Selector Reuse (Multiple) | 0.848 |
  203. | Average Ensemble Reuse (Multiple) | 0.816 |
  204. </div>
  205. The figure below showcases the results for different amounts of labeled data provided by the user; for each user, we conducted multiple experiments repeatedly and calculated the mean and standard deviation of the losses; the average losses over all users are illustrated in the figure. It illustrates that when users have limited training data, identifying and reusing single or multiple learnwares yields superior performance compared to user's self-trained models.
  206. <div align=center>
  207. <img src="./docs/_static/img/Homo_labeled_curves.svg" width="500" height="auto" style="max-width: 100%;"/>
  208. </div>
  209. ### Heterogeneous Cases
  210. Based on the similarity of tasks between the market's learnwares and the users, the heterogeneous cases can be further categorized into different feature engineering and different task scenarios.
  211. #### Different Feature Engineering Scenarios
  212. We consider the 41 stores within the PFS dataset as users, generating their user data using a unique feature engineering approach that differ from the methods employed by the learnwares in the market. As a result, while some learnwares in the market are also designed for the PFS dataset, the feature spaces do not align exactly.
  213. In this experimental setup, we examine various data-free reusers. The results in the following table indicate that even when users lack labeled data, the market exhibits strong performance, particularly with the AverageEnsemble method that reuses multiple learnwares.
  214. <div align=center>
  215. | Setting | MSE |
  216. |-----------------------------------|--------|
  217. | Mean in Market (Single) | 1.149 |
  218. | Best in Market (Single) | 1.038 |
  219. | Top-1 Reuse (Single) | 1.075 |
  220. | Average Ensemble Reuse (Multiple) | 1.064 |
  221. </div>
  222. #### Different Task Scenarios
  223. We employ three distinct feature engineering methods on all the ten stores from the M5 dataset, resulting in a total of 30 users. Although the overall task of sales forecasting aligns with the tasks addressed by the learnwares in the market, there are no learnwares specifically designed to satisfy the M5 sales forecasting requirements.
  224. In the following figure, we present the loss curves for the user's self-trained model and several learnware reuse methods. It is evident that heterogeneous learnwares prove beneficial with a limited amount of the user's labeled data, facilitating better alignment with the user's specific task.
  225. <div align=center>
  226. <img src="./docs/_static/img/Hetero_labeled_curves.svg" width="500" height="auto" style="max-width: 100%;"/>
  227. </div>
  228. ## Image Scenario Experiment
  229. Second, we assess our algorithms on image datasets. It is worth noting that images of different sizes could be standardized through resizing, eliminating the need to consider heterogeneous feature cases.
  230. ### Settings
  231. We choose the famous image classification dataset [CIFAR-10](https://www.cs.toronto.edu/~kriz/cifar.html), which consists of 60000 32x32 color images in 10 classes. A total of 50 learnwares are uploaded: each learnware contains a convolutional neural network trained on an unbalanced subset that includs 12000 samples from four categories with a sampling ratio of `0.4:0.4:0.1:0.1`.
  232. A total of 100 user tasks are tested and each user task consists of 3000 samples of CIFAR-10 with six categories with a sampling ratio of `0.3:0.3:0.1:0.1:0.1:0.1`.
  233. ### Results
  234. We assess the average performance of various methods using 1 - Accuracy as the loss metric. The following table and figure show that when users face a scarcity of labeled data or possess only a limited amount of it (less than 2000 instances), leveraging the learnware market can yield good performances.
  235. <div align=center>
  236. | Setting | Accuracy |
  237. |-----------------------------------|----------|
  238. | Mean in Market (Single) | 0.655 |
  239. | Best in Market (Single) | 0.304 |
  240. | Top-1 Reuse (Single) | 0.406 |
  241. | Job Selector Reuse (Multiple) | 0.406 |
  242. | Average Ensemble Reuse (Multiple) | 0.310 |
  243. </div>
  244. <div align=center>
  245. <img src="./docs/_static/img/image_labeled_curves.svg" width="500" height="auto" style="max-width: 100%;"/>
  246. </div>
  247. ## Text Scenario Experiment
  248. Finally, we evaluate our algorithms on text datasets. Text data naturally exhibit feature heterogeneity, but this issue can be addressed by applying a sentence embedding extractor.
  249. ### Settings
  250. We conduct experiments on the well-known text classification dataset: [20-newsgroup](http://qwone.com/~jason/20Newsgroups/), which consists approximately 20000 newsgroup documents partitioned across 20 different newsgroups. Similar to the image experiments, a total of 50 learnwares are uploaded. Each learnware is trained on a subset that includes only half of the samples from three superclasses and the model in it is a tf-idf feature extractor combined with a naive Bayes classifier. We define 10 user tasks, and each of them encompasses two superclasses.
  251. ### Results
  252. The results are depicted in the following table and figure. Similarly, even when no labeled data is provided, the performance achieved through learnware identification and reuse can match that of the best learnware in the market. Additionally, utilizing the learnware market allows for a reduction of approximately 2000 samples compared to training models from scratch.
  253. <div align=center>
  254. | Setting | Accuracy |
  255. |-----------------------------------|----------|
  256. | Mean in Market (Single) | 0.507 |
  257. | Best in Market (Single) | 0.859 |
  258. | Top-1 Reuse (Single) | 0.846 |
  259. | Job Selector Reuse (Multiple) | 0.845 |
  260. | Average Ensemble Reuse (Multiple) | 0.862 |
  261. </div>
  262. <div align=center>
  263. <img src="./docs/_static/img/text_labeled_curves.svg" width="500" height="auto" style="max-width: 100%;"/>
  264. </div>
  265. # Citation
  266. If you use our project in your research or work, we kindly request that you cite the following papers:
  267. ```bibtex
  268. @article{zhou2024learnware,
  269. title = {Learnware: Small models do big},
  270. author = {Zhou, Zhi-Hua and Tan, Zhi-Hao},
  271. journal = {Science China Information Sciences},
  272. volume = {67},
  273. number = {1},
  274. pages = {112102},
  275. year = {2024}
  276. }
  277. @article{tan2024beimingwu,
  278. title = {Beimingwu: A learnware dock system},
  279. author = {Tan, Zhi-Hao and Liu, Jian-Dong and Bi, Xiao-Dong and Tan, Peng and Zheng, Qin-Cheng and Liu, Hai-Tian and Xie, Yi and Zou, Xiao-Chuan and Yu, Yang and Zhou, Zhi-Hua},
  280. journal = {arXiv preprint arXiv:2401.14427},
  281. year = {2024}
  282. }
  283. ```
  284. # About
  285. ## How to Contribute
  286. `learnware` is still in its early stages and may contain bugs and issues. We highly value and encourage contributions from the community, and we sincerely invite everyone to research and improve learnware algorithms, develop and explore within the learnware paradigm. For detailed development guidelines, please consult our [Developer Guide](https://learnware.readthedocs.io/en/latest/about/dev.html). We kindly request that contributors adhere to the provided commit format and pre-commit configuration when participating in the project. Your valuable contributions are greatly appreciated.
  287. ## About Us
  288. The `learnware` repository is developed and maintained by the LAMDA Beimingwu R&D (Research and Development) Team. To learn more about our team, please visit the [Team Overview](https://docs.bmwu.cloud/en/about-us.html).