From 8a3a1e6e7dfe21762c68febc648bce763d249245 Mon Sep 17 00:00:00 2001 From: JiaYanhao <2474840061@qq.com> Date: Mon, 4 Jul 2022 10:49:11 +0800 Subject: [PATCH] 0.0.2 --- CART.py => BaseML/CART.py | 0 KNN.py => BaseML/KNN.py | 4 +- BaseML/LICENSE | 201 ++++++++++++++++++++++++++ PCA.py => BaseML/PCA.py | 0 Perceptron.py => BaseML/Perceptron.py | 0 BaseNet/BaseNet.py | 143 ++++++++++++++++++ BaseNet/__init__.py | 6 + Mlearing_Edu.py | 39 ----- __init__.py | 13 ++ ml_demo.py | 25 ---- 10 files changed, 365 insertions(+), 66 deletions(-) rename CART.py => BaseML/CART.py (100%) rename KNN.py => BaseML/KNN.py (94%) create mode 100644 BaseML/LICENSE rename PCA.py => BaseML/PCA.py (100%) rename Perceptron.py => BaseML/Perceptron.py (100%) create mode 100644 BaseNet/BaseNet.py create mode 100644 BaseNet/__init__.py delete mode 100644 Mlearing_Edu.py create mode 100644 __init__.py delete mode 100644 ml_demo.py diff --git a/CART.py b/BaseML/CART.py similarity index 100% rename from CART.py rename to BaseML/CART.py diff --git a/KNN.py b/BaseML/KNN.py similarity index 94% rename from KNN.py rename to BaseML/KNN.py index 764b8d8..7d9df2a 100644 --- a/KNN.py +++ b/BaseML/KNN.py @@ -3,9 +3,9 @@ import os -class KNNClassifier: +class KNN: def __init__(self, - backbone='KNNClassifier', + backbone='KNN', n_neighbors=10, ): self.backbone = backbone diff --git a/BaseML/LICENSE b/BaseML/LICENSE new file mode 100644 index 0000000..261eeb9 --- /dev/null +++ b/BaseML/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/PCA.py b/BaseML/PCA.py similarity index 100% rename from PCA.py rename to BaseML/PCA.py diff --git a/Perceptron.py b/BaseML/Perceptron.py similarity index 100% rename from Perceptron.py rename to BaseML/Perceptron.py diff --git a/BaseNet/BaseNet.py b/BaseNet/BaseNet.py new file mode 100644 index 0000000..08b4677 --- /dev/null +++ b/BaseNet/BaseNet.py @@ -0,0 +1,143 @@ +from statistics import mode +import torch +import torch.nn as nn +from torch.autograd import Variable +import numpy as np +import pandas as pd +import warnings +warnings.filterwarnings('ignore') + +class Reshape(nn.Module): + def __init__(self, *args): + super(Reshape, self).__init__() + self.shape = args + + def forward(self, x): + # print(x.shape,x.view(x.shape[0], -1).shape) + return x.view(x.shape[0], -1) + +def cal_accuracy(y, pred_y): + res = pred_y.argmax(dim=1) + tp = np.array(y)==np.array(res) + acc = np.sum(tp)/ y.shape[0] + return acc + +class BaseNet: + def __init__(self): + self.model = nn.Sequential() + self.batchsize = None + self.layers = [] + self.layers_num = 0 + self.optimizer = 'SGD' + self.x = None + self.y = None + + def add(self, layer=None, activation=None, optimizer=None, **kw): + self.layers_num += 1 + self.layers.append(layer) + if layer == 'Linear': + self.model.add_module('Reshape', Reshape(self.batchsize)) + self.model.add_module('Linear' + str(self.layers_num), nn.Linear(kw['size'][0], kw['size'][1])) + print("增加全连接层,输入维度:{},输出维度:{}。".format(kw['size'][0], kw['size'][1])) + elif layer == 'Reshape': + self.model.add_module('Reshape', Reshape(self.batchsize)) + # elif layer == 'ReLU': + # self.model.add_module('ReLU' + str(self.layers_num), nn.ReLU()) + # print("增加ReLU层。") + elif layer == 'Conv2D': + self.model.add_module('Conv2D' + str(self.layers_num), nn.Conv2d(kw['size'][0], kw['size'][1], kw['kernel_size'])) + print("增加卷积层,输入维度:{},输出维度:{},kernel_size: {} ".format(kw['size'][0], kw['size'][1], kw['kernel_size'])) + elif layer == 'MaxPool': + self.model.add_module('MaxPooling' + str(self.layers_num), nn.MaxPool2d(kw['kernel_size'])) + print("增加最大池化层,kernel_size: {} ".format(kw['kernel_size'])) + elif layer == 'AvgPool': + self.model.add_module('MaxPooling' + str(self.layers_num), nn.AvgPool2d(kw['kernel_size'])) + print("增加平均池化层,kernel_size: {} ".format(kw['kernel_size'])) + + # 激活函数 + if activation == 'ReLU': + self.model.add_module('ReLU' + str(self.layers_num), nn.ReLU()) + print("使用ReLU激活函数。") + elif activation == 'Softmax': + self.model.add_module('Softmax'+str(self.layers_num), nn.Softmax()) + print('使用Softmax激活函数。') + + # 优化器 + if optimizer != None: + self.optimizer = optimizer + + + def load_data(self, x, y): + self.x = Variable(torch.tensor(np.array(x)).to(torch.float32)) + self.y = Variable(torch.tensor(np.array(y))) + + self.batchsize = self.x.shape[0] + + def train(self, lr=0.1, epochs=30): + loss_fun = nn.CrossEntropyLoss() # 使用交叉熵作为损失函数 + if self.optimizer == 'SGD': + optimizer = torch.optim.SGD(self.model.parameters(), lr=lr,momentum=0.9) # 使用SGD优化器 + elif self.optimizer == 'Adam': + optimizer = torch.optim.Adam(self.model.parameters(), lr=lr) + elif self.optimizer == 'Adagrad': + optimizer = torch.optim.Adagrad(self.model.parameters(), lr=lr) + elif self.optimizer == 'ASGD': + optimizer = torch.optim.ASGD(self.model.parameters(), lr=lr) + print("使用 {} 优化器。".format(self.optimizer)) + for epoch in range(epochs): + y_pred = self.model(self.x) + acc = cal_accuracy(self.y, y_pred) + # print(y_pred, self.y) + loss = loss_fun(y_pred, self.y) + print("{epoch:%d Loss:%.4f Accuracy:%.4f}" % (epoch, loss, acc)) + optimizer.zero_grad() # 将梯度初始化为零,即清空过往梯度 + loss.backward() # 反向传播,计算当前梯度 + optimizer.step() # 根据梯度更新网络参数 + + def inference(self, data, show=False): + data = Variable(torch.tensor(np.array(data)).to(torch.float32)) + with torch.no_grad(): + res = self.model(data) + if show: + print("推理结果为:",res) + return res + + def print_model(self): + # print('模型共{}层'.format(self.layers_num)) + print(self.model) + + def save(self, model_path='mmbase_net.pkl'): + print("保存模型中...") + torch.save(self.model, model_path) + print("保存模型{}成功!".format(model_path)) + + def load(self,model_path): + print("载入模型中...") + self.model = torch.load(model_path) + print("载入模型{}成功!".format(model_path)) + +def test1(): + x = Variable(torch.randn(100, 1, 20,20)) # 生成随机数据 + # x = np.array((torch.randn(100, 1, 20,20))) # 生成随机数据,numpy形式 + y = Variable(torch.randint(0, 2, (100,))) # 生成随机标签 + + test_x = Variable(torch.randn(1,1,20,20)) # 生成测试数据 + model = BaseNet() #声明模型 + model.load_data(x, y) # 载入数据 + # 添加各种层,注释为输入数据经过每个层的尺寸变化 + model.add('Conv2D', size=(1, 3),kernel_size=( 3, 3)) # [100, 3, 18, 18] + model.add('MaxPool', kernel_size=(2,2), activation='ReLU') # [100, 3, 9, 9] + model.add('Conv2D', size=(3, 10), kernel_size=(3, 3)) # [100, 10, 7, 7] + model.add('AvgPool', kernel_size=(2,2), activation='ReLU') # [100, 10, 3, 3] + model.add('Linear', size=(90, 10), activation='ReLU') # [100, 10] + model.add('Linear', size=(10, 2), activation='Softmax') # [100,2] + model.add(optimizer='SGD') + # model.print_model() + model.train(lr=0.1, epochs=300) # 训练 + # model.save("mmbase_net.pkl") # 保存模型 + # model.load("mmbase_net.pkl") # 加载模型 + # model.inference(test_x) # 推理 + +if __name__ == "__main__": + test1() + diff --git a/BaseNet/__init__.py b/BaseNet/__init__.py new file mode 100644 index 0000000..22fb687 --- /dev/null +++ b/BaseNet/__init__.py @@ -0,0 +1,6 @@ +from .BaseNet import BaseNet +import torch +import torch.nn as nn +from torch.autograd import Variable + +__all__ = ['BaseNet','torch', 'nn', 'Variable'] \ No newline at end of file diff --git a/Mlearing_Edu.py b/Mlearing_Edu.py deleted file mode 100644 index 952b645..0000000 --- a/Mlearing_Edu.py +++ /dev/null @@ -1,39 +0,0 @@ -import pandas as pd -import numpy as np -from sklearn.model_selection import train_test_split -from sklearn.ensemble import RandomForestClassifier -from sklearn.metrics import accuracy_score -import os - -class MMMlearing: - def __init__(self, - backbone='RandomForest' - ): - self.backbone = backbone - # 获取外部运行py的绝对路径 - self.cwd = os.path.dirname(os.getcwd()) - # 获取当前文件的绝对路径 - self.file_dirname = os.path.dirname(os.path.abspath(__file__)) - self.model = RandomForestClassifier() - - def train(self, seed=0): - np.random.seed(seed) - dataset = pd.read_csv(self.dataset_path, sep=',', header=None).values - np.random.shuffle(dataset) - data, label = dataset[:,:-1],dataset[:,-1] - train_index = int((1-self.test_size) * len(dataset)) - train_data, train_label = data[:train_index, :], label[:train_index] - self.test_set = { - 'data':data[train_index:, :], - 'label':label[train_index:] - } - self.model.fit(train_data, train_label) - - def inference(self): - pred = self.model.predict(self.test_set['data']) - acc = accuracy_score(self.test_set['label'], pred) - print('准确率为:{}%'.format(acc*100)) - - def load_dataset(self, path, test_size=0.2): - self.dataset_path = path - self.test_size = test_size \ No newline at end of file diff --git a/__init__.py b/__init__.py new file mode 100644 index 0000000..40375e1 --- /dev/null +++ b/__init__.py @@ -0,0 +1,13 @@ +from .BaseML import CART +from .BaseML import KNN +from .BaseML import PCA +from .BaseML import Perceptron +from .BaseNet import BaseNet + +__all__ = [ + 'BaseNet', + 'CART', + # 'KNNClassifier', + 'KNN', + 'PCA', + 'Perceptron'] \ No newline at end of file diff --git a/ml_demo.py b/ml_demo.py deleted file mode 100644 index 149058c..0000000 --- a/ml_demo.py +++ /dev/null @@ -1,25 +0,0 @@ -from sklearn.datasets import load_wine -from KNN import KNNClassifier -from PCA import PCA -import numpy as np - - -def knn_demo(): - model = KNNClassifier(n_neighbors=10) - model.load_dataset(dataset=load_wine()) - model.train() - test_data = np.array([[11.8, 4.39, 2.39, 29, 82, 2.86, 3.53, 0.21, 2.85, 2.8, 0.75, 3.78, 490]]) - model.inference(test_data) - - -def pca_demo(): - data = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]]) - model = PCA(n_components='mle') - model.load_dataset(dataset=data) - model.train() - model.inference(data) - - -if __name__ == '__main__': - knn_demo() - pca_demo()