### Build and Install Armadillo Source: https://github.com/davidealtomare/channelattribution/blob/master/python/src/cypack/armadillo-9.860.2/README.md Commands to compile the library and install it to the system or a specified directory. ```bash make ``` ```bash sudo make install ``` ```bash make install ``` -------------------------------- ### Configure Intel MKL Library Paths Source: https://github.com/davidealtomare/channelattribution/blob/master/python/src/cypack/armadillo-9.860.2/README.md Example content for /etc/ld.so.conf.d/mkl.conf to ensure the system linker locates Intel MKL libraries. ```text /opt/intel/lib/intel64 /opt/intel/mkl/lib/intel64 ``` -------------------------------- ### Compile Armadillo with Installation (Linux/macOS) Source: https://github.com/davidealtomare/channelattribution/blob/master/python/src/cypack/armadillo-9.860.2/README.md Use this command to compile a C++ program that uses the Armadillo library when Armadillo is installed system-wide. Ensure Armadillo is correctly installed and discoverable by your compiler. ```bash g++ example1.cpp -o example1 -O2 -larmadillo ``` -------------------------------- ### Install Xcode Command Line Tools Source: https://github.com/davidealtomare/channelattribution/blob/master/python/src/cypack/armadillo-9.860.2/README.md Command to install the necessary C++ compiler tools on macOS. ```bash xcode-select --install ``` -------------------------------- ### Install ChannelAttribution via pip Source: https://github.com/davidealtomare/channelattribution/blob/master/python/README.md Commands to install the library and its dependencies. Requires Python 3 and Microsoft Visual C++ 14.0 or greater on Windows. ```bash pip install --upgrade setuptools pip install Cython pip install ChannelAttribution ``` -------------------------------- ### API Initialization and Input Validation Source: https://github.com/davidealtomare/channelattribution/blob/master/python/src/cypack/docs/_build/html/_modules/ChannelAttribution.html This snippet demonstrates the initial setup for interacting with the Channel Attribution API. It includes checking for necessary libraries, importing them, and validating the presence and type of the 'token' and 'Data' parameters before proceeding with API calls. ```python server = "api.channelattribution.net" try: ck_libs=__check_libs_for_api() if ck_libs==1: __import_libs_for_api() if "NoneType" in str(type(token)): raise NameError("token must be specified. Use function generate_token(email,job,company)") else: if "str" not in str(type(token)): print("token must be a string") if "NoneType" in str(type(Data)): raise NameError("Data must be specified") else: if "DataFrame" not in str(type(Data)): raise NameError("Data must be a DataFrame") ``` -------------------------------- ### Check Required Libraries for APIs Source: https://github.com/davidealtomare/channelattribution/blob/master/python/src/cypack/docs/_build/html/_modules/ChannelAttribution.html Verifies if all necessary libraries for the APIs are installed. If any are missing, it prints installation instructions. ```python def __check_libs_for_api(): res=1 libs=['pysftp','tarfile','uuid','time','urllib','shutil','cryptography','json','requests'] no_libs=[] for lib0 in libs: ck=importlib.util.find_spec(lib0) if ck==None: no_libs= no_libs+[lib0] if len(no_libs)>0: print("There are some missing libraries you need for using our apis. Install them with:") print("pip install " + " ".join(no_libs)) res=0 return(res) ``` -------------------------------- ### Install ChannelAttribution for R Source: https://github.com/davidealtomare/channelattribution/blob/master/README.md Command to install the package from CRAN. ```r install.packages("ChannelAttribution") ``` -------------------------------- ### Initialize SFTP Connection and Get Credentials Source: https://github.com/davidealtomare/channelattribution/blob/master/python/src/cypack/docs/_build/html/_modules/ChannelAttribution.html Establishes an SFTP connection by first obtaining username and password from a remote API endpoint. It creates a unique directory for the session. ```python def __f_initialize_connection(server,token): filename = str(uuid.uuid4()) os.mkdir(filename) os.chdir(filename) url='https://{0}/api/api.php?type=pw&filename={1}&token={2}'.format(server,filename,token) #print(url) info = requests.get(url) info=info.text.split("\n") Username=info[0] Password=info[1][0:-1] sftp=pysftp.Connection(host=socket.gethostbyname(server) , username=Username, password=Password) sftp.cwd('/{0}'.format(Username)) return([filename,sftp]) ``` -------------------------------- ### Configure Armadillo with CMake Source: https://github.com/davidealtomare/channelattribution/blob/master/python/src/cypack/armadillo-9.860.2/README.md Commands to initialize the build configuration using CMake, including options for custom installation paths. ```bash cmake . ``` ```bash cmake . -DCMAKE_INSTALL_PREFIX:PATH=alternative_directory ``` -------------------------------- ### Execute new_paths_attribution_api Source: https://github.com/davidealtomare/channelattribution/blob/master/python/src/cypack/docs/_build/html/_modules/ChannelAttribution.html Example usage of the new_paths_attribution_api function to perform attribution analysis. ```python >>> res_new=new_paths_attribution_api(token, tab_new,var_path="path", \ >>> Tab_re=res['removal_effects'],D_tab_corr=res['corrective_factors'],sep=">") ``` -------------------------------- ### Compile Armadillo without Installation (Linux/macOS) Source: https://github.com/davidealtomare/channelattribution/blob/master/python/src/cypack/armadillo-9.860.2/README.md Compile a C++ program using Armadillo without relying on a system-wide installation. This requires specifying the include path and linking against BLAS and LAPACK manually. Adjust the include path to your Armadillo version and installation directory. ```bash g++ example1.cpp -o example1 -O2 -I /home/blah/armadillo-7.200.3/include -DARMA_DONT_USE_WRAPPER -lblas -llapack ``` -------------------------------- ### GET /transition_matrix Source: https://github.com/davidealtomare/channelattribution/blob/master/python/src/cypack/docs/_build/html/_modules/ChannelAttribution.html Estimates a k-order transition matrix from customer journey data. ```APIDOC ## GET /transition_matrix ### Description Estimate a k-order transition matrix from customer journey data. ### Method GET ### Endpoint /transition_matrix ### Parameters #### Request Body - **Data** (DataFrame) - Required - Customer journeys. - **var_path** (string) - Required - Column of Data containing paths. - **var_conv** (string) - Required - Column of Data containing total conversions for each path. - **var_null** (string) - Required - Column of Data containing null conversions. - **order** (integer) - Optional - Order of the Markov model (default: 1). - **sep** (string) - Optional - Separator used in paths (default: ">"). - **flg_equal** (boolean) - Optional - Flag for equal processing (default: True). - **flg_adv** (boolean) - Optional - Flag for advanced attribution messaging (default: True). ### Response #### Success Response (200) - **transition_matrix** (DataFrame) - The estimated transition matrix containing channel_from, channel_to, and transition_probability. ``` -------------------------------- ### Automatic Markov Model Estimation in Python Source: https://context7.com/davidealtomare/channelattribution/llms.txt Automatically determines the optimal Markov model order and estimates the model in a single step. This function combines the functionality of 'choose_order' and 'markov_model'. Set 'out_more' to TRUE to get detailed results. ```python import pandas as pd from ChannelAttribution import auto_markov_model # Load data Data = pd.read_csv('https://channelattribution.io/csv/Data.csv', sep=";") # Automatic order selection and Markov model estimation result = auto_markov_model( Data, var_path="path", var_conv="total_conversions", var_null="total_null", var_value="total_conversion_value", max_order=10, out_more=True, ncore=4, seed=42, flg_adv=False ) # Output: "Suggested order: 3" # Access results print(result['result']) # Output: # channel_name total_conversions total_conversion_value # 0 alpha 498.35 5415.20 # 1 beta 405.50 4320.75 # 2 gamma 1096.15 12264.05 print(result['transition_matrix']) print(result['removal_effects']) ``` -------------------------------- ### Load Data and Initialize R Package Source: https://github.com/davidealtomare/channelattribution/blob/master/README.md Loads the library and sample dataset. ```r library(ChannelAttribution) library(reshape2) library(ggplot2) data(PathData) ``` -------------------------------- ### Load Data for Attribution Source: https://github.com/davidealtomare/channelattribution/blob/master/python/README.md Initializes the environment and loads customer journey data from a CSV file. ```python import numpy as np import pandas as pd from ChannelAttribution import * import plotly.io as pio Data = pd.read_csv("https://channelattribution.io/csv/Data.csv",sep=";") ``` -------------------------------- ### Initialize Server Connection and Execute Model Source: https://github.com/davidealtomare/channelattribution/blob/master/python/src/cypack/docs/_build/html/_modules/ChannelAttribution.html Establishes a connection to the server, sends data, and triggers the Markov model elaboration via an API request. ```python path0=os.getcwd() #initialize connection [filename,sftp]=__f_initialize_connection(server,token) #send input to server [key,cipher_suite]=__f_send_to_server(Data,False,filename,server,sftp) if key!=-1: #elaborate on server print("Asking to our server to start the elaboration...") url='https://{0}/api/api.php?type=markov-model-local&filename={1}&key={2}&var_path={3}&var_conv={4}&var_value={5}&var_null={6}&order={7}&sep={8}&ncore={9}&conv_par_glob={10}&conv_par_loc={11}&verbose={12}&token={13}'.format(server,filename,key.decode("utf-8"),var_path,var_conv,var_value,var_null,order,sep,ncore,conv_par_glob,conv_par_loc,verbose,token) #print(url) resp=requests.get(url) resp=resp.text print(resp) if "token_ko" not in resp: ``` -------------------------------- ### Load Data and Initialize Python Library Source: https://github.com/davidealtomare/channelattribution/blob/master/README.md Imports necessary libraries and loads customer journey data from a CSV file. ```python import numpy as np import pandas as pd from ChannelAttribution import * import plotly.io as pio Data = pd.read_csv("https://channelattribution.io/csv/Data.csv",sep=";") ``` -------------------------------- ### Initialize Search Box Source: https://github.com/davidealtomare/channelattribution/blob/master/python/src/cypack/docs/_build/html/index.html jQuery snippet to display the search box element. ```javascript $('#searchbox').show(0); ``` -------------------------------- ### Load Sample Data for Attribution Source: https://github.com/davidealtomare/channelattribution/blob/master/python/src/cypack/docs/_build/html/_modules/ChannelAttribution.html Loads sample data from a CSV file using pandas. This is a prerequisite for performing path-level attribution. ```python import pandas as pd from ChannelAttribution import * Data = pd.read_csv('https://channelattribution.io/csv/Data.csv',sep=";") ``` -------------------------------- ### Estimate Transition Matrix in Python Source: https://context7.com/davidealtomare/channelattribution/llms.txt Estimates a k-order transition matrix from customer journey data without performing full attribution. This is useful for analyzing customer behavior patterns and channel transitions. Requires loading data first. ```python import pandas as pd from ChannelAttribution import transition_matrix # Load data Data = pd.read_csv('https://channelattribution.io/csv/Data.csv', sep=";") ``` -------------------------------- ### Estimate First-Order Transition Matrix (Python) Source: https://context7.com/davidealtomare/channelattribution/llms.txt Calculates the first-order transition matrix from customer journey data. Requires specifying the path, conversions, and null variables. The `sep` parameter defines the path separator. ```python result = transition_matrix( Data, var_path="path", var_conv="total_conversions", var_null="total_null", order=1, sep=">", flg_equal=True, flg_adv=False ) # View channel mapping print(result['channels']) # Output: # id_channel channel_name # 0 1 alpha # 1 2 beta # 2 3 gamma # 3 4 (start) # 4 5 (conversion) # 5 6 (null) # View transition probabilities print(result['transition_matrix']) # Output: # channel_from channel_to transition_probability # 0 (start) alpha 0.450 # 1 (start) beta 0.350 # 2 (start) gamma 0.200 # 3 alpha beta 0.280 # 4 alpha gamma 0.410 # 5 alpha (conversion) 0.180 # 6 alpha (null) 0.130 ``` -------------------------------- ### Implementation of new_paths_attribution_api Source: https://github.com/davidealtomare/channelattribution/blob/master/python/src/cypack/docs/_build/html/_modules/ChannelAttribution.html Internal logic for validating inputs, establishing an SFTP connection, and processing attribution data on the remote server. ```python ''' server = "api.channelattribution.net" try: ck_libs=__check_libs_for_api() if ck_libs==1: __import_libs_for_api() if "NoneType" in str(type(token)): raise NameError("token must be specified. Use function generate_token(email,job,company)") else: if "str" not in str(type(token)): print("token must be a string") if "NoneType" in str(type(tab_new)): raise NameError("tab_new must be specified") else: if "DataFrame" not in str(type(tab_new)): raise NameError("tab_new must be a DataFrame") if "NoneType" in str(type(var_path)): raise NameError("var_path must be specified") else: if "str" not in str(type(var_path)): print("var_path must be a string") else: var_path_old=var_path var_path=re.sub(r"\s+", '_', var_path) tab_new.rename(columns={var_path_old: var_path},inplace=True) if "NoneType" in str(type(Tab_re)): raise NameError("Tab_re must be specified") else: if "DataFrame" not in str(type(Tab_re)): raise NameError("Tab_re must be a DataFrame") if "NoneType" in str(type(D_tab_corr)): raise NameError("D_tab_corr must be specified") else: if "dict" not in str(type(D_tab_corr)): raise NameError("D_tab_corr must be a dictionary") if "NoneType" not in str(type(sep)): if "str" not in str(type(sep)): print("sep must be a string") else: print("sep must be specified") path0=os.getcwd() #initialize connection [filename,sftp]=__f_initialize_connection(server,token) #send input to server list_Data=dict() list_Data['tab_new']=tab_new list_Data['Tab_re']=Tab_re list_Data['D_tab_corr_conv']=D_tab_corr['total_conversions'] list_Data['D_tab_corr_value']=D_tab_corr['total_conversion_value'] [key,cipher_suite]=__f_send_to_server(list_Data,True,filename,server,sftp) if key!=-1: # #elaborate on server print("Asking to our server to start the elaboration...") url='https://{0}/api/api.php?type=new-paths-attribution&filename={1}&key={2}&var_path={3}&sep={4}&token={5}'.format(server,filename,key.decode("utf-8"),var_path,sep,token) #print(url) resp=requests.get(url) resp=resp.text print(resp) if "token_ko" not in resp: #retrieving output __f_retrieve_from_server(filename,sftp) print("Composing output...") cipher_text = open(filename+'-O', 'r').read() plain_text = cipher_suite.decrypt(str.encode(cipher_text)) res=pd.read_json(plain_text,orient='records') shutil.rmtree(path0+'/'+filename) os.chdir(path0) print("Your data has been cancelled from our server") print("Elaboration finished!") return(res) else: print("Your token is not valid. Try again or try to generate a new one.") return(-1) ``` -------------------------------- ### Estimate Second-Order Transition Matrix (Python) Source: https://context7.com/davidealtomare/channelattribution/llms.txt Calculates the second-order transition matrix, considering the previous two states in the customer journey. This provides a more detailed view of transitions. ```python # Second-order transition matrix (considers previous two states) result_order2 = transition_matrix( Data, var_path="path", var_conv="total_conversions", var_null="total_null", order=2, flg_adv=False ) print(result_order2['transition_matrix']) ``` -------------------------------- ### POST /transition_matrix Source: https://github.com/davidealtomare/channelattribution/blob/master/python/src/cypack/docs/_build/html/_modules/ChannelAttribution.html Estimates a transition matrix for customer journey paths using Markov models. ```APIDOC ## POST /transition_matrix ### Description Estimates a transition matrix based on customer journey paths, total conversions, and non-conversion paths. ### Parameters #### Request Body - **Data** (DataFrame) - Required - Customer journey data. - **var_path** (string) - Required - Column name containing paths. - **var_conv** (string) - Required - Column name containing total conversions. - **var_null** (string) - Required - Column name containing paths that do not lead to conversion. - **order** (int) - Optional - Markov model order (default 1). - **sep** (string) - Optional - Separator between channels (default ">"). - **flg_equal** (bool) - Optional - If True, transitions from a channel to itself are considered (default True). - **flg_adv** (bool) - Optional - If True, prints ChannelAttribution Pro banner (default True). ### Response #### Success Response (200) - **channels** (DataFrame) - Contains id_channel and channel_name. - **transition_matrix** (DataFrame) - Contains channel_from, channel_to, and transition_probability. ``` -------------------------------- ### Prepare Attribution Value Data for Plotting in Python Source: https://github.com/davidealtomare/channelattribution/blob/master/README.md Formats attribution value data for visualization. ```python R2=R[["channel_name","first_touch_value","last_touch_value",\ "linear_touch_value","total_conversion_value"]] R2.columns=["channel_name","first_touch","last_touch","linear_touch","markov_model"] R2=pd.melt(R2, id_vars="channel_name") data = [dict( type = "histogram", histfunc="sum", x = R2.channel_name, y = R2.value, transforms = [dict( type = "groupby", groups = R2.variable, )], )] ``` -------------------------------- ### Load Data for Channel Attribution Source: https://github.com/davidealtomare/channelattribution/blob/master/python/src/cypack/docs/_build/html/index.html Loads customer journey data from a CSV file using pandas. Ensure the file path and separator are correct. ```python import pandas as pd from ChannelAttribution import * Data = pd.read_csv('https://channelattribution.io/csv/Data.csv',sep=";") ``` -------------------------------- ### Estimate Transition Matrix Source: https://github.com/davidealtomare/channelattribution/blob/master/python/src/cypack/docs/_build/html/index.html Estimates a k-order transition matrix from customer journey data. This function focuses solely on transition probabilities. ```python transition_matrix(Data, "path", "total_conversions", "total_null") ``` -------------------------------- ### Prepare Attribution Value Data for Plotting Source: https://github.com/davidealtomare/channelattribution/blob/master/python/README.md Formats conversion value data for visualization. ```python R2=R[["channel_name","first_touch_value","last_touch_value",\ "linear_touch_value","total_conversion_value"]] R2.columns=["channel_name","first_touch","last_touch","linear_touch","markov_model"] R2=pd.melt(R2, id_vars="channel_name") data = [dict( type = "histogram", histfunc="sum", x = R2.channel_name, y = R2.value, transforms = [dict( type = "groupby", groups = R2.variable, )], )] ``` -------------------------------- ### Perform Path-Level Attribution using Markov Model API Source: https://github.com/davidealtomare/channelattribution/blob/master/python/src/cypack/docs/_build/html/_modules/ChannelAttribution.html Executes path-level attribution using the Markov model API. Requires a valid token and specifies columns for path, conversions, conversion value, and null paths. The order of the Markov model, channel separator, number of cores, and convergence parameters can be adjusted. ```python res=markov_model_local_api(token, Data,var_path="path", var_conv="total_conversions", \ >>> var_value="total_conversion_value", var_null="total_null", order=1, sep=">") ``` -------------------------------- ### Estimate Transition Matrix (R) Source: https://context7.com/davidealtomare/channelattribution/llms.txt Calculates transition matrices using the ChannelAttribution library in R. Supports specifying the order of the Markov model. ```r library(ChannelAttribution) data(PathData) # First-order transition matrix result <- transition_matrix( Data, var_path = "path", var_conv = "total_conversions", var_null = "total_null", order = 1, sep = ">", flg_equal = TRUE, flg_adv = FALSE ) print(result$channels) print(result$transition_matrix) # Third-order transition matrix result_order3 <- transition_matrix( Data, var_path = "path", var_conv = "total_conversions", var_null = "total_null", order = 3, flg_adv = FALSE ) print(result_order3$transition_matrix) ``` -------------------------------- ### Load Data for ChannelAttribution Source: https://github.com/davidealtomare/channelattribution/blob/master/python/src/cypack/docs/_build/html/index.html Standard initialization and data loading process required for all attribution models. ```python >>> import pandas as pd >>> from ChannelAttribution import * >>> Data = pd.read_csv('https://channelattribution.io/csv/Data.csv',sep=";") ``` -------------------------------- ### Download File from SFTP Server with Retries Source: https://github.com/davidealtomare/channelattribution/blob/master/python/src/cypack/docs/_build/html/_modules/ChannelAttribution.html Downloads a file from an SFTP server and verifies its existence. It retries the download and check up to a specified number of times with a delay between attempts. ```python def __f_get_file(filename0,sftp,ntry=12): z=0 flg_ok=0 ck_file=False while (ck_file==False) and (z>> transition_matrix(Data, "path", "total_conversions", var_null="total_null", order=2) ``` -------------------------------- ### Validate Configuration Parameters Source: https://github.com/davidealtomare/channelattribution/blob/master/python/src/cypack/docs/_build/html/_modules/ChannelAttribution.html Checks that configuration parameters like order, separator, and model parameters meet type and value constraints. ```python if "NoneType" not in str(type(order)): if "int" not in str(type(order)): print("order must be a int") else: if order<1: print("order must be > 0") else: print("order must be specified") ``` ```python if "NoneType" not in str(type(sep)): if "str" not in str(type(sep)): print("sep must be a string") else: print("sep must be specified") ``` ```python if "NoneType" not in str(type(conv_par_glob)): if "float" not in str(type(conv_par_glob)): print("conv_par_glob must be a float") else: if conv_par_glob<=0: print("conv_par_glob must be > 0") ``` ```python if "NoneType" not in str(type(conv_par_loc)): if "float" not in str(type(conv_par_loc)): print("conv_par_loc must be a float") else: if conv_par_loc<=0: print("conv_par_loc must be > 0") ``` ```python if "NoneType" not in str(type(verbose)): if "bool" not in str(type(verbose)): print("verbose must be True or False") ``` -------------------------------- ### Configure Armadillo for Windows Libraries Source: https://github.com/davidealtomare/channelattribution/blob/master/python/src/cypack/armadillo-9.860.2/README.md Modify the Armadillo configuration header to enable specific libraries like LAPACK, BLAS, ARPACK, and SuperLU. Uncomment the relevant defines based on the libraries available on your system. ```c++ #define ARMA_USE_LAPACK #define ARMA_USE_BLAS #define ARMA_USE_ARPACK #define ARMA_USE_SUPERLU ``` -------------------------------- ### Compare Heuristic and Markov Models (Python) Source: https://context7.com/davidealtomare/channelattribution/llms.txt Estimates heuristic and Markov attribution models and merges the results for comparison. Requires loading data and specifying path, conversions, and value variables. ```python import pandas as pd from ChannelAttribution import heuristic_models, markov_model # Load customer journey data Data = pd.read_csv('https://channelattribution.io/csv/Data.csv', sep=";") # Estimate heuristic models H = heuristic_models( Data, "path", "total_conversions", var_value="total_conversion_value", flg_adv=False ) # Estimate Markov model M = markov_model( Data, "path", "total_conversions", var_value="total_conversion_value", flg_adv=False ) # Merge results for comparison R = pd.merge(H, M, on="channel_name", how="inner") # Compare conversions across models comparison = R[[ "channel_name", "first_touch_conversions", "last_touch_conversions", "linear_touch_conversions", "total_conversions" ]] comparison.columns = [ "channel_name", "first_touch", "last_touch", "linear_touch", "markov_model" ] print(comparison) # Output: # channel_name first_touch last_touch linear_touch markov_model # 0 alpha 1230.0 230.0 615.25 498.35 # 1 beta 450.0 380.0 425.75 405.50 # 2 gamma 320.0 1390.0 958.00 1096.15 # Visualize with plotly import plotly.express as px comparison_melted = pd.melt(comparison, id_vars="channel_name", var_name="model", value_name="conversions") fig = px.bar(comparison_melted, x="channel_name", y="conversions", color="model", barmode="group", title="Attribution Model Comparison") fig.show() ``` -------------------------------- ### Prepare Attribution Value Data for Plotting in R Source: https://github.com/davidealtomare/channelattribution/blob/master/README.md Formats attribution value data for visualization. ```r R2=R[,(colnames(R)%in%c("channel_name","first_touch_value","last_touch_value","linear_touch_value", "total_conversion_value"))] colnames(R2)=c("channel_name","first_touch","last_touch","linear_touch","markov_model") R2=melt(R2,id="channel_name") ``` -------------------------------- ### Compare Heuristic and Markov Models (R) Source: https://context7.com/davidealtomare/channelattribution/llms.txt Estimates heuristic and Markov attribution models in R and visualizes the comparison using ggplot2. Requires loading libraries and data. ```r library(ChannelAttribution) library(reshape2) library(ggplot2) data(PathData) # Estimate heuristic models H <- heuristic_models( Data, "path", "total_conversions", var_value="total_conversion_value", flg_adv=FALSE ) # Estimate Markov model M <- markov_model( Data, "path", "total_conversions", var_value="total_conversion_value", flg_adv=FALSE ) # Merge results R <- merge(H, M, by="channel_name") # Prepare comparison data R1 <- R[, c("channel_name", "first_touch_conversions", "last_touch_conversions", "linear_touch_conversions", "total_conversions")] colnames(R1) <- c("channel_name", "first_touch", "last_touch", "linear_touch", "markov_model") R1 <- melt(R1, id="channel_name") # Visualize ggplot(R1, aes(channel_name, value, fill=variable)) + geom_bar(stat="identity", position="dodge") + labs(title="Attribution Model Comparison", x="Channel", y="Conversions") + theme_minimal() + theme(legend.title=element_blank()) ``` -------------------------------- ### Estimate Transition Matrix (Order 2) Source: https://github.com/davidealtomare/channelattribution/blob/master/python/src/cypack/docs/_build/html/_modules/ChannelAttribution.html Estimates a second-order transition matrix using total conversions and paths that do not lead to conversion. Requires the pandas DataFrame 'Data' and column names for path, conversions, and null paths. ```python transition_matrix(Data, "path", "total_conversions", var_null="total_null", order=2) ``` -------------------------------- ### Estimate Markov Model with Conversions and Revenue Source: https://github.com/davidealtomare/channelattribution/blob/master/python/src/cypack/docs/_build/html/index.html Estimates a Markov model considering both total conversions and revenue. Requires specifying the revenue column. ```python markov_model(Data, "path", "total_conversions", var_value="total_conversion_value") ``` -------------------------------- ### Advanced Markov Model with Options in R Source: https://context7.com/davidealtomare/channelattribution/llms.txt Configures a Markov model with all available options, including conversion value, null conversions, model order, and parallel processing. Set 'out_more' to TRUE to retrieve additional results like transition matrix and removal effects. ```r library(ChannelAttribution) data(PathData) # Markov model with all options result <- markov_model( Data, var_path = "path", var_conv = "total_conversions", var_value = "total_conversion_value", var_null = "total_null", order = 2, out_more = TRUE, ncore = 4, seed = 42, verbose = TRUE, flg_adv = FALSE ) # View results print(result$result) print(result$transition_matrix) print(result$removal_effects) ``` -------------------------------- ### Estimate Markov Model Order Source: https://github.com/davidealtomare/channelattribution/blob/master/python/src/cypack/docs/_build/html/_modules/ChannelAttribution.html Load customer journey data and execute the choose_order function to determine the optimal model order. ```python >>> import pandas as pd >>> from ChannelAttribution import * >>> Data = pd.read_csv('https://channelattribution.io/csv/Data.csv',sep=";") >>> choose_order(Data, var_path="path", var_conv="total_conversions", var_null="total_null") ``` -------------------------------- ### List Files in SFTP Directory Source: https://github.com/davidealtomare/channelattribution/blob/master/python/src/cypack/docs/_build/html/_modules/ChannelAttribution.html Retrieves a list of filenames from the current directory on an SFTP server. ```python def __f_list_files(sftp): directory_structure = sftp.listdir_attr() vattr=[] for attr in directory_structure: vattr=vattr+[attr.filename] #print(attr.filename, attr) return(vattr) ``` -------------------------------- ### Perform Markov Attribution in Python Source: https://github.com/davidealtomare/channelattribution/blob/master/README.md Calculates attribution using the Markov model. ```python M=markov_model(Data, "path", "total_conversions", var_value="total_conversion_value") ``` -------------------------------- ### Estimate Markov Attribution Models Source: https://context7.com/davidealtomare/channelattribution/llms.txt Uses stochastic simulations to estimate k-order Markov models, supporting transition matrix extraction and removal effects. ```python import pandas as pd from ChannelAttribution import markov_model # Load data Data = pd.read_csv('https://channelattribution.io/csv/Data.csv', sep=";") # Basic Markov model with first-order transitions result = markov_model(Data, "path", "total_conversions") print(result) # Output: # channel_name total_conversions # 0 alpha 523.45 # 1 beta 412.30 # 2 gamma 1064.25 # Markov model with conversion values and non-converting paths result = markov_model( Data, var_path="path", var_conv="total_conversions", var_value="total_conversion_value", var_null="total_null", order=2, seed=42, flg_adv=False ) print(result) # Output: # channel_name total_conversions total_conversion_value # 0 alpha 485.20 5230.50 # 1 beta 398.75 4125.80 # 2 gamma 1116.05 12643.70 # Full output with transition matrix and removal effects result = markov_model( Data, var_path="path", var_conv="total_conversions", var_value="total_conversion_value", var_null="total_null", order=1, out_more=True, ncore=4, verbose=True, flg_adv=False ) # Access attribution results print(result['result']) # Access transition probabilities print(result['transition_matrix']) # Output: # channel_from channel_to transition_probability # 0 (start) alpha 0.450 ``` -------------------------------- ### transition_matrix Source: https://github.com/davidealtomare/channelattribution/blob/master/python/src/cypack/docs/_build/html/index.html Estimates a transition matrix between channels based on conversion data. ```APIDOC ## transition_matrix ### Description Estimates a transition matrix (of a specified order) using total conversions and paths that do not lead to conversion. ### Parameters #### Arguments - **Data** (DataFrame) - Required - The input dataset containing path and conversion information. - **path** (string) - Required - The column name containing the conversion paths. - **total_conversions** (string) - Required - The column name containing total conversion counts. - **var_null** (string) - Optional - The column name representing paths that do not lead to conversion. - **order** (integer) - Optional - The order of the transition matrix to estimate. ### Response - **channels** (DataFrame) - Contains 'id_channel' and 'channel_name'. - **transition_matrix** (DataFrame) - Contains 'channel_from', 'channel_to', and 'transition_probability'. ### Request Example ```python transition_matrix(Data, "path", "total_conversions", var_null="total_null", order=2) ``` ``` -------------------------------- ### Estimate Markov Model with Multiprocessing Source: https://github.com/davidealtomare/channelattribution/blob/master/python/src/cypack/docs/_build/html/index.html Estimates a Markov model utilizing multiple threads for faster computation. Specify the number of cores with `ncore`. ```python markov_model(Data, "path", "total_conversions", var_value="total_conversion_value", ncore=4) ``` -------------------------------- ### Estimate Heuristic Attribution Models Source: https://context7.com/davidealtomare/channelattribution/llms.txt Calculates first-touch, last-touch, and linear-touch attribution metrics from customer journey data. ```python import pandas as pd from ChannelAttribution import heuristic_models # Load customer journey data Data = pd.read_csv('https://channelattribution.io/csv/Data.csv', sep=";") # Example data structure: # path | total_conversions | total_conversion_value | total_null # alpha > beta > beta > gamma | 1 | 10.50 | 5 # alpha > gamma | 2 | 25.00 | 3 # Basic attribution using only conversions result = heuristic_models(Data, "path", "total_conversions") print(result) # Output: # channel_name first_touch last_touch linear_touch # 0 alpha 1230.0 230.0 615.25 # 1 beta 450.0 380.0 425.75 # 2 gamma 320.0 1390.0 958.00 # Attribution with conversion values included result_with_value = heuristic_models( Data, var_path="path", var_conv="total_conversions", var_value="total_conversion_value", sep=">", flg_adv=False ) print(result_with_value) # Output includes: # channel_name first_touch_conversions first_touch_value last_touch_conversions # last_touch_value linear_touch_conversions linear_touch_value ``` ```r library(ChannelAttribution) # Load sample data included with package data(PathData) # Basic heuristic attribution result <- heuristic_models(Data, "path", "total_conversions") print(result) # Attribution with conversion values result_with_value <- heuristic_models( Data, var_path = "path", var_conv = "total_conversions", var_value = "total_conversion_value", sep = ">", flg_adv = FALSE ) print(result_with_value) ``` -------------------------------- ### Estimate Markov Model with More Output Source: https://github.com/davidealtomare/channelattribution/blob/master/python/src/cypack/docs/_build/html/index.html Estimates a Markov model and returns additional details like the transition matrix and removal effects. Set `out_more` to True. ```python markov_model(Data, "path", "total_conversions", var_value="total_conversion_value", var_null="total_null", out_more=True) ``` -------------------------------- ### Configure Armadillo Integer and Function Name Defines Source: https://github.com/davidealtomare/channelattribution/blob/master/python/src/cypack/armadillo-9.860.2/README.md Modify these defines in include/armadillo_bits/config.hpp to match the integer sizes and function naming conventions of your BLAS/LAPACK replacement library. ```cpp ARMA_USE_WRAPPER ARMA_BLAS_CAPITALS ARMA_BLAS_UNDERSCORE ARMA_BLAS_LONG ARMA_BLAS_LONG_LONG ``` -------------------------------- ### Upload File to SFTP Server with Retries Source: https://github.com/davidealtomare/channelattribution/blob/master/python/src/cypack/docs/_build/html/_modules/ChannelAttribution.html Uploads a file to an SFTP server and verifies its presence. It retries the upload and check up to a specified number of times with a delay between attempts. ```python def __f_put_file(filename0,sftp,ntry=12): z=0 flg_ok=0 list_files=[] while (filename0 not in list_files) and (z"). - **ncore** (int) - Optional - Number of threads to be used (default 1). - **nfold** (int) - Optional - Repetitions to verify convergence (default 10). - **seed** (int) - Optional - Random seed (default 0). - **conv_par** (double) - Optional - Convergence parameter (default 0.05). - **rate_step_sim** (double) - Optional - Simulation rate multiplier (default 1.5). - **verbose** (bool) - Optional - Show convergence info (default True). - **flg_adv** (bool) - Optional - Print Pro banner (default True). ### Response - **result** (DataFrame) - Contains channel_name, total_conversions, and total_conversion_value. - **transition_matrix** (DataFrame) - Contains channel_from, channel_to, and transition_probability. - **removal_effects** (DataFrame) - Contains channel_name, removal_effects_conversion, and removal_effects_conversion_value. ``` -------------------------------- ### Estimate Markov Model with Total Conversions Source: https://github.com/davidealtomare/channelattribution/blob/master/python/src/cypack/docs/_build/html/index.html Estimates a Markov model using only total conversions. This is a basic usage scenario. ```python markov_model(Data, "path", "total_conversions") ``` -------------------------------- ### Perform Heuristic Attribution in Python Source: https://github.com/davidealtomare/channelattribution/blob/master/README.md Calculates attribution using heuristic models. ```python H=heuristic_models(Data,"path","total_conversions",var_value="total_conversion_value") ``` -------------------------------- ### Automatic Markov Model Estimation in R Source: https://context7.com/davidealtomare/channelattribution/llms.txt Performs automatic Markov model estimation by selecting the optimal order and fitting the model. This function streamlines the process of channel attribution. Set 'out_more' to TRUE to obtain detailed outputs. ```r library(ChannelAttribution) data(PathData) # Automatic Markov model with optimal order selection result <- auto_markov_model( Data, var_path = "path", var_conv = "total_conversions", var_null = "total_null", var_value = "total_conversion_value", max_order = 10, out_more = TRUE, ncore = 4, seed = 42, flg_adv = FALSE ) print(result$result) print(result$transition_matrix) print(result$removal_effects) ``` -------------------------------- ### Perform Markov Model Local Path Attribution Source: https://github.com/davidealtomare/channelattribution/blob/master/python/src/cypack/docs/_build/html/_modules/ChannelAttribution.html Applies a Markov model for local path attribution. Requires a token, dataframes for new paths, removal effects, and corrective factors, along with specified column names and an optional separator. ```python res=markov_model_local_api(token, Data,var_path="path", var_conv="total_conversions", \ var_value="total_conversion_value", var_null="total_null", order=1, sep=">") ```