Skip to content
TheChatArchiveThe Chat Archive
gpt-4-0314· openaiHugging Face Suzhen/CodeChat

Change that R code: Data<-read.csv("C:/Users/Użytkownik/Desktop/player22.csv") RWidx <-…

  1. User

    Change that R code: Data<-read.csv("C:/Users/Użytkownik/Desktop/player22.csv")

    RW_idx <- which(grepl("RW", DataPositions))STidx<−which(grepl("ST",DataPositions)) ST_idx <- which(grepl("ST", DataPositions)) GK_idx <- which(grepl("GK", DataPositions))CMidx<−which(grepl("CM",DataPositions)) CM_idx <- which(grepl("CM", DataPositions)) LW_idx <- which(grepl("LW", DataPositions))CDMidx<−which(grepl("CDM",DataPositions)) CDM_idx <- which(grepl("CDM", DataPositions)) LM_idx <- which(grepl("LM", DataPositions))CFidx<−which(grepl("CF",DataPositions)) CF_idx <- which(grepl("CF", DataPositions)) CB_idx <- which(grepl("CB", DataPositions))CAMidx<−which(grepl("CAM",DataPositions)) CAM_idx <- which(grepl("CAM", DataPositions)) LB_idx <- which(grepl("LB", DataPositions))RBidx<−which(grepl("RB",DataPositions)) RB_idx <- which(grepl("RB", DataPositions)) RM_idx <- which(grepl("RM", DataPositions))LWBidx<−which(grepl("LWB",DataPositions)) LWB_idx <- which(grepl("LWB", DataPositions)) RWB_idx <- which(grepl("RWB", Data$Positions))

    #############

    pop_init <- list()

    Create a list of vectors to loop through

    position_vectors <- list(RW_idx, ST_idx, GK_idx, CM_idx, LW_idx, CDM_idx, LM_idx, CF_idx, CB_idx, CAM_idx, LB_idx, RB_idx, RM_idx, LWB_idx, RWB_idx)

    position_vectors_list<-position_vectors

    tournament_selection <- function(parents, t_size) {

    Select t_size random parents

    random_parents_idx <- sample(nrow(parents), t_size, replace = FALSE) random_parents <- parents[random_parents_idx, ]

    Evaluate the target function for each selected parent

    random_parents_fitness <- apply(random_parents, 1, target)

    Select the best parent based on the target function value

    best_parent_idx <- which.max(random_parents_fitness) return(random_parents[best_parent_idx, ]) }

    Crossover function

    crossover <- function(parent1, parent2) {

    Choose a random crossover point

    crossover_point <- sample(2:(ncol(parent1) - 1), 1)

    Swap the position vectors after the crossover point

    offspring1 <- c(parent1[1:crossover_point], parent2[(crossover_point + 1):ncol(parent1)]) offspring2 <- c(parent2[1:crossover_point], parent1[(crossover_point + 1):ncol(parent2)])

    return(rbind(offspring1, offspring2)) }

    mutate <- function(individual, position_vectors_list, probability = 0.09) { for (pos_idx in 1:length(position_vectors_list)) { if (runif(1) <= probability) { repeat { random_idx <- sample(position_vectors_list[[pos_idx]], 1) if (!random_idx %in% individual) { individual[pos_idx] <- random_idx break } } } } return(individual) }

    preserve_elites <- function(population, num_elites) { population_fitness <- apply(population, 1, target) elite_indices <- order(-population_fitness)[1:num_elites] elites <- population[elite_indices, ] return(as.matrix(elites)) }

    initialize_individual <- function(position_vectors_list) { individual <- sapply(position_vectors_list, function(pos) sample(pos, 1)) return(individual) }

    Create initial population

    n_rows <- 100 initial_population <- matrix(NA, n_rows, length(position_vectors)) for (i in 1:n_rows) { individual <- initialize_individual(position_vectors) initial_population[i, ] <- individual }

    Define the target function

    target <- function(parent_indices) { position_ratings <- c("RWRating", "STRating", "GKRating", "CMRating", "LWRating", "CDMRating", "LMRating", "CFRating", "CBRating", "CAMRating", "LBRating", "RBRating", "RMRating", "LWBRating", "RWBRating")

    parent_data <- Data[parent_indices, ] ratings <- parent_data[position_ratings] ratings_log <- log(ratings)

    potential_minus_age <- parent_dataPotential−parentdataPotential - parent_dataAge log_value_eur_minus_wage_eur <- log(parent_dataValueEUR)−log(parentdataValueEUR) - log(parent_dataWageEUR) int_reputation <- parent_data$IntReputation

    Apply constraints

    constraint_penalty <- 0 if (sum(parent_dataValueEUR)>250000000)constraintpenalty<−constraintpenalty+200if(sum(parentdataValueEUR) > 250000000) { constraint_penalty <- constraint_penalty + 200 } if (sum(parent_dataWageEUR) > 250000) { constraint_penalty <- constraint_penalty + 200 } if (any(ratings_log < 1.2)) { constraint_penalty <- constraint_penalty + 200 }

    target_value <- -(rowSums(ratings_log) + potential_minus_age - log_value_eur_minus_wage_eur + int_reputation) + constraint_penalty

    return(target_value) }

    Create a matrix to store the population

    population <- as.matrix(population)

    Genetic algorithm parameters

    population_size <- 100 num_generations <- 1000 tournament_size <- 5 num_elites <- 2

    for (gen in 1:num_generations) {

    Preserve elites

    elites <- preserve_elites(population, num_elites)

    Create an empty matrix to store offspring

    offspring_population <- matrix(NA, population_size - num_elites, ncol(population))

    Perform crossover and mutation to generate offspring

    for (i in seq(1, population_size - num_elites, 2)) { # Select two parents using tournament selection parent1 <- tournament_selection(population, tournament_size) parent2 <- tournament_selection(population, tournament_size)

    # Perform crossover to generate offspring
    offspring <- crossover(parent1, parent2)
    
    # Mutate offspring
    offspring[1, ] <- mutate(offspring[1, ], position_vectors_list)
    offspring[2, ] <- mutate(offspring[2, ], position_vectors_list)
    
    # Add the generated offspring to the offspring population matrix
    offspring_population[i, ] <- as.numeric(offspring[1, ])
    offspring_population[(i + 1), ] <- as.numeric(offspring[2, ])
    

    }

    Replace the old population with the offspring and elites

    population <- rbind(elites, offspring_population)

    Calculate the fitness for the current population

    population_fitness <- apply(population, 1, target)

    Get the best solution in the current population

    best_solution <- population[which.max(population_fitness), ] best_fitness <- max(population_fitness) }

    Remove temporary variables

    rm(offspring_population, population_fitness)

    To Julia.

  2. Assistant
    using DataFrames, CSV, Random
    Data = CSV.read("C:/Users/Użytkownik/Desktop/player22.csv", DataFrame)
    
    positions = ["RW", "ST", "GK", "CM", "LW", "CDM", "LM", "CF",
                 "CB", "CAM", "LB", "RB", "RM", "LWB", "RWB"]
    
    position_indices = [findall(occursin.(pos, Data.Positions)) for pos in positions]
    n_rows = 100
    
    function tournament_selection(parents, t_size)
        random_parents_idx = randperm(size(parents, 1))[1:t_size]
        random_parents = parents[random_parents_idx, :]
        random_parents_fitness = map(eachrow(random_parents)) do row
            target(row)
        end
        best_parent_idx = argmax(random_parents_fitness)
        return random_parents[best_parent_idx, :]
    end
    
    function crossover(parent1, parent2)
        crossover_point = rand(2:size(parent1, 2) - 1)
        offspring1 = vcat(parent1[1:crossover_point], parent2[crossover_point + 1:end])
        offspring2 = vcat(parent2[1:crossover_point], parent1[crossover_point + 1:end])
        return hcat(offspring1, offspring2)
    end
    
    function mutate(individual, position_vectors_list, probability = 0.09)
        for (pos_idx, position) in enumerate(position_vectors_list)
            if rand() <= probability
                while true
                    random_idx = rand(position)
                    if !(random_idx in individual)
                        individual[pos_idx] = random_idx
                        break
                    end
                end
            end
        end
        return individual
    end
    
    function preserve_elites(population, num_elites)
        population_fitness = map(eachrow(population)) do row
            target(row)
        end
        elite_indices = sortperm(population_fitness, rev=true)[1:num_elites]
        return population[elite_indices, :]
    end
    
    function initialize_individual(position_vectors_list)
        individual = [rand(pos) for pos in position_vectors_list]
        return individual
    end
    
    initial_population = [initialize_individual(position_indices) for _ in 1:n_rows]
    
    function target(parent_indices)
        position_ratings = ["RWRating", "STRating", "GKRating", "CMRating",
                            "LWRating", "CDMRating", "LMRating", "CFRating",
                            "CBRating", "CAMRating", "LBRating", "RBRating",
                            "RMRating", "LWBRating", "RWBRating"]
    
        ratings = log.(Data[parent_indices, position_ratings])
        potential_minus_age = Data[parent_indices, :Potential] .- Data[parent_indices, :Age]
        log_value_eur_minus_wage_eur = log.(Data[parent_indices, :ValueEUR]) .- log.(Data[parent_indices, :WageEUR])
        int_reputation = Data[parent_indices, :IntReputation]
    
        constraint_penalty = 0
        if sum(Data[parent_indices, :ValueEUR]) > 250000000
            constraint_penalty += 200
        end
        if sum(Data[parent_indices, :WageEUR]) > 250000
            constraint_penalty += 200
        end
        if any(ratings .< 1.2)
            constraint_penalty += 200
        end
    
        target_value = -(sum(ratings) + potential_minus_age - log_value_eur_minus_wage_eur + int_reputation) + constraint_penalty
        return target_value
    end
    
    population = hcat(initial_population...)
    
    # Genetic algorithm parameters
    population_size = 100
    num_generations = 1000
    tournament_size = 5
    num_elites = 2
    
    for gen in 1:num_generations
        elites = preserve_elites(population, num_elites)
        offspring_population = Matrix{Int}(undef, population_size - num_elites, size(population, 2))
        for i in 1:2:(population_size - num_elites)
            parent1 = tournament_selection(population, tournament_size)
            parent2 = tournament_selection(population, tournament_size)
            offspring = crossover(parent1, parent2)
            offspring[:, 1] = mutate(offspring[:, 1], position_indices)
            offspring[:, 2] = mutate(offspring[:, 2], position_indices)
            offspring_population[i:i+1, :] = offspring
        end
        population = vcat(elites, offspring_population)
        population_fitness = map(eachrow(population)) do row
            target(row)
        end
        best_solution = population[argmax(population_fitness), :]
        best_fitness = maximum(population_fitness)
    end
    

    I have converted the R code to Julia code. Please note that this code uses the DataFrames, CSV, and Random packages, so make sure that you have these packages installed. To install them, you can run:

    import Pkg
    Pkg.add("DataFrames")
    Pkg.add("CSV")
    Pkg.add("Random")