├── neural_networks.py ├── README.md ├── .gitignore ├── clustering.py ├── criteria.py ├── classification.py ├── performance.py ├── ReleaseLog.txt ├── model_drawer.py ├── pytorch.py ├── regression.py ├── preprocessor.py └── LICENSE /neural_networks.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Wed Sep 4 00:25:27 2019 4 | 5 | @author: 俊男 6 | """ 7 | 8 | # In[] Import Area 9 | import tensorflow as tf 10 | from tensorflow.keras.models import Sequential 11 | from tensorflow.keras import layers 12 | 13 | # In[] create_seq_model(): A function generating a sequential neural network model 14 | def create_seq_model(nodes=[], weight_init="glorot_normal", 15 | hidden_activation="relu", opt_name="adam", metric_list=["acc"], 16 | output_activation="softmax", loss_name="categorical_crossentropy"): 17 | # Check the version of Keras 18 | keras_version = tf.keras.__version__ 19 | 20 | # Create Sequential Model 21 | model = Sequential() 22 | 23 | if nodes != []: 24 | # Create Input Layer 25 | if keras_version.startswith("2."): 26 | model.add(layers.InputLayer(input_shape=nodes[0], name="input")) 27 | elif keras_version.startswith("3."): 28 | model.add(layers.Input(shape=(nodes[0],), name="input")) 29 | else: 30 | raise ValueError(f"Unsupported Keras version: {keras_version}, please use 2.x or 3.x instead.") 31 | 32 | # Create Hidden Layers 33 | for i in range(1, len(nodes)-1): 34 | hidden_name = "hidden_{}".format(i) 35 | model.add(layers.Dense(units=nodes[i], kernel_initializer=weight_init, activation=hidden_activation, name=hidden_name)) 36 | 37 | # Create Output Layers 38 | model.add(layers.Dense(units=nodes[-1], kernel_initializer=weight_init, activation=output_activation, name="output")) 39 | 40 | # Compile Neural Network 41 | model.compile(optimizer=opt_name, loss=loss_name, metrics=metric_list) 42 | 43 | # Return built model 44 | return model -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # HappyML Introduction 2 | HappyML is a machine learning library for educational purpose. This library simplified many aspects of machine learning including preprocessing, model creation, data visualization...etc. This library is for experimental purpose and does not recommend to use in production. 3 | 4 | HappyML 是一個教學用的機器學習函式庫。該函式庫簡化了機器學習的程式碼寫作。包括:前處理、模型建置、資料視覺化...等方面。本函式庫乃教學用途,實驗性質重,可能存在不少潛在錯誤。不建議直接使用在正式場合。 5 | 6 | 如果您對每個版本修改了哪些東西的細節好奇,也歡迎您參考 ReleaseLog.txt。 7 | 8 | 9 | 10 | # Revision History 11 | 12 | * 2024/03/23-01 13 | * [NEW] pytorch.py: The file contains a class called Sequential. The class inherits torch.nn.Module and provides functions that allow people who are only familiar with TensorFlow/Keras, but not PyTorch, to build PyTorch models using Keras-like functions in the class. 14 | * 2023/02/10-01 15 | * [BUGFIX] preprocessor.feature_scaling(): Fix an error message caused by the feature_scaling() function when the incoming array is not a DataFrame. 16 | * [NEW] MultipleRegressor.named_features: It can return the dimension reduction result with "field name" except the column "const" instead of "index". For example: ['R&D Spend', 'Marketing Spend']. 17 | * 2023/02/05-01 18 | * [NEW] MultipleRegressor: Now it can automatically detect if there are constants in the incoming X_train and X_test. If not, it will be added automatically. 19 | * 2021/06/06-01 20 | * [FIX] Heatmap in criteria.AssumptionChecker.features_correlation() will overlap with other plot. 21 | * 2021/06/03-01 22 | * [FIX] cluster_drawer() shows error message: "findfont: Font family ['sans-serif'] not found. Falling back to DejaVu Sans" 23 | * 2021/05/26-01 24 | * [FIX] PCASelector.fit() shows same information no matter verbose=True or =False. 25 | * 2021/05/19-01 26 | * [REMOVE] Remove auto=False parameter from KBestSelector.fit() 27 | * [FIX] KBestSelector.fit() show nothing when <>auto and verbose=True. 28 | * [FIX] Remove iid= parameter from GridSearchCV() 29 | * 2020/08/03-01 30 | * [NEW] Add show_first_n_images() into model_drawer.py 31 | * [NEW] Add create_seq_model() into neural_networks.py 32 | * 2020/07/26-01 33 | * [NEW] Add epochs_metrics_plot() into model_drawer.py 34 | * 2020/07/26-01 35 | * [NEW] Create this repository. 36 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | target/ 76 | 77 | # Jupyter Notebook 78 | .ipynb_checkpoints 79 | 80 | # IPython 81 | profile_default/ 82 | ipython_config.py 83 | 84 | # pyenv 85 | .python-version 86 | 87 | # pipenv 88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 91 | # install all needed dependencies. 92 | #Pipfile.lock 93 | 94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 95 | __pypackages__/ 96 | 97 | # Celery stuff 98 | celerybeat-schedule 99 | celerybeat.pid 100 | 101 | # SageMath parsed files 102 | *.sage.py 103 | 104 | # Environments 105 | .env 106 | .venv 107 | env/ 108 | venv/ 109 | ENV/ 110 | env.bak/ 111 | venv.bak/ 112 | 113 | # Spyder project settings 114 | .spyderproject 115 | .spyproject 116 | 117 | # Rope project settings 118 | .ropeproject 119 | 120 | # mkdocs documentation 121 | /site 122 | 123 | # mypy 124 | .mypy_cache/ 125 | .dmypy.json 126 | dmypy.json 127 | 128 | # Pyre type checker 129 | .pyre/ 130 | -------------------------------------------------------------------------------- /clustering.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Mon Aug 26 22:18:56 2019 4 | 5 | @author: 俊男 6 | """ 7 | 8 | # In[] KMeans 9 | import numpy as np 10 | import pandas as pd 11 | import matplotlib.pyplot as plt 12 | import time 13 | 14 | from sklearn.cluster import KMeans 15 | from sklearn.preprocessing import MinMaxScaler 16 | 17 | 18 | class KMeansCluster: 19 | __cluster = None 20 | __best_k = None 21 | __max_k = None 22 | __strategy = None 23 | __random_state = None 24 | __centroids = None 25 | 26 | def __init__(self, best_k="auto", max_k=10, random_state=int(time.time())): 27 | if type(best_k) is int: 28 | self.__strategy = "fixed" 29 | self.best_k = best_k 30 | else: 31 | self.__strategy = "auto" 32 | self.best_k = 8 33 | 34 | self.__max_k = max_k 35 | self.__random_state = random_state 36 | 37 | self.__cluster = KMeans(n_clusters=self.best_k, max_iter=300, n_init=10, init="k-means++", random_state=self.__random_state) 38 | 39 | @property 40 | def cluster(self): 41 | return self.__cluster 42 | 43 | @cluster.setter 44 | def cluster(self, cluster): 45 | self.__cluster = cluster 46 | 47 | @property 48 | def best_k(self): 49 | return self.__best_k 50 | 51 | @best_k.setter 52 | def best_k(self, best_k): 53 | if (type(best_k) is int) and (best_k >= 1): 54 | self.__best_k = best_k 55 | else: 56 | self.__best_k = 1 57 | 58 | @property 59 | def centroids(self): 60 | return self.__centroids 61 | 62 | def fit(self, x_ary, verbose=False, plot=False): 63 | if self.__strategy == "auto": 64 | wcss = [] 65 | for i in range(1, self.__max_k+1): 66 | kmeans = KMeans(n_clusters=i, max_iter=300, n_init=10, init="k-means++", random_state=self.__random_state) 67 | kmeans.fit(x_ary) 68 | wcss.append(kmeans.inertia_) 69 | 70 | scaler = MinMaxScaler(feature_range=(0, len(wcss)-1)) 71 | wcss_scaled = scaler.fit_transform(np.array(wcss).reshape(-1, 1)).ravel() 72 | for i in range(1, wcss_scaled.shape[0]): 73 | if (wcss_scaled[i-1]-wcss_scaled[i]) < 1: 74 | break 75 | self.best_k = i 76 | 77 | if verbose: 78 | print("The best clusters = {}".format(self.best_k)) 79 | 80 | if plot: 81 | plt.plot(range(1, len(wcss)+1), wcss, color="blue") 82 | plt.scatter(x=self.best_k, y=wcss[self.best_k], color="red") 83 | plt.title("The Best Cluster") 84 | plt.xlabel("# of Clusters") 85 | plt.ylabel("WCSS") 86 | plt.show() 87 | 88 | # Fit the Model 89 | self.cluster = KMeans(n_clusters=self.best_k, random_state=self.__random_state) 90 | self.cluster.fit(x_ary) 91 | self.__centroids = self.cluster.cluster_centers_ 92 | 93 | return self 94 | 95 | def predict(self, x_ary, y_column="Result"): 96 | return pd.DataFrame(self.cluster.predict(x_ary), index=x_ary.index, columns=[y_column]) 97 | -------------------------------------------------------------------------------- /criteria.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Sat Aug 3 11:43:24 2019 4 | 5 | @author: 俊男 6 | """ 7 | 8 | # In[] Define the Class for Checking Linear Regression Assumption 9 | import matplotlib.pyplot as plt 10 | import scipy.stats as stats 11 | from pandas.plotting import autocorrelation_plot 12 | import pandas as pd 13 | import seaborn as sns 14 | import numpy as np 15 | 16 | class AssumptionChecker: 17 | __x_train = None 18 | __x_test = None 19 | __y_train = None 20 | __y_test = None 21 | __y_pred = None 22 | __residuals = None 23 | 24 | __x_lim = None 25 | __y_lim = None 26 | __heatmap = False 27 | 28 | def __init__(self, x_train, x_test, y_train, y_test, y_pred): 29 | self.__x_train = x_train 30 | self.__x_test = x_test 31 | self.__y_train = y_train 32 | self.__y_test = y_test 33 | 34 | self.__y_pred = y_pred 35 | self.__residuals = (self.__y_test.values.ravel() - self.__y_pred.values.ravel()) 36 | 37 | @property 38 | def x_lim(self): 39 | return self.__x_lim 40 | 41 | @x_lim.setter 42 | def x_lim(self, x_lim): 43 | self.__x_lim = x_lim 44 | 45 | @property 46 | def y_lim(self): 47 | return self.__y_lim 48 | 49 | @y_lim.setter 50 | def y_lim(self, y_lim): 51 | self.__y_lim = y_lim 52 | 53 | @property 54 | def heatmap(self): 55 | return self.__heatmap 56 | 57 | @heatmap.setter 58 | def heatmap(self, heatmap): 59 | self.__heatmap = heatmap 60 | 61 | def sample_linearity(self): 62 | print("*** Check for Linearity of Independent to Dependent Variable ***") 63 | 64 | for i in range(self.__x_train.values.shape[1]): 65 | plt.scatter(self.__x_train.values[:, i], self.__y_train.values, color="red") 66 | plt.title("Linearity of Column {}".format(self.__x_train.columns[i])) 67 | plt.xlabel(self.__x_train.columns[i]) 68 | plt.ylabel("".join(self.__y_train.columns)) 69 | plt.show() 70 | 71 | def residuals_normality(self): 72 | print("*** Check for Normality of Residuals ***") 73 | 74 | stats.probplot(self.__residuals, plot=plt) 75 | plt.show() 76 | 77 | def residuals_independence(self): 78 | print("*** Check for Independence of Residuals ***") 79 | 80 | df_res = pd.DataFrame(self.__residuals) 81 | autocorrelation_plot(df_res) 82 | plt.show() 83 | 84 | def residuals_homoscedasticity(self, x_lim=None, y_lim=None): 85 | print("*** Check for Homoscedasticity of Residuals ***") 86 | 87 | if x_lim != None: 88 | self.x_lim = x_lim 89 | if y_lim != None: 90 | self.y_lim = y_lim 91 | 92 | plt.scatter(self.__y_pred, self.__residuals, color="red", label="Y_pred vs. Residuals") 93 | 94 | dimension = self.__y_pred.shape[0] 95 | residual_mean = self.__residuals.mean() 96 | plt.plot(self.__y_pred, np.full(dimension, residual_mean), color="blue", label="Residual Mean") 97 | 98 | plt.title("Y_predict vs. Residuals") 99 | plt.xlabel("Y_predict") 100 | plt.ylabel("Residuals") 101 | plt.legend(loc="best") 102 | if self.x_lim != None: 103 | plt.xlim(self.x_lim) 104 | if self.y_lim != None: 105 | plt.ylim(self.y_lim) 106 | plt.show() 107 | 108 | def features_correlation(self, heatmap=None): 109 | print("*** Check for Correlation of Features ***") 110 | if heatmap != None: 111 | self.heatmap = heatmap 112 | 113 | df = pd.DataFrame(self.__x_train) 114 | corr = df.corr().round(4) 115 | print("--- Features Correlation Matrix ---") 116 | print(corr) 117 | if self.heatmap: 118 | # annot = annotation = True = put number inside matrix 119 | sns.heatmap(data=corr, annot=True) 120 | plt.show() 121 | 122 | corr_ary = corr.to_numpy() 123 | corr_bool = False 124 | for i in range(corr_ary.shape[0]): 125 | for j in range(corr_ary.shape[1]): 126 | if i != j: 127 | if corr_ary[i, j] >= 0.8: 128 | corr_bool = True 129 | print("Correlation Found at[{}, {}] = {}".format(i, j, corr_ary[i, j])) 130 | if not corr_bool: 131 | print("No Correlation (>=0.8) Found!") 132 | 133 | def check_all(self): 134 | self.sample_linearity() 135 | self.residuals_normality() 136 | self.residuals_independence() 137 | self.residuals_homoscedasticity() 138 | self.features_correlation() 139 | -------------------------------------------------------------------------------- /classification.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Tue Jul 30 16:15:31 2019 4 | 5 | @author: 俊男 6 | """ 7 | # In[] Naive Bayesian Classifier default with Gaussian Kernal 8 | from sklearn.naive_bayes import BernoulliNB, MultinomialNB, GaussianNB 9 | import pandas as pd 10 | 11 | class NaiveBayesClassifier: 12 | __classifier = None 13 | __y_columns = None 14 | 15 | def __init__(self, type="gaussian"): 16 | algorithm_dict = { 17 | "bernoulli" : BernoulliNB(), 18 | "multinomial" : MultinomialNB(), 19 | "gaussian" : GaussianNB() 20 | } 21 | self.__classifier = algorithm_dict[type] 22 | 23 | @property 24 | def classifier(self): 25 | return self.__classifier 26 | 27 | @classifier.setter 28 | def classifier(self, classifier): 29 | self.__classifier = classifier 30 | 31 | def fit(self, x_train, y_train): 32 | self.classifier.fit(x_train, y_train.values.ravel()) 33 | self.__y_columns = y_train.columns 34 | 35 | return self 36 | 37 | def predict(self, x_test): 38 | return pd.DataFrame(self.classifier.predict(x_test), index=x_test.index, columns=self.__y_columns) 39 | 40 | # In[] Support Vecor Machine (SVM) Classifier default with Gaussian Radial Basis Function (Gaussian RBF) 41 | from sklearn.svm import SVC 42 | import time 43 | 44 | class SVM: 45 | __classifier = None 46 | 47 | __penalty_C = None 48 | __kernel = None 49 | __degree = None 50 | __gamma = None 51 | __coef0 = None 52 | __y_columns = None 53 | 54 | def __init__(self, C=1.0, kernel="rbf", degree=3, gamma="scale", coef0=0.0, random_state=int(time.time())): 55 | self.__penalty_C = C 56 | self.__kernel = kernel 57 | self.__degree = degree 58 | self.__gamma = gamma 59 | self.__coef0 = coef0 60 | 61 | self.__classifier = SVC(C=self.__penalty_C, 62 | kernel=self.__kernel, 63 | degree=self.__degree, 64 | gamma=self.__gamma, 65 | coef0=self.__coef0, 66 | random_state=random_state) 67 | 68 | @property 69 | def classifier(self): 70 | return self.__classifier 71 | 72 | @classifier.setter 73 | def classifier(self, classifier): 74 | self.__classifier = classifier 75 | 76 | def fit(self, x_train, y_train): 77 | self.classifier.fit(x_train, y_train.values.ravel()) 78 | self.__y_columns = y_train.columns 79 | 80 | return self 81 | 82 | def predict(self, x_test): 83 | return pd.DataFrame(self.classifier.predict(x_test), index=x_test.index, columns=self.__y_columns) 84 | 85 | # In[] Decision Tree 86 | from sklearn.tree import DecisionTreeClassifier 87 | import time 88 | 89 | class DecisionTree: 90 | __classifier = None 91 | __criterion = None 92 | __y_columns = None 93 | 94 | def __init__(self, criterion="entropy", random_state=int(time.time())): 95 | self.__criterion = criterion 96 | self.__classifier = DecisionTreeClassifier(criterion=self.__criterion, random_state=random_state) 97 | 98 | @property 99 | def classifier(self): 100 | return self.__classifier 101 | 102 | @classifier.setter 103 | def classifier(self, classifier): 104 | self.__classifier = classifier 105 | 106 | def fit(self, x_train, y_train): 107 | self.classifier.fit(x_train, y_train) 108 | self.__y_columns = y_train.columns 109 | return self 110 | 111 | def predict(self, x_test): 112 | return pd.DataFrame(self.classifier.predict(x_test), index=x_test.index, columns=self.__y_columns) 113 | 114 | # In[] Random Forest 115 | from sklearn.ensemble import RandomForestClassifier 116 | import time 117 | 118 | class RandomForest: 119 | __classifier = None 120 | __n_estimators = None 121 | __criterion = None 122 | __y_columns = None 123 | 124 | def __init__(self, n_estimators=10, criterion="entropy"): 125 | self.__n_estimators = n_estimators 126 | self.__criterion = criterion 127 | self.__classifier = RandomForestClassifier(n_estimators=self.__n_estimators, criterion=self.__criterion, random_state=int(time.time())) 128 | 129 | @property 130 | def classifier(self): 131 | return self.__classifier 132 | 133 | @classifier.setter 134 | def classifier(self, classifier): 135 | self.__classifier = classifier 136 | 137 | @property 138 | def n_estimators(self): 139 | return self.__n_estimators 140 | 141 | def fit(self, x_train, y_train): 142 | self.classifier.fit(x_train, y_train.values.ravel()) 143 | self.__y_columns = y_train.columns 144 | return self 145 | 146 | def predict(self, x_test): 147 | return pd.DataFrame(self.classifier.predict(x_test), index=x_test.index, columns=self.__y_columns) 148 | -------------------------------------------------------------------------------- /performance.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Sat Jul 27 11:34:21 2019 4 | 5 | @author: 俊男 6 | """ 7 | 8 | # In[] Warning setting 9 | import warnings 10 | warnings.filterwarnings('ignore') # "error", "ignore", "always", "default", "module" or "once" 11 | 12 | # In[] Root of Mean Square Error (RMSE) 13 | from sklearn.metrics import mean_squared_error 14 | import numpy as np 15 | 16 | def rmse(y_real, y_pred): 17 | return np.sqrt(mean_squared_error(y_real, y_pred)) 18 | 19 | # In[] R2 (coefficient of determination) 20 | from sklearn.metrics import r2_score 21 | 22 | def r2(y_real, y_pred): 23 | return r2_score(y_real, y_pred) 24 | 25 | # In[] Classification Performance 26 | from sklearn.metrics import confusion_matrix 27 | from sklearn.metrics import accuracy_score 28 | from sklearn.metrics import precision_score 29 | from sklearn.metrics import recall_score 30 | from sklearn.metrics import fbeta_score 31 | 32 | class ClassificationPerformance: 33 | __y_real = None 34 | __y_pred = None 35 | 36 | def __init__(self, y_real, y_pred): 37 | self.__y_real = y_real 38 | self.__y_pred = y_pred 39 | 40 | def confusion_matrix(self): 41 | return confusion_matrix(self.__y_real, self.__y_pred) 42 | 43 | def accuracy(self): 44 | return accuracy_score(self.__y_real, self.__y_pred) 45 | 46 | def recall(self): 47 | return recall_score(self.__y_real, self.__y_pred, average="macro") 48 | 49 | def precision(self): 50 | return precision_score(self.__y_real, self.__y_pred, average="macro") 51 | 52 | def f_score(self, beta=1): 53 | return fbeta_score(self.__y_real, self.__y_pred, beta=beta, average="macro") 54 | 55 | # In[] K-Fold Cross Validation of Classification Performance 56 | from sklearn.model_selection import cross_val_score 57 | 58 | class KFoldClassificationPerformance: 59 | __k_fold = None 60 | __x_ary = None 61 | __y_ary = None 62 | __classifier = None 63 | __verbose = None 64 | 65 | def __init__(self, x_ary, y_ary, classifier, k_fold=10, verbose=False): 66 | self.__x_ary = x_ary 67 | self.__y_ary = y_ary 68 | self.k_fold = k_fold 69 | self.__classifier = classifier 70 | self.verbose = verbose 71 | 72 | @property 73 | def k_fold(self): 74 | return self.__k_fold 75 | 76 | @k_fold.setter 77 | def k_fold(self, k_fold): 78 | if k_fold >=2: 79 | self.__k_fold = k_fold 80 | else: 81 | self.__k_fold = 2 82 | 83 | @property 84 | def verbose(self): 85 | return self.__verbose 86 | 87 | @verbose.setter 88 | def verbose(self, verbose): 89 | if verbose: 90 | self.__verbose = 10 91 | else: 92 | self.__verbose = 0 93 | 94 | @property 95 | def classifier(self): 96 | return self.__classifier 97 | 98 | def accuracy(self): 99 | results = cross_val_score(estimator=self.classifier, X=self.__x_ary, y=self.__y_ary.values.ravel(), scoring="accuracy", cv=self.k_fold, verbose=self.verbose) 100 | return results.mean() 101 | 102 | def recall(self): 103 | def recall_scorer(estimator, X, y): 104 | return recall_score(y, estimator.predict(X), average="macro") 105 | 106 | results = cross_val_score(estimator=self.classifier, X=self.__x_ary, y=self.__y_ary.values.ravel(), scoring=recall_scorer, cv=self.k_fold, verbose=self.verbose) 107 | return results.mean() 108 | 109 | def precision(self): 110 | def precision_scorer(estimator, X, y): 111 | return precision_score(y, estimator.predict(X), average="macro") 112 | 113 | results = cross_val_score(estimator=self.classifier, X=self.__x_ary, y=self.__y_ary.values.ravel(), scoring=precision_scorer, cv=self.k_fold, verbose=self.verbose) 114 | return results.mean() 115 | 116 | def f_score(self): 117 | def f1_scorer(estimator, X, y): 118 | return fbeta_score(y, estimator.predict(X), beta=1, average="macro") 119 | 120 | results = cross_val_score(estimator=self.classifier, X=self.__x_ary, y=self.__y_ary.values.ravel(), scoring=f1_scorer, cv=self.k_fold, verbose=self.verbose) 121 | return results.mean() 122 | 123 | # In[] GridSearch for Searching the Best Hyper-parameters of a function 124 | from sklearn.model_selection import GridSearchCV 125 | 126 | class GridSearch: 127 | __validator = None 128 | __estimator = None 129 | __parameters = None 130 | __scorer = None 131 | __k_fold = None 132 | __best_score = None 133 | __best_parameters = None 134 | __best_estimator = None 135 | __verbose = None 136 | 137 | def __init__(self, estimator, parameters, scorer=None, k_fold=10, verbose=False): 138 | self.__estimator = estimator 139 | self.__parameters = parameters 140 | self.__scorer = scorer 141 | self.__k_fold = k_fold 142 | 143 | self.verbose = verbose 144 | self.__validator = GridSearchCV(estimator=self.__estimator, param_grid=self.__parameters, scoring=self.__scorer, cv=self.__k_fold, verbose=self.verbose) 145 | 146 | @property 147 | def verbose(self): 148 | return self.__verbose 149 | 150 | @verbose.setter 151 | def verbose(self, verbose): 152 | if verbose: 153 | self.__verbose = 10 154 | else: 155 | self.__verbose = 0 156 | 157 | @property 158 | def validator(self): 159 | return self.__validator 160 | 161 | @property 162 | def best_score(self): 163 | return self.__best_score 164 | 165 | @property 166 | def best_parameters(self): 167 | return self.__best_parameters 168 | 169 | @property 170 | def best_estimator(self): 171 | return self.__best_estimator 172 | 173 | def fit(self, x_ary, y_ary): 174 | self.validator.fit(x_ary, y_ary.values.ravel()) 175 | 176 | self.__best_parameters = self.validator.best_params_ 177 | self.__best_score = self.validator.best_score_ 178 | self.__best_estimator = self.validator.best_estimator_ 179 | -------------------------------------------------------------------------------- /ReleaseLog.txt: -------------------------------------------------------------------------------- 1 | [20230210-01] BUGFIX, NEW 2 | 3 | * [BUGFIX] preprocessor.py 4 | - 修正 feature_scaling() 函數,傳入 pandas.Series 而非 pandas.DataFrame 時,引發的錯誤訊息。原先沒有考慮到一維的 Series。目前改成一律用 pandas.DataFrame() 轉換函數,轉成 DataFrame 之後,再進行後續的處理步驟之方法解決。 5 | 6 | * [NEW] regression.py 7 | - 替 MultipleRegressor 增加一個屬性,叫做 .named_features。它可以用「欄位名稱」,傳回除了 "const" 以外的降維結果。如:['R&D Spend', 'Marketing Spend']。 8 | 9 | 10 | [20230205-01] MODIFY, NEW 11 | 12 | * [MODIFY] regression.py 13 | - 修正引入的多元線性迴歸函式庫。 14 | 本來: import statsmodels.regression.linear_model as sm 15 | 後來: import statsmodels.api as sm 16 | 17 | * [NEW] regression.py 18 | - 替 class MultipleRegressor 增加「自動增加常數項」的功能。包含: 19 | 1. 新增 add_constant(self, exog),全自動判斷是否已經加了常數項。 20 | 2. 在 backward_elimination(), fit(), predict() 一開頭,都先呼叫 add_constant(),確保有常數項。 21 | - 新增針對 X_train, X_test 自動切片功能。 22 | 1. 若有做過 backward_elimination(),則 __features 存在,先切片再擬合、預測。 23 | 2. 若沒做過 backward_elimination(),則 __features 不存在,代表不需降維。直接擬合、預測。 24 | 25 | 26 | [20210606-01] BUGFIX 27 | 28 | * [BUGFIX] criteria.py 29 | - 修正叫用 criteria.AssumptionChecker.features_correlation() 時,若 heatmap=True,用 Seaborn 畫出來的 Heapmap,會跟其它圖形重疊在一起的問題。這是因為用 sns.heatmap(data=corr, annot=True) 之後,沒有馬上使用 plt.show(),導致繪製好的熱區圖,一直停留在記憶體中。如果後續還有繪製其它圖形,就會疊加在 Seaborn 留在記憶體中的熱區圖上面。目前已經在 sns.heatmap(data=corr, annot=True) 後方,添加了一道 plt.show(),強迫 Seaborn 把繪製好的熱區圖(Heatmap),馬上從記憶體輸出到螢幕上。所以,此一現象已經不會再發生了。 30 | 31 | 32 | [20210603-01] BUGFIX 33 | 34 | * [BUGFIX] model_drawer.py 35 | - 修正呼叫 sample_model()、classify_result()、cluster_drawer() 時,如果 title= 裡面的文字並未用使用中文,也就是沒有指定 font= 參數、放任它使用預設值時,會出現「findfont: Font family ['sans-serif'] not found. Falling back to DejaVu Sans」這個警告訊息之問題。這是因為原先 font= 的預設值是 font="Arial Unicode MS"。如果程式師呼叫 sample_model()、classify_result()、cluster_drawer() 三函數時,沒有特意指定 font= 的值,放任它使用預設值,而使用人的電腦內,又沒有 "Arial Unicode MS" 這個字型時,就會發出「findfont: Font family ['sans-serif'] not found. Falling back to DejaVu Sans」這個警告訊息。目前已經將 font= 的預設值,改成 font="" 了。 36 | 37 | 38 | [20210526-01] BUGFIX 39 | 40 | * [BUGFIX] preprocessor.py 41 | - 修正呼叫 preprocessor.PCASelector.fit() 時,不論指定 verbose=True 或 verbose=False,出來的訊息都一樣之問題。除了修正一個 verbose=True 的邏輯錯誤外,也大量添加當 verbose=True 時,秀出來的訊息。這次 verbose=True 添加的訊息包括 (1) 秀出每個 PCA 元素,所涵蓋的資訊量 (2) 秀出挑選幾個 PCA 元素後,累加的資訊量會有多少。 42 | 43 | 44 | [20210519-01] MODIFY, BUGFIX 45 | 46 | * [MODIFY] preprocessor.py 47 | - 將 KBestSelector.fit() 裡面的 auto=False 參數移除。移除原因為該參數已經不再具備任何作用。早在 2019 年的版本,就已經使用 KBestSelector.__init__() 裡面的 best_k="auto" 取代之了。 48 | 49 | * [BUGFIX] preprocessor.py 50 | - 當 KBestSelector.__init__() 內的 best_k ≠ "auto" 的情況下,就算將 KBestSelector.fit() 裡面的 verbose=True,也會看不到 KBestSelector.fit() 逐步計算過程。這個問題是出自於程式邏輯考慮不周。原版所有 verbose=True 的機制,全部都內縮於 "auto" 之下。所以只有在 best_k="auto" 時,指定 verbose=True 才會有用。目前已經將整個 KBestSelector.fit() 裡面,與 verbose 有關的邏輯全部重新改寫,不會再出現這個現象了。 51 | 52 | * [BUGFIX] performance.py 53 | - 呼叫 performance.GridSearch() 建構函數時,會出現 "無效的 iid= 參數" 錯誤訊息。這是因為 performance.GridSearch() 建構函數裡面會呼叫 sklearn.model_selection.GridSearchCV()。原本呼叫 GridSearchCV() 時,需要一個 iid= 參數。後來在 sklearn 新版中,已經將 GridSearchCV() 裡面的 iid= 參數拿掉了。所以才會出現 "無效的 iid= 參數" 這個錯誤訊息。目前我已經將 performance.GridSearch() 建構函數裡面,GridSearchCV() 的 iid= 參數拿掉了。 54 | 55 | 56 | [20200803-01] NEW 57 | 58 | * [NEW] model_drawer.py 59 | - 新增 show_first_n_images() 函數。它可以讓你在做「卷積神經網路」時,秀出前 N 張圖形。藉以驗證圖形載入後,處於沒問題可用的狀態。 60 | 61 | * [NEW] neural_networks.py 62 | - 新增 create_seq_model() 函數。讓你用一個函數,就能做到神經網路序列模型中,繁複的隱藏層添加任務。 63 | 64 | 65 | [20200726-01] NEW 66 | * [NEW] model_drawer.py 67 | - 為了神經網路做完之後圖形繪製的方便,新增一個 epochs_metrics_plot() 函數。它可以繪製出「訓練集 vs. 驗證集」的效能差異,藉以看出是否過擬合。 68 | 69 | 70 | [20191012-01] MODIFY 71 | * [MODIFY] preprocessor.py, missing_data() 72 | - 加上一個條件判斷: if (type(dataset) is pd.DataFrame) and (sum(dataset.isnull().sum()) > 0)。用來判斷是否為 DataFrame,以及是否需要缺失資料補遺。 73 | - 使用 missing_cols = [i for i, j in enumerate(dataset.isnull().any()) if j],自動判斷缺失欄位。不必使用者告知缺失欄位是哪幾個。 74 | - 因為有自動判斷缺失欄位,所以就算沒有缺失欄位,也可以呼叫。並不會造成任何「無缺失」欄位的任何改變。 75 | 76 | 77 | [20190918-01] BUGFIX 78 | 79 | * [BUGFIX] regression.py Line# 35 80 | - 原本使用 import statsmodels.formula.api as sm 匯入的套件,現在要改成 import statsmodels.regression.linear_model as sm 這樣才能匯入。 81 | 82 | 83 | [20190826-01] BUBFIX & MODIFY & NEW 84 | 85 | * [BUGFIX] preprocessor.missing_data(ary, strategy="mean") 86 | - 原先版本還保留使用 NDArray 的樣子。目前已經修正成使用 DataFrame 的版本了。 87 | 88 | * [MODIFY] preprocessor.decomposition(dataset, x_columns, y_columns=[]) 89 | - 原本 y_columns 是個「必傳」的參數。因為「集群(Clustering)」問題,只有自變數,沒有應變數,因此修改成 y_columns=[]。 90 | - 當你不提供 y_columns 時,它會使用預設值 [],導致不會回傳任何應變數(集群問題沒有任何應變數)。 91 | 92 | * [NEW] clustering.KMeansCluster 93 | - 新增 KMeansCluster 類別,實作 K-Means 集群演算法。 94 | 95 | * [NEW] model_drawer.cluster_drawer(x, y, centroids, title="", font='Arial Unicode MS') 96 | - 可以用來將集群結果視覺化的函數。 97 | - x: DataFrame, 只能有兩個 Features。y: DataFrame, 集群預設結果。centroids: 各集群的中心點。 98 | 99 | * [NEW] preprocessor.combine(dataset, y_pred) 100 | - 可以將 y_pred 的答案,附加到 dataset 尾部 101 | - 適合用於集群分析取得答案後,黏到 dataset 的尾部。 102 | 103 | 104 | [20190817-01] BUGFIX & NEW 105 | 106 | * [BUGFIX] model_drawer 107 | - 該模組內有一個函數,叫做 tree_drawer(),需要 import pydotplus 後才能運作。 108 | - 而 pydotplus 是需要 pip install pydotplus 之後,才有辦法使用的。 109 | - 當使用者 from robert.model_drawer import ,且沒有安裝 pydotplus 時,系統會發出 ImportError 說:「無法引入 pydotplut」。 110 | - 加上下列機制,讓使用者沒有安裝 pydotplus,也可以引用 robert.model_drawer 裡 tree_drawer() 以外的其它函數。 111 | try: 112 | import pydotplus 113 | except ImportError: 114 | pass 115 | 116 | * [BUGFIX] preprocessor.feature_scaling(fit_ary, transform_arys=None) 117 | - 當 transform_arys 只有一個時,使用者容易寫成 pp.feature_scaling(fit_ary=X, transform_arys=X) 118 | - 但 transform_arys 程式內部就直接把它當成 tuple 了。所以使用者如上述方法叫用,會失敗。 119 | - 正確叫法應該是 pp.feature_scaling(fit_ary=X, transform_arys=(X,))。別忘了單一元素的 tuple 要寫成 (X,) 120 | - 為了讓使用者自由使用 Tuple 與單一元素。程式碼改成這樣: 121 | if type(transform_arys) is tuple: 122 | return (pd.DataFrame(scaler.transform(ary.astype("float64")), index=ary.index, columns=ary.columns) for ary in transform_arys) 123 | else: 124 | return pd.DataFrame(scaler.transform(transform_arys.astype("float64")), index=transform_arys.index, columns=transform_arys.columns) 125 | - 如此一來,使用者也可以用 pp.feature_scaling(fit_ary=X, transform_arys=X) 這種方法叫用了。 126 | 127 | * [BUGFIX] preprocessor.KBestSelector 128 | - 當有人這麼寫的時候: 129 | selector = KBestSelector(best_k=2) 130 | X = selector.fit(x_ary=X, y_ary=Y, auto=True, verbose=True, sort=True).transform(x_ary=X) 131 | - 會因為 auto=True,導致 best_k=2 失效。所以改成KBestSelector(best_k=??) best_k= "auto" | <整數> 的寫法 132 | if type(best_k) is int: 133 | self.__strategy = "fixed" 134 | self.best_k = best_k 135 | else: 136 | self.__strategy = "auto" 137 | self.best_k = 1 138 | - 而 KBestSelector.fit(x_ary=X, y_ary=Y, auto=True, verbose=True, sort=True) 中的 auto=True/False 目前保留但不作用。將在下一版移除。 139 | 140 | * [BUGFIX] performance.KFoldClassificationPerformance 141 | - 每次 K 折運算時,只要某一折內,不含特定應變數 Y 的某種答案,就會發出以下警告訊號: 142 | Warning: The least populated class in y has only 5 members, which is too few. 143 | UndefinedMetricWarning: F-score is ill-defined and being set to 0.0 in labels with no predicted samples 144 | - 加上這個選項,讓 Warning 不再出現。只有 Error 才出現: 145 | import warnings 146 | warnings.filterwarnings('ignore') 147 | 148 | * [NEW] preprocessor.PCASelector 149 | - 新增 PCASelector 類別,實作以 PCA 將特性(Features)降維 150 | 151 | 152 | 153 | 154 | [20190813-01] MODIFY & NEW 155 | 156 | * [MODIFY] preprocessor.label_encoder(ary, mapping=False) 157 | - 新增一個參數 mapping=False 158 | - 當 mapping=True 時,會傳回來兩個值 159 | (1) LabelEncode 過的 DataFrame 陣列 160 | (2) 對應字典。如 {0:"Yes", 1:"No"},就是把 Yes 編碼為 0,No 編碼為 "1" 161 | 162 | * [MODIFY] preprocessor.onehot_encoder(ary, columns=[], remove_trap=False) 163 | - 新增一個參數 remove_trap=False 164 | - 當 remove_trap=True 時,會自動移除 One Hot Encoder 後的一欄,以去除自變數共線性。 165 | - 會自動保持原來的欄位順序。不會因為執行 One Hot Encoder,而改變欄位順序。 166 | 167 | * [NEW] classification.DecisionTree 168 | - 新增 DecisionTree 類別,實作 Decision Tree。 169 | 170 | * [NEW] classification.RandomForest 171 | - 新增 RandomForest 類別,實作 Random Forest 172 | 173 | * [NEW] model_drawer.tree_drawer() 174 | - 新增 tree_drawer(),以繪製 Decision Tree 的分類結果。 -------------------------------------------------------------------------------- /model_drawer.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Mon Jul 15 11:52:25 2019 4 | 5 | @author: 俊男 6 | """ 7 | 8 | # In[] Import Area 9 | import numpy as np 10 | import matplotlib.pyplot as plt 11 | from matplotlib.colors import ListedColormap 12 | import pandas as pd 13 | 14 | # In[] sample_model(): Draw the model as line, and sample data as scatter 15 | # USAGE: model_drawer.sample_model(sample_data=(X_test, Y_test), model_data=(X_test, Y_pred)) 16 | 17 | def sample_model(sample_data=None, sample_color="red", model_data=None, model_color="blue", title="", xlabel="", ylabel="", font=""): 18 | # for showing Chinese characters 19 | if font != "": 20 | plt.rcParams['font.sans-serif']=[font] 21 | plt.rcParams['axes.unicode_minus'] = False 22 | 23 | # Draw for Sample Data with Scatter Chart 24 | if sample_data != None: 25 | plt.scatter(sample_data[0], sample_data[1], color=sample_color) 26 | 27 | # Draw for Model with line chart 28 | if model_data != None: 29 | plt.plot(model_data[0], model_data[1], color=model_color) 30 | 31 | # Draw for title, xlabel, ylabel 32 | if sample_data!=None or model_data!=None: 33 | plt.title(title) 34 | plt.xlabel(xlabel) 35 | plt.ylabel(ylabel) 36 | plt.show() 37 | 38 | # In[] classify_result(): Visualize the result of classification 39 | # X-axis, Y-asix: Feature 1 & Feature 2 of X (e.g. X-axis = Age, Y-axis = Salary) 40 | # Background Color: The classification of Y_pred (e.g. RED: Y=0, BLUE: Y=1...) 41 | # Dot: The samples 42 | # Dot Color: The classification of Y_real (e.g. RED: Y=0, BLUE: Y=1...) 43 | # USAGE: classifiy_result(x=X_train, y=Y_train, classifier=regressor.regressor, title="訓練集樣本點 vs. 模型", xlabel="年齡", ylabel="薪水") 44 | # NOTE1: Make sure you've done "Feature Scaling" before calling this function. Otherwise the background dots will be too many to out-of-memory. 45 | # NOTE2: This function can only take 2 features to draw. Make sure you selected "Best 2" features to train the classifier. 46 | 47 | def classify_result(x, y, classifier, fg_color=("orange", "blue"), bg_color=("red", "green"), title="", font=""): 48 | # Get the xlabel & ylabel first 49 | xlabel = x.columns[0] 50 | ylabel = x.columns[1] 51 | 52 | # Convert the color strings into hex codes 53 | # This is for compatibility with ListedColormap when matplotlib >= 3.8.0 54 | color_hex_codes = { 55 | 'red': '#FF0000', 56 | 'green': '#008000', 57 | 'blue': '#0000FF', 58 | 'yellow': '#FFFF00', 59 | 'cyan': '#00FFFF', 60 | 'magenta': '#FF00FF', 61 | 'black': '#000000', 62 | 'white': '#FFFFFF', 63 | 'orange': '#FFA500', 64 | 'purple': '#800080' 65 | } 66 | 67 | fg_color = [color_hex_codes[color] for color in fg_color] 68 | bg_color = [color_hex_codes[color] for color in bg_color] 69 | 70 | # Prepare each dot of background 71 | x = x.values 72 | y = y.values 73 | x_axis_range = np.arange(x[:, 0].min()-1, x[:, 0].max()+1, 0.01) 74 | y_axis_range = np.arange(x[:, 1].min()-1, x[:, 1].max()+1, 0.01) 75 | X_background, Y_background = np.meshgrid(x_axis_range, y_axis_range) 76 | 77 | # Limit the range of drawing 78 | plt.xlim(X_background.min(), X_background.max()) 79 | plt.ylim(Y_background.min(), Y_background.max()) 80 | 81 | # Draw the dots of background (as the predicting result) 82 | 83 | # To predict each dots at X_background x Y_background: 84 | # 1. X_background.ravel() as Row0, Y_background.ravel() as Row1 85 | # 2. Transpose Row0, Row1, as Column0, Column1 86 | # 3. Change it as Dataframe before passing it to .predict() 87 | # 4. After predict, use .values make DataFrame as NDArray 88 | # 5. Change 1D back to 2D as dimention X_background.shape 89 | Target_predict = pd.DataFrame(classifier.predict(pd.DataFrame(np.array([X_background.ravel(), Y_background.ravel()]).T))).values.reshape(X_background.shape) 90 | plt.contourf(X_background, Y_background, Target_predict, alpha=0.75, cmap=ListedColormap(bg_color)) 91 | 92 | # Draw the sample data in dots 93 | # Iterate all types of Targets (e.g. Y_real = 0, Y_real = 1, ...) 94 | for y_real_index, y_real in enumerate(np.unique(y)): 95 | row_selector = y.reshape(x.shape[0]) # y.ndim =2, we need 1D array to select rows of X 96 | plt.scatter(x[row_selector == y_real, 0], x[row_selector == y_real, 1], c=[ListedColormap(fg_color)(y_real_index)], label=y_real) 97 | 98 | # Set the Title & Label 99 | # for showing Chinese characters 100 | if font != "": 101 | plt.rcParams['font.sans-serif']=[font] 102 | plt.rcParams['axes.unicode_minus'] = False 103 | 104 | plt.title(title) 105 | plt.xlabel(xlabel) 106 | plt.ylabel(ylabel) 107 | plt.legend(loc="best") 108 | plt.show() 109 | 110 | # In[] tree_drawer(): Visualize the result of decision tree 111 | # USAGE: 112 | # import robert.model_drawer as md 113 | # from IPython.display import Image 114 | # cls_name = [Y_mapping[key] for key in sorted(Y_mapping.keys())] 115 | # graph = md.tree_drawer(classifier=classifier.classifier, feature_names=X_test.columns, target_names=cls_name) 116 | # Image(graph.create_png()) 117 | # Package Installation: 118 | # (1) Install graphviz first: conda install graphviz + pip install graphviz 119 | # (2) Install pydotplus: conda install pydotplus 120 | # (3) Install GraphViz Executable: Go to https://graphviz.gitlab.io/download/ to download 121 | # (4) Restart Spyder 122 | 123 | from sklearn import tree 124 | import os 125 | 126 | try: 127 | import pydotplus 128 | except ImportError: 129 | pass 130 | 131 | def tree_drawer(classifier, feature_names=None, target_names=None, graphviz_bin='C:/Program Files (x86)/Graphviz2.38/bin/'): 132 | os.environ["PATH"] += os.pathsep + graphviz_bin 133 | dot_data = tree.export_graphviz(classifier, filled=True, feature_names=feature_names, class_names=target_names, rounded=True, special_characters=True) 134 | return pydotplus.graph_from_dot_data(dot_data) 135 | 136 | 137 | # In[] cluster_drawer() 138 | import matplotlib.cm as cm 139 | 140 | # Shut off the warning messages from matplotlib 141 | # Reference: https://is.gd/Iq1WGw 142 | from matplotlib.axes._axes import _log as matplotlib_axes_logger 143 | matplotlib_axes_logger.setLevel('ERROR') 144 | 145 | def cluster_drawer(x, y, centroids, title="", font=""): 146 | # Check for x has only two columns 147 | if x.shape[1] != 2: 148 | print("ERROR: x must have only two features to draw!!") 149 | return None 150 | 151 | # Change y from DataFrame to NDArray 152 | y_ndarray = y.values.ravel() 153 | 154 | # Get how many classes in y 155 | y_unique = np.unique(y_ndarray) 156 | 157 | # Iterate all classes in y 158 | colors = cm.rainbow(np.linspace(0, 1, len(y_unique))) 159 | for val, col in zip(y_unique, colors): 160 | plt.scatter(x.iloc[y_ndarray==val, 0], x.iloc[y_ndarray==val, 1], s=50, c=col, label="Cluster {}".format(val)) 161 | 162 | # Draw Centroids 163 | plt.scatter(centroids[:, 0], centroids[:, 1], s=200, c="black", marker="^", label="Centroids") 164 | 165 | # Labels & Legends 166 | # for showing Chinese characters 167 | if font != "": 168 | plt.rcParams['font.sans-serif']=[font] 169 | plt.rcParams['axes.unicode_minus'] = False 170 | 171 | plt.title(title) 172 | plt.xlabel(x.columns[0]) 173 | plt.ylabel(x.columns[1]) 174 | plt.legend(loc="best") 175 | plt.show() 176 | 177 | 178 | # In[] epochs_metrics_plot(): Draw the line plots of metrics for each epoch during Neural Net training 179 | def epochs_metrics_plot(history_dict, keys=(), title=None, xyLabel=[], ylim=(), size=()): 180 | lineType = ("-", "--", ".", ":") 181 | if len(ylim)==2: 182 | plt.ylim(*ylim) 183 | if len(size)==2: 184 | plt.gcf().set_size_inches(*size) 185 | epochs = range(1, len(history_dict[keys[0]])+1) 186 | for i in range(len(keys)): 187 | plt.plot(epochs, history_dict[keys[i]], lineType[i]) 188 | if title: 189 | plt.title(title) 190 | if len(xyLabel)==2: 191 | plt.xlabel(xyLabel[0]) 192 | plt.ylabel(xyLabel[1]) 193 | plt.legend(keys, loc="best") 194 | plt.show() 195 | 196 | 197 | # In[] show_first_n_images(): Show the first N images of dataset. 198 | def show_first_n_images(x_ary, y_real=[], y_pred=[], first_n=5, font_size=18, color_scheme="gray"): 199 | # Get Current Figure (GCF) & Set Height 15 inches, Width 4 inches 200 | plt.gcf().set_size_inches(15, 4) 201 | 202 | # Convert y_pred as NumPy NDArray 203 | y_pred = np.array(y_pred) 204 | 205 | # Iterate the first N images 206 | for i in range(first_n): 207 | # each row has first_n sub-images 208 | ax = plt.subplot(1, first_n, i+1) 209 | 210 | # "gray": black background, "binary": white background 211 | ax.imshow(x_ary[i], cmap=color_scheme) 212 | 213 | # set sub-image title 214 | if y_pred.size == 0: 215 | img_title = "real = {}".format(y_real[i]) 216 | else: 217 | img_title = "real = {}\npred = {}".format(y_real[i], y_pred[i]) 218 | ax.set_title(img_title, fontsize=font_size) 219 | 220 | # Make X-axis, Y-axis without ticks 221 | ax.set_xticks([]) 222 | ax.set_yticks([]) 223 | 224 | # Show all images 225 | plt.show() -------------------------------------------------------------------------------- /pytorch.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn as nn 3 | import torch.optim as optim 4 | import torch.nn.init as init 5 | from torch.utils.data import DataLoader, TensorDataset, random_split 6 | 7 | 8 | class Sequential(nn.Module): 9 | def __init__(self): 10 | super(Sequential, self).__init__() 11 | self.layers = nn.ModuleList() 12 | 13 | def add(self, layer, kernel_initializer=None, activation=None): 14 | # Define Python dictionary for weight initializers------------- 15 | initializer_dict = { 16 | "random_uniform": init.uniform_, 17 | "random_normal": init.normal_, 18 | "glorot_uniform": init.xavier_uniform_, 19 | "glorot_normal": init.xavier_normal_, 20 | "he_uniform": init.kaiming_uniform_, 21 | "he_normal": init.kaiming_normal_ 22 | } 23 | 24 | # Check the parameter kernel_initializer 25 | if isinstance(kernel_initializer, str): 26 | kernel_initializer = initializer_dict.get(kernel_initializer, None) 27 | if kernel_initializer is None: 28 | raise ValueError(f"Initializer Error: Not support string {kernel_initializer}, 'None' applied.") 29 | 30 | if kernel_initializer is not None and hasattr(layer, 'weight'): 31 | kernel_initializer(layer.weight) 32 | 33 | self.layers.append(layer) 34 | 35 | # Define Python dictionary for activation function------------- 36 | activation_dict = { 37 | "relu": nn.ReLU(), 38 | "leaky_relu": nn.LeakyReLU(), 39 | "sigmoid": nn.Sigmoid(), 40 | "softmax": nn.Softmax(dim=-1), # Note: Softmax required assigning dim 41 | "tanh": nn.Tanh(), 42 | "linear": None # No activation function required for linear 43 | } 44 | 45 | # Check the parameter activation 46 | if isinstance(activation, str): 47 | activation = activation_dict.get(activation, None) 48 | if activation is None: 49 | raise ValueError(f"Activation Error: Not support string {activation}, 'None' applied.") 50 | 51 | if activation is not None: 52 | self.layers.append(activation) 53 | 54 | def forward(self, x): 55 | for layer in self.layers: 56 | x = layer(x) 57 | return x 58 | 59 | def compile(self, optimizer="adam", loss="categorical_crossentropy"): 60 | # Define Python dictionary for loss functions------------- 61 | loss_dict = { 62 | "mse": nn.MSELoss(), 63 | "binary_crossentropy": nn.BCELoss(), 64 | "categorical_crossentropy": nn.CrossEntropyLoss() 65 | } 66 | 67 | # Check the parameter loss 68 | if isinstance(loss, str): 69 | self.criterion = loss_dict.get(loss, None) 70 | if loss is None: 71 | raise ValueError(f"Loss Error: Not support string {loss}, 'None' applied.") 72 | else: 73 | self.criterion = loss 74 | 75 | # Define Python dictionary for optimizers------------- 76 | lr = 0.0001 77 | optimizer_dict = { 78 | "sgd": optim.SGD(self.parameters(), lr=lr), 79 | "adagrad": optim.Adagrad(self.parameters(), lr=lr), 80 | "adadelta": optim.Adadelta(self.parameters(), lr=lr), 81 | "rmsprop": optim.RMSprop(self.parameters(), lr=lr), 82 | "adam": optim.Adam(self.parameters(), lr=lr), 83 | "adamax": optim.Adamax(self.parameters(), lr=lr), 84 | "nadam": optim.NAdam(self.parameters(), lr=lr) 85 | } 86 | 87 | # Check the parameter optimizer 88 | if isinstance(optimizer, str): 89 | self.optimizer = optimizer_dict.get(optimizer, None) 90 | if optimizer is None: 91 | raise ValueError(f"Optimizer Error: Not support string {optimizer}, 'None' applied.") 92 | else: 93 | self.optimizer = optimizer 94 | 95 | def summary(self): 96 | print(self) 97 | 98 | def fit(self, x=None, y=None, validation_split=0.0, batch_size=None, epochs=1, shuffle=True): 99 | # Split the dataset into training and validation sets 100 | dataset_size = len(x) 101 | val_size = int(dataset_size * validation_split) 102 | train_size = dataset_size - val_size 103 | train_dataset, val_dataset = random_split(TensorDataset(x, y), [train_size, val_size]) 104 | 105 | train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=shuffle) 106 | val_loader = DataLoader(val_dataset, batch_size=batch_size, shuffle=False) 107 | 108 | # Start the training loop 109 | for epoch in range(epochs): 110 | # Change the model to training mode 111 | self.train() 112 | # Save the metrics for the training set 113 | train_loss, train_correct, train_total = 0.0, 0, 0 114 | for X_batch, Y_batch in train_loader: 115 | # Clear the gradients for this batch 116 | self.optimizer.zero_grad() 117 | 118 | # Compute the Y_pred for this batch 119 | Y_pred = self(X_batch) 120 | # Calculate the loss for this batch 121 | loss = self.criterion(Y_pred, Y_batch.squeeze()) 122 | # Find the gradients for the loss 123 | loss.backward() 124 | # Update the weights using the optimizer 125 | self.optimizer.step() 126 | 127 | # Calculate the loss for this batch 128 | train_loss += loss.item() * X_batch.size(0) 129 | # Find the maximum probability to get the predicted class 130 | _, predicted = torch.max(Y_pred.data, 1) 131 | # Add the total number of this batch 132 | train_total += Y_batch.size(0) 133 | # Add the number of correct predictions 134 | # Note: .item() is used to get the value of the tensor 135 | train_correct += (predicted == Y_batch).sum().item() 136 | 137 | # Change the model to evaluation mode 138 | self.eval() 139 | # Save the metrics for the validation set 140 | val_loss, val_correct, val_total = 0.0, 0, 0 141 | # Close the autograd for validation 142 | with torch.no_grad(): 143 | for X_batch, Y_batch in val_loader: 144 | # Compute the Y_pred for this batch 145 | Y_pred = self(X_batch) 146 | # Calculate the loss for this batch 147 | loss = self.criterion(Y_pred, Y_batch) 148 | 149 | # Calculate the metrics for this batch 150 | val_loss += loss.item() * X_batch.size(0) 151 | _, predicted = torch.max(Y_pred.data, 1) 152 | val_total += Y_batch.size(0) 153 | val_correct += (predicted == Y_batch).sum().item() 154 | 155 | # Calculate the average loss and accuracy for this epoch 156 | train_loss /= train_total 157 | train_acc = train_correct / train_total 158 | val_loss /= val_total 159 | val_acc = val_correct / val_total 160 | 161 | # Print the metrics for this epoch 162 | print(f"Epoch {epoch + 1}/{epochs} - loss: {train_loss:.4f} - acc: {train_acc:.4f} - val_loss: {val_loss:.4f} - val_acc: {val_acc:.4f}") 163 | 164 | def predict(self, x, batch_size=None): 165 | # Set the model to evaluation mode 166 | self.eval() 167 | predictions = [] 168 | 169 | # Create a DataLoader if a batch_size is provided 170 | if batch_size is not None: 171 | dataloader = DataLoader(x, batch_size=batch_size) 172 | else: 173 | dataloader = DataLoader(x, batch_size=len(x)) 174 | 175 | # No need to track gradients for prediction 176 | with torch.no_grad(): 177 | for inputs in dataloader: 178 | # Get the predicted classes 179 | outputs = self(inputs) 180 | _, predicted = torch.max(outputs.data, 1) 181 | 182 | # Append predictions to list 183 | predictions.append(predicted) 184 | 185 | # Concatenate all tensors in the list into a single tensor 186 | return torch.cat(predictions) 187 | 188 | def evaluate(self, x=None, y=None, batch_size=None): 189 | # Set the model to evaluation mode 190 | self.eval() 191 | test_loss, test_correct, test_total = 0.0, 0, 0 192 | 193 | # Create a DataLoader if a batch_size is provided 194 | if batch_size is not None: 195 | dataloader = DataLoader(TensorDataset(x, y), batch_size=batch_size, shuffle=False) 196 | else: 197 | dataloader = DataLoader(TensorDataset(x, y), batch_size=len(x), shuffle=False) 198 | 199 | # No need to track gradients for evaluation 200 | with torch.no_grad(): 201 | for X_batch, Y_batch in dataloader: 202 | # Compute the Y_pred for this batch 203 | Y_pred = self(X_batch) 204 | # Calculate the loss for this batch 205 | loss = self.criterion(Y_pred, Y_batch.squeeze()) 206 | 207 | # Calculate the metrics for this batch 208 | test_loss += loss.item() * X_batch.size(0) 209 | _, predicted = torch.max(Y_pred.data, 1) 210 | test_total += Y_batch.size(0) 211 | test_correct += (predicted == Y_batch).sum().item() 212 | 213 | # Calculate the average loss and accuracy for the testing dataset 214 | test_loss /= test_total 215 | test_acc = test_correct / test_total 216 | 217 | return test_loss, test_acc 218 | -------------------------------------------------------------------------------- /regression.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Mon Jul 15 15:16:22 2019 4 | 5 | @author: 俊男 6 | """ 7 | 8 | # In[] Define the class for Simple Regressor 9 | from sklearn.linear_model import LinearRegression 10 | import pandas as pd 11 | 12 | class SimpleRegressor: 13 | __regressor = None 14 | __y_columns = None 15 | 16 | def __init__(self): 17 | self.__regressor = LinearRegression() 18 | 19 | @property 20 | def regressor(self): 21 | return self.__regressor 22 | 23 | def fit(self, x_train, y_train): 24 | self.__regressor.fit(x_train, y_train) 25 | self.__y_columns = y_train.columns 26 | return self 27 | 28 | def predict(self, x_test): 29 | return pd.DataFrame(self.__regressor.predict(x_test), index=x_test.index, columns=self.__y_columns) 30 | 31 | def r_score(self, x_test, y_test): 32 | return self.__regressor.score(x_test, y_test) 33 | 34 | # In[] Define the class for Multiple Linear Regressor 35 | import statsmodels.api as sm 36 | import copy 37 | 38 | class MultipleRegressor: 39 | 40 | def __init__(self) : 41 | self.__regressor = None 42 | self.__features = None 43 | self.__named_features = None 44 | 45 | @property 46 | def regressor(self): 47 | return self.__regressor 48 | 49 | @property 50 | def named_features(self): 51 | return self.__named_features 52 | 53 | def add_constant(self, exog): 54 | # This function only support DataFrame 55 | if isinstance(exog, pd.DataFrame): 56 | # Check if the column 'const' has been added 57 | if not ('const' in exog): 58 | exog = sm.add_constant(exog) 59 | return exog 60 | else: 61 | print("Error: HappyML only supports pandas.DataFrame") 62 | raise TypeError() 63 | 64 | def fit(self, x_train, y_train): 65 | # Make sure there is a const column before fitting 66 | x_train = self.add_constant(x_train) 67 | 68 | # If there is a dimension reduction result, use it 69 | if self.__features is not None: 70 | x_train = x_train.iloc[:, self.__features] 71 | 72 | self.__regressor = sm.OLS(exog=x_train.astype("float"), endog=y_train.astype("float")).fit() 73 | return self 74 | 75 | def predict(self, x_test): 76 | # Make sure there is a const column before predicting 77 | x_test = self.add_constant(x_test) 78 | 79 | # If there is a dimension reduction result, use it 80 | if self.__features is not None: 81 | x_test = x_test.iloc[:, self.__features] 82 | 83 | return self.__regressor.predict(exog=x_test) 84 | 85 | def backward_elimination(self, x_train, y_train, significance=0.05, verbose=False): 86 | # Make sure there is a const column before reduction 87 | x_train = self.add_constant(x_train) 88 | 89 | # Initialize variables 90 | final_features = [i for i in range(x_train.shape[1])] 91 | p_values = [1.0 for i in range(x_train.shape[1])] 92 | this_features = copy.copy(final_features) 93 | prev_adj_rsquared = float("-inf") 94 | this_adj_rsquared = 0 95 | 96 | while(True): 97 | # Show final features first (if verbose) 98 | if verbose: 99 | feature_names = [x_train.columns[pos] for pos in final_features] 100 | print("CUR: {} Adj-RSquared={:.4f}".format(dict(zip(feature_names, ["{:.4f}".format(i) for i in p_values])), prev_adj_rsquared)) 101 | 102 | # Load the current chosen columns 103 | x_opt = x_train.iloc[:, this_features] 104 | 105 | # Fit the model with chosen columns 106 | self.fit(x_train=x_opt, y_train=y_train) 107 | this_adj_rsquared = self.__regressor.rsquared_adj 108 | p_values = self.__regressor.pvalues.tolist() 109 | 110 | # Show trial features (if verbose) 111 | if verbose: 112 | feature_names = [x_train.columns[pos] for pos in this_features] 113 | print("TRY: {} Adj-RSquared={:.4f}".format(dict(zip(feature_names, ["{:.4f}".format(i) for i in p_values])), this_adj_rsquared)) 114 | 115 | # If Adjust R-Squared reduced, stop the procedure 116 | if this_adj_rsquared < prev_adj_rsquared: 117 | if verbose: print("!!! STOP (Adj RSquared getting lower)\n") 118 | break 119 | else: 120 | final_features = this_features 121 | 122 | # Prepare for next round, get the maximum p-value and compare to significance 123 | this_features = copy.copy(final_features) 124 | max_pvalue = max(p_values) 125 | if max_pvalue > significance: 126 | max_pvalue_index = p_values.index(max_pvalue) 127 | del this_features[max_pvalue_index] 128 | prev_adj_rsquared = this_adj_rsquared 129 | if verbose: print(">>> GO NEXT (Higher Adj RSquared & has p-value>{})\n".format(significance)) 130 | else: 131 | if verbose: print("!!! STOP (No more p-value>{})\n".format(significance)) 132 | break 133 | 134 | if verbose: 135 | feature_names = [x_train.columns[pos] for pos in final_features] 136 | print("*** FINAL FEATURES: {}".format(feature_names)) 137 | 138 | self.__features = final_features 139 | self.__named_features = [x_train.columns[pos] for pos in final_features if x_train.columns[pos] != "const"] 140 | return final_features 141 | 142 | def r_score(self): 143 | return self.__regressor.rsquared_adj 144 | 145 | # In[] Define the Class for Polynomial Regression 146 | from sklearn.preprocessing import PolynomialFeatures 147 | from sklearn.metrics import mean_squared_error 148 | import numpy as np 149 | 150 | class PolynomialRegressor: 151 | __degree = 1 152 | __regressor = None 153 | __poly_regressor = None 154 | __X_poly = None 155 | 156 | def __init__(self): 157 | pass 158 | 159 | @property 160 | def degree(self): 161 | return self.__degree 162 | 163 | @degree.setter 164 | def degree(self, degree): 165 | if degree > 0: 166 | self.__degree = degree 167 | else: 168 | self.__degree = 1 169 | 170 | @property 171 | def X_poly(self): 172 | return self.__X_poly 173 | 174 | @property 175 | def regressor(self): 176 | return self.__regressor 177 | 178 | @property 179 | def poly_regressor(self): 180 | return self.__poly_regressor 181 | 182 | def best_degree(self, x_train, y_train, x_test, y_test, max_degree=10, verbose=False): 183 | the_best = [] 184 | best_deg, min_rmse = 0, float("inf") 185 | 186 | # Calculate the RMSE of each degree 187 | for deg in range(1, max_degree+1): 188 | self.degree = deg 189 | y_pred = self.fit(x_train, y_train).predict(x_test=x_test) 190 | this_rmse = np.sqrt(mean_squared_error(y_test, y_pred)) 191 | 192 | if this_rmse < min_rmse: 193 | best_deg = deg 194 | min_rmse = this_rmse 195 | 196 | the_best.append(best_deg) 197 | 198 | if verbose: 199 | print("Degree {}: RMSE={:.4f} (BEST DEG={}, RMSE={:.4f})".format(deg, this_rmse, best_deg, min_rmse)) 200 | 201 | # Get the best degree 202 | keys_degree, values_freq = np.unique(the_best, return_counts=True) 203 | degree_freq_dict = dict(zip(keys_degree, values_freq)) 204 | freq_degree_dict = {} 205 | for k, v in degree_freq_dict.items(): 206 | freq_degree_dict[v] = freq_degree_dict.get(v, []) 207 | freq_degree_dict[v].append(k) 208 | max_freq = max(freq_degree_dict) 209 | best_deg = max(freq_degree_dict[max_freq]) 210 | 211 | if verbose: 212 | print("Frequency vs. Degree dictionary:", freq_degree_dict) 213 | print("The Best Degree: {} Frequency: {}".format(best_deg, max_freq)) 214 | 215 | self.degree = best_deg 216 | return self.degree 217 | 218 | def fit(self, x_train, y_train): 219 | self.__poly_regressor = PolynomialFeatures(self.degree) 220 | self.__X_poly = pd.DataFrame(self.__poly_regressor.fit_transform(x_train)) 221 | self.__regressor = SimpleRegressor() 222 | self.__regressor.fit(self.X_poly, y_train) 223 | 224 | return self 225 | 226 | def predict(self, x_test): 227 | x_test = pd.DataFrame(self.__poly_regressor.fit_transform(x_test), index=x_test.index) 228 | return self.__regressor.predict(x_test=x_test) 229 | 230 | # In[] Define the Class for Logistic Regression 231 | from sklearn.linear_model import LogisticRegression 232 | import time 233 | 234 | class LogisticRegressor: 235 | __regressor = None 236 | __solver = "lbfgs" 237 | __y_columns = None 238 | 239 | def __init__(self, solver="lbfgs"): 240 | if solver not in ("liblinear", "lbfgs", "sag", "saga", "newton-cg"): 241 | self.__solver = "lbfgs" 242 | self.__regressor = LogisticRegression(solver=self.solver, random_state=int(time.time())) 243 | 244 | @property 245 | def regressor(self): 246 | return self.__regressor 247 | 248 | @property 249 | def solver(self): 250 | return self.__solver 251 | 252 | def fit(self, x_train, y_train): 253 | self.__y_columns = y_train.columns 254 | if y_train.ndim > 1: 255 | y_train = y_train.values.ravel() 256 | 257 | self.regressor.fit(x_train, y_train) 258 | return self 259 | 260 | def predict(self, x_test): 261 | return pd.DataFrame(self.regressor.predict(x_test), index=x_test.index, columns=self.__y_columns) 262 | -------------------------------------------------------------------------------- /preprocessor.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Mon Jul 15 10:04:02 2019 4 | 5 | @author: 俊男 6 | """ 7 | 8 | # In[] Import Area 9 | import numpy as np 10 | import pandas as pd 11 | 12 | # In[] Loading Dataset 13 | # USAGE: dataset = preprocessor.dataset("MyCSVFile.csv") 14 | 15 | def dataset(file=""): 16 | if file != "": 17 | dataset = pd.read_csv(file) 18 | else: 19 | dataset = None 20 | 21 | return dataset 22 | 23 | # In[] Decomposite Dataset into Independent Variables & Dependent Variables 24 | # USAGE: X, Y = preprocessor.decomposition(dataset, [0, 1, 2, 3], [4]) 25 | 26 | def decomposition(dataset, x_columns, y_columns=[]): 27 | X = dataset.iloc[:, x_columns] 28 | Y = dataset.iloc[:, y_columns] 29 | 30 | if len(y_columns) > 0: 31 | return X, Y 32 | else: 33 | return X 34 | 35 | # In[] Processing Missing Data 36 | # USAGE: X[:, 1:3] = preprocessor.missing_data(X[:, 1:3], strategy="mean") 37 | # strategy= "mean" | "median", | "most_frequent" 38 | 39 | from sklearn.impute import SimpleImputer 40 | 41 | def missing_data(dataset, strategy="mean"): 42 | if strategy not in ("mean", "median", "most_frequent"): 43 | strategy = "mean" 44 | 45 | if (type(dataset) is pd.DataFrame) and (sum(dataset.isnull().sum()) > 0): 46 | ary = dataset.values 47 | missing_cols = [i for i, j in enumerate(dataset.isnull().any()) if j] 48 | imputer = SimpleImputer(missing_values=np.nan, strategy=strategy) 49 | imputer = imputer.fit(ary[:, missing_cols]) 50 | ary[:, missing_cols] = imputer.transform(ary[:, missing_cols]) 51 | return pd.DataFrame(ary, index=dataset.index, columns=dataset.columns) 52 | else: 53 | return dataset 54 | 55 | 56 | # In[] Categorical Data Pre-processing 57 | 58 | # Label Encoder 59 | # USAGE: Y = preprocessor.label_encoder(Y, dtype="float64") 60 | from sklearn.preprocessing import LabelEncoder 61 | 62 | def label_encoder(ary, mapping=False): 63 | encoder = LabelEncoder() 64 | columns = ary.columns 65 | index = ary.index 66 | encoder.fit(ary.values.ravel()) 67 | mapper = {k:v for k, v in enumerate(list(encoder.classes_))} 68 | encoded_ary = pd.DataFrame(encoder.transform(ary.values.ravel()), index=index, columns=columns) 69 | 70 | if mapping: 71 | return encoded_ary, mapper 72 | else: 73 | return encoded_ary 74 | 75 | # One Hot Encoder 76 | # USAGE: X = preprocessor.onehot_encoder(X, [1, 3]) 77 | def onehot_encoder(ary, columns=[], remove_trap=False): 78 | df_results = pd.DataFrame() 79 | 80 | # Iterate each column in DataFrame ary 81 | for i in range(ary.shape[1]): 82 | # if this column (i) is dummy column 83 | if i in columns: 84 | base_name = ary.columns[i] 85 | this_column = pd.get_dummies(ary.iloc[:, i]) 86 | this_column = this_column.rename(columns={n:"{}_{}".format(base_name, n) for n in this_column.columns}) 87 | # Remove Dummy Variable Trap if needed 88 | if remove_trap: 89 | this_column = this_column.drop(this_column.columns[0], axis=1) 90 | # else this column is normal column 91 | else: 92 | this_column = ary.iloc[:, i] 93 | # Append this column to the Result DataFrame 94 | df_results = pd.concat([df_results, this_column], axis=1) 95 | 96 | return df_results 97 | 98 | # In[] Spliting Training Set vs. Testing Set 99 | # USAGE: X_train, X_test, Y_train, Y_test = preprocessor.split_train_test(X, Y, train_size=0.8) 100 | 101 | from sklearn.model_selection import train_test_split 102 | import time 103 | 104 | def split_train_test(x_ary, y_ary, train_size=0.75, random_state=int(time.time())): 105 | return train_test_split(x_ary, y_ary, test_size=(1-train_size), random_state=random_state) 106 | 107 | # In[] Feature Scaling 108 | # USAGE: 109 | # if transform_arys == None: 110 | # return the fitted Scaler for future use 111 | # e.g. scaler = preprocessor.feature_scaling(fit_ary=X_train) 112 | # if transform_arys != None: 113 | # return a Tuple for scaled dataset 114 | # e.g. X_train, X_test = preprocessor.feature_scaling(fit_ary=X_train, transform_arys=(X_train, X_test)) 115 | 116 | from sklearn.preprocessing import StandardScaler 117 | 118 | def feature_scaling(fit_ary, transform_arys=None): 119 | scaler = StandardScaler() 120 | scaler.fit(fit_ary.astype("float64")) 121 | 122 | if type(transform_arys) is tuple: 123 | result_list = list() 124 | for ary in transform_arys: 125 | ary = pd.DataFrame(ary) 126 | result_list += [pd.DataFrame(scaler.transform(ary.astype("float64")), index=ary.index, columns=ary.columns)] 127 | return result_list 128 | else: 129 | transform_arys = pd.DataFrame(transform_arys) 130 | return pd.DataFrame(scaler.transform(transform_arys.astype("float64")), index=transform_arys.index, columns=transform_arys.columns) 131 | 132 | # In[] Remove Columns 133 | # USAGE: X = preprocessor.remove_columns(X, [0]) 134 | 135 | def remove_columns(ary, columns=[]): 136 | return ary.drop(ary.columns[columns], axis=1) 137 | 138 | # In[] Add 1 column for constant 139 | import statsmodels.tools.tools as smtools 140 | 141 | def add_constant(ary): 142 | return smtools.add_constant(ary) 143 | 144 | # In[] Join two DataFrame (Left join) 145 | 146 | def combine(dataset, y_pred): 147 | return dataset.join(y_pred) 148 | 149 | # In[] Feature Selection: SelectKBest 150 | # SelectKBest requires Y, only good for Supervised Learning 151 | 152 | from sklearn.feature_selection import SelectKBest 153 | from sklearn.feature_selection import chi2 154 | 155 | class KBestSelector: 156 | __selector = None 157 | __significance = None 158 | __best_k = None 159 | __strategy = None 160 | 161 | def __init__(self, significance=0.05, best_k="auto"): 162 | self.significance = significance 163 | 164 | if type(best_k) is int: 165 | self.__strategy = "fixed" 166 | self.best_k = best_k 167 | else: 168 | self.__strategy = "auto" 169 | self.best_k = 1 170 | 171 | self.__selector = SelectKBest(score_func=chi2, k=self.best_k) 172 | 173 | @property 174 | def selector(self): 175 | return self.__selector 176 | 177 | @property 178 | def significance(self): 179 | return self.__significance 180 | 181 | @significance.setter 182 | def significance(self, significance): 183 | if significance > 0: 184 | self.__significance = significance 185 | else: 186 | self.__significance = 0.05 187 | 188 | @property 189 | def best_k(self): 190 | return self.__best_k 191 | 192 | @best_k.setter 193 | def best_k(self, best_k): 194 | if best_k >= 1: 195 | self.__best_k = best_k 196 | else: 197 | self.__best_k = 1 198 | 199 | # auto=False has been deprecated in version 2021-05-19 200 | def fit(self, x_ary, y_ary, verbose=False, sort=False): 201 | #Get the scores of every feature 202 | kbest = SelectKBest(score_func=chi2, k="all") 203 | kbest = kbest.fit(x_ary, y_ary) 204 | 205 | # if auto, choose the best K features 206 | if self.__strategy == "auto": 207 | sig_ary = np.full(kbest.pvalues_.shape, self.significance) 208 | feature_selected = np.less_equal(kbest.pvalues_, sig_ary) 209 | self.best_k = np.count_nonzero(feature_selected == True) 210 | 211 | # if verbose, show additional information 212 | if verbose: 213 | print("\nThe Significant Level: {}".format(self.significance)) 214 | p_values_dict = dict(zip(x_ary.columns, kbest.pvalues_)) 215 | print("\n--- The p-values of Feature Importance ---") 216 | 217 | # if sorted, rearrange p-values in ascending order 218 | if sort: 219 | name_pvalue = sorted(p_values_dict.items(), key=lambda kv: kv[1]) 220 | else: 221 | name_pvalue = [(k, v) for k, v in p_values_dict.items()] 222 | 223 | # Show each feature and its p-value 224 | for k, v in name_pvalue: 225 | sig_str = "TRUE <" if v <= self.significance else "FALSE >" 226 | sig_str += "{:.2f}".format(self.significance) 227 | print("{} {:.8e} ({})".format(sig_str, v, k)) 228 | 229 | # Show how many features have been selected 230 | print("\nNumber of Features Selected: {}".format(self.best_k)) 231 | 232 | # Start to select features 233 | self.__selector = SelectKBest(score_func=chi2, k=self.best_k) 234 | self.__selector = self.__selector.fit(x_ary, y_ary) 235 | 236 | return self 237 | 238 | 239 | def transform(self, x_ary): 240 | # indices=True will return an NDArray of integer for selected columns 241 | cols_kept = self.selector.get_support(indices=True) 242 | return x_ary.iloc[:, cols_kept] 243 | 244 | # In[] Feature Selection: PCA 245 | # PCA does not require Y, also good for non-supervised learning 246 | # NOTE! Do feature scaling before PCA!! 247 | 248 | from sklearn.decomposition import PCA 249 | from sklearn.preprocessing import MinMaxScaler 250 | import matplotlib.pyplot as plt 251 | 252 | class PCASelector: 253 | __selector = None 254 | __best_k = None 255 | __info_covered = None 256 | __strategy = None 257 | 258 | def __init__(self, best_k="auto"): 259 | if type(best_k) is int: 260 | self.__strategy = "fixed" 261 | self.__best_k = best_k 262 | elif type(best_k) is float: 263 | self.__strategy = "percentage" 264 | self.__info_covered = best_k 265 | self.__best_k = None 266 | else: 267 | self.__strategy = "auto" 268 | self.__best_k = None 269 | 270 | self.__selector = PCA(n_components=self.__best_k) 271 | 272 | @property 273 | def selector(self): 274 | return self.__selector 275 | 276 | @property 277 | def best_k(self): 278 | return self.__best_k 279 | 280 | def fit(self, x_ary, verbose=False, plot=False): 281 | # Get information covered by each component 282 | pca = PCA(n_components=None) 283 | pca.fit(x_ary) 284 | info_covered = pca.explained_variance_ratio_ 285 | if verbose: 286 | print("Information Covered by Each Component:") 287 | print(info_covered) 288 | print() 289 | 290 | # Cumulated Coverage of Information 291 | cumulated_sum = np.cumsum(info_covered) 292 | info_covered_dict = dict(zip([i+1 for i in range(info_covered.shape[0])], cumulated_sum)) 293 | if verbose: 294 | print("Cumulated Coverage of Information:") 295 | for n, c in info_covered_dict.items(): 296 | print("{:3d}: {}".format(n, c)) 297 | print() 298 | 299 | if self.__strategy == "auto": 300 | scaler = MinMaxScaler(feature_range=(0, info_covered.shape[0]-1)) 301 | scaled_info_covered = scaler.fit_transform(info_covered.reshape(-1, 1)).ravel() 302 | for i in range(1, scaled_info_covered.shape[0]): 303 | if (scaled_info_covered[i-1]-scaled_info_covered[i]) < 1: 304 | break 305 | self.__best_k = i 306 | elif self.__strategy =="percentage": 307 | current_best = 1 308 | cummulated_info = 0.0 309 | for i in info_covered: 310 | cummulated_info += i 311 | if cummulated_info < self.__info_covered: 312 | current_best += 1 313 | else: 314 | break 315 | self.__best_k = current_best 316 | 317 | self.__selector = PCA(n_components=self.best_k) 318 | self.selector.fit(x_ary) 319 | 320 | if verbose: 321 | print("Strategy: {}".format(self.__strategy)) 322 | print("Select {} components, covered information {:.2%}".format(self.best_k, info_covered_dict[self.best_k])) 323 | print() 324 | 325 | if plot: 326 | np.insert(cumulated_sum, 0, 0.0) 327 | plt.plot(cumulated_sum, color="blue") 328 | plt.scatter(x=self.best_k, y=cumulated_sum[self.best_k], color="red") 329 | plt.title("Components vs. Information") 330 | plt.xlabel("# of Components") 331 | plt.ylabel("Covered Information (%)") 332 | plt.show() 333 | 334 | return self 335 | 336 | def transform(self, x_ary): 337 | X_columns = ["PCA_{}".format(i) for i in range(1, self.best_k+1)] 338 | return pd.DataFrame(self.selector.transform(x_ary), index=x_ary.index, columns=X_columns) 339 | 340 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------