Package: cane
Cane - Categorical Attribute traNsformation EnvironmentCANE is a simpler but powerful preprocessing method for machine learning.At the moment offers some preprocessing methods:--> The Percentage Categorical Pruned (PCP) merges all least frequent levels (summing up to "perc" percent) into a single level as presented in (https://doi.org/10.1109/IJCNN.2019.8851888), which, for example, can be "Others" category. It can be useful when dealing with several amounts of categorical information (e.g., city data).An example of this can be viewed by the following pdf:View PDF.Which the 1,000 highest frequency values (decreasing order) for the user city attribute for the TEST traffic data (which contains a total of 10,690 levels).
For this attribute and when, PCP selects only the most frequent 688 levels (dashed vertical line) merging the other 10,002 infrequent levels into the "Others" label.This method results in 689 binary inputs, which is much less than the 10690 binary inputs required by the standard one-hot transform (reduction ofpercentage points).--> The Inverse Document Frequency (IDF) codifies the categorical levels into frequency values, where the closer to 0 means, the more frequent it is (https://ieeexplore.ieee.org/document/8710472).--> Implementation of a simpler One-Hot-Encoding method.--> Minmax and Standard scaler (based on sklearn functions) with column selection and multicore support. Also, it is possible to apply these transformations to specific columns only instead of the full dataset (follow the example). However it only works with numerical data (e.g., MSE, decision scores)--> You can also provide a custom scaler version of your own! (check example)--> Use IDF with spark dataframesFuture Function ideas:MultiColumn scale (based on the implementation of IDF and PCP)Scaling of IDF values (normalized IDF)InstallationTo install this package please run the following commandpip install caneNewVersion 2.3:[x] - PCP with spark dataframes[x] - Improvements in the example file and readme[x] -  New CitationSuggestions and feedbackAny feedback will be appreciated.
For questions and other suggestions contactluis.matos@dsi.uminho.ptFound any bugs? Post Them on the github page of the project! (https://github.com/Metalkiler/Cane-Categorical-Attribute-traNsformation-Environment)Thanks for the support!CitationTo cite this module please use:@article{MATOS2022100359,
	author = {Lu{\'\i}s Miguel Matos and Jo{\~a}o Azevedo and Arthur Matta and Andr{\'e} Pilastri and Paulo Cortez and Rui Mendes},
	doi = {https://doi.org/10.1016/j.simpa.2022.100359},
	issn = {2665-9638},
	journal = {Software Impacts},
	keywords = {Data preprocessing, CANE, Python programming language, Machine learning},
	pages = {100359},
	title = {Categorical Attribute traNsformation Environment (CANE): A python module for categorical to numeric data preprocessing},
	url = {https://www.sciencedirect.com/science/article/pii/S2665963822000720},
	year = {2022},
	bdsk-url-1 = {https://www.sciencedirect.com/science/article/pii/S2665963822000720},
	bdsk-url-2 = {https://doi.org/10.1016/j.simpa.2022.100359}}Exampleimportpandasaspdimportcaneimporttimeitimportnumpyasnpx=[kforsin([k]*nfork,nin[('a',70000),('b',50000),('c',30000),('d',10000),('e',1000)])forkins]df=pd.DataFrame({f'x{i}':xforiinrange(1,130)})dataPCP=cane.pcp(df)# uses the PCP method and only 1 core with perc == 0.05 for all columnsdataPCP=cane.pcp(df,n_coresJob=2)# uses the PCP method and only 2 cores for all columnsdataPCP=cane.pcp(df,n_coresJob=2,disableLoadBar=False)# With Progress Bar for all columnsdataPCP=cane.pcp(df,n_coresJob=2,disableLoadBar=False,columns_use=["x1","x2"])# With Progress Bar and specific columns#dicionary with the transformed datadataPCP=cane.pcp(df)dicionary=cane.PCPDictionary(dataset=dataPCP,columnsUse=dataPCP.columns,targetColumn=None)#no target feature to avoid going into dictionaryprint(dicionary)dataIDF=cane.idf(df)# uses the IDF method and only 1 core for all columnsdataIDF=cane.idf(df,n_coresJob=2)# uses the IDF method and only 2 core for all columnsdataIDF=cane.idf(df,n_coresJob=2,disableLoadBar=False)# With Progress Bar for all columnsdataIDF=cane.idf(df,n_coresJob=2,disableLoadBar=False,columns_use=["x1","x2"])# specific columnsdataIDF=cane.idf_multicolumn(df,columns_use=["x1","x2"])# aplication of specific multicolumn setting IDFidfDicionary=cane.idfDictionary(Original=df,Transformed=dataIDF,columns_use=["x1","x2"])#following the example above of the 2 columnsdataH=cane.one_hot(df)# without a column prefixerdataH2=cane.one_hot(df,column_prefix='column')# it will use the original column name prefix# (useful for when dealing with id number columns)dataH3=cane.one_hot(df,column_prefix='customColName')# it will use a custom prefix defined by# the value of the column_prefixdataH4=cane.one_hot(df,column_prefix='column',n_coresJob=2)# it will use the original column name prefix# (useful for when dealing with id number columns)# with 2 coresdataH4=cane.one_hot(df,column_prefix='column',n_coresJob=2,disableLoadBar=False)# With Progress Bar Active with 2 coresdataH4=cane.one_hot(df,column_prefix='column',n_coresJob=2,disableLoadBar=False,columns_use=["x1","x2"])# With Progress Bar specific columns!#specific example with multicolumnx2=[kforsin([k]*nfork,nin[('a',50),('b',10),('c',20),('d',15),('e',5)])forkins]x3=[kforsin([k]*nfork,nin[('a',40),('b',20),('c',1),('d',1),('e',38)])forkins]df2=pd.concat([pd.DataFrame({f'x{i}':x2foriinrange(1,3)}),pd.DataFrame({f'y{i}':x3foriinrange(1,3)})],axis=1)dataPCP=cane.pcp(df2,n_coresJob=2,disableLoadBar=False)print("normal PCP\n",dataPCP)dataPCP2=cane.pcp_multicolumn(df2,columns_use=["x1","y1"])# aplication of specific multicolumn setting PCPprint("multicolumn PCP\n",dataPCP2)dataIDF=cane.idf(df2,n_coresJob=2,disableLoadBar=False,columns_use=["x1","y1"])# specific columnsprint("normal idf\n",dataIDF)dataIDF2=cane.idf_multicolumn(df2,columns_use=["x1","y1"])# aplication of specific multicolumn setting IDFprint("multicolumn idf\n",dataIDF2)#Time Measurement in 10 runsprint("Time Measurement in 10 runs (unicore)")OT=timeit.timeit(lambda:cane.one_hot(df,column_prefix='column',n_coresJob=1),number=10)IT=timeit.timeit(lambda:cane.idf(df),number=10)PT=timeit.timeit(lambda:cane.pcp(df),number=10)print("One-Hot Time:",OT)print("IDF Time:",IT)print("PCP Time:",PT)#Time Measurement in 10 runs (multicore)print("Time Measurement in 10 runs (multicore)")OTM=timeit.timeit(lambda:cane.one_hot(df,column_prefix='column',n_coresJob=10),number=10)ITM=timeit.timeit(lambda:cane.idf(df,n_coresJob=10),number=10)PTM=timeit.timeit(lambda:cane.pcp(df,n_coresJob=10),number=10)print("One-Hot Time Multicore:",OTM)print("IDF Time Multicore:",ITM)print("PCP Time Multicore:",PTM)# IDF with pyspark configsimportcanefrompyspark.sqlimportSparkSession#Create PySpark SparkSessionspark=SparkSession.builder.getOrCreate()#Create PySpark DataFrame from PandassparkDF=spark.createDataFrame(df)cols=sparkDF.columnsDFIDF,idf=cane.spark_idf_multicolumn(sparkDF,cols)print(DFIDF.show(20))dataIDF=cane.idf(df)#check if it is correct:print(dataIDF.equals(DFIDF.toPandas()))#equals means correct for both pandas version and original#PCP with pyspark configsimportcanefrompyspark.sqlimportSparkSession#Create PySpark SparkSessionspark=SparkSession.builder.getOrCreate()#Create PySpark DataFrame from PandassparkDF=spark.createDataFrame(df)cols=sparkDF.columnsDFPCP,pcp=cane.spark_pcp(sparkDF,cols,0.05,"Others")DFPCP.show(20)#check if it is correct:dataPCP=cane.pcp(df)print(dataPCP.equals(DFPCP.toPandas()))#equals means correct for both pandas version and originalScaler Example with caneThese examples present the usage of cane with the standard methods (standard scaler e min max scaler).
Also, it is presented how to implement a custom scaler function of your own with cane!#New Scaler FunctiondfNumbers=pd.DataFrame(np.random.randint(0,100000,size=(100000,12)),columns=list('ABCDEFGHIJKL'))cane.scale_data(dfNumbers,n_cores=3,scaleFunc="min_max")# all columns using 3 corescane.scale_data(dfNumbers,column=["A","B"],n_cores=3,scaleFunc="min_max")# scale specific columnscane.scale_data(dfNumbers,column=["A","B"],n_cores=3,scaleFunc="std")#standard Scaler#####################Custom Function Example########################This will be an example file you of your custom function (e.g., "functions.py")importpandasaspdimportnumpyasnpimportcanedefcustomFunc(val):returnpd.DataFrame([round((i-1)/3,2)foriinval],columns=[val.name+"_custom_scalled_function])### This is will be your main scriptfromfunctionsimport*# with a custom function to apply to data:if__name__=="__main__":dfNumbers=pd.DataFrame(np.random.randint(0,100000,size=(100000,12)),columns=list('ABCDEFGHIJKL'))cane.scale_data(dfNumbers,column=["A","B"],n_cores=3,scaleFunc="custom",customfunc=customFunc)