optimize that Julia code to make it run faster: function target(row, penalty=5)…
- User
optimize that Julia code to make it run faster: function target(row, penalty=5) position_ratings = ["RWRating", "STRating", "GKRating", "CMRating", "LWRating", "CDMRating", "LMRating", "CFRating", "CBRating", "CAMRating", "LBRating", "RBRating", "RMRating", "LWBRating", "RWBRating"] parent_data = DataFrame(ID=Int[], Name=String[], FullName=String[], Age=Int[], Height=Int[], Weight=Int[], PhotoUrl=String[], Nationality=String[], Overall=Int[], Potential=Int[], Growth=Int[], TotalStats=Int[], BaseStats=Int[], Positions=String[], BestPosition=String[], Club=String[], ValueEUR=Int[], WageEUR=Int[], ReleaseClause=Int[], ClubPosition=String[], ContractUntil=String[], ClubNumber=Int[], ClubJoined=Int[], OnLoad=Bool[], NationalTeam=String[], NationalPosition=String[], NationalNumber=Int[], PreferredFoot=String[], IntReputation=Int[], WeakFoot=Int[], SkillMoves=Int[], AttackingWorkRate=String[], DefensiveWorkRate=String[], PaceTotal=Int[], ShootingTotal=Int[], PassingTotal=Int[], DribblingTotal=Int[], DefendingTotal=Int[], PhysicalityTotal=Int[], Crossing=Int[], Finishing=Int[], HeadingAccuracy=Int[], ShortPassing=Int[], Volleys=Int[], Dribbling=Int[], Curve=Int[], FKAccuracy=Int[], LongPassing=Int[], BallControl=Int[], Acceleration=Int[], SprintSpeed=Int[], Agility=Int[], Reactions=Int[], Balance=Int[], ShotPower=Int[], Jumping=Int[], Stamina=Int[], Strength=Int[], LongShots=Int[], Aggression=Int[], Interceptions=Int[], Positioning=Int[], Vision=Int[], Penalties=Int[], Composure=Int[], Marking=Int[], StandingTackle=Int[], SlidingTackle=Int[], GKDiving=Int[], GKHandling=Int[], GKKicking=Int[], GKPositioning=Int[], GKReflexes=Int[], STRating=Int[], LWRating=Int[], LFRating=Int[], CFRating=Int[], RFRating=Int[], RWRating=Int[], CAMRating=Int[], LMRating=Int[], CMRating=Int[], RMRating=Int[], LWBRating=Int[], CDMRating=Int[], RWBRating=Int[], LBRating=Int[], CBRating=Int[], RBRating=Int[], GKRating=Int[]) for i in row row_indices = view(Data[i, :]) parent_data=vcat(parent_data,row_indices) end parent_data=DataFrame(parent_data[2:16]) ratings = parent_data[:, position_ratings] ratings_log = log.(ratings)
potential_minus_age = 0.15 * parent_data.Potential - 0.6 * parent_data.Age int_reputation = parent_data.IntReputation sumratings = [] for i in 1:15 temp=ratings_log[i,i] push!(sumratings, temp) end rating_list=sumratings sumratings=sum(sumratings) # Apply constraints constraint_penalty = 0 if sum(parent_data.ValueEUR) > 250000000 constraint_penalty += log((sum(parent_data.ValueEUR) - 250000000)) ^ penalty end if sum(parent_data.WageEUR) > 250000 constraint_penalty += log((sum(parent_data.WageEUR) - 250000)) ^ penalty end if any(rating_list .< 1.2) constraint_penalty += 1.2 ^ penalty end target_value = -(sumratings + 0.3 * sum(potential_minus_age) + sum(int_reputation)) + constraint_penalty return target_valueend
- Assistant
- User
Ia it not better to switch that Data into a transposed matrix?
- Assistant
Yes, transposing the data and using matrices instead of DataFrames may lead to performance gains. Here is the optimized version of the function using matrices:
using LinearAlgebra const POSITION_RATINGS = ["RWRating", "STRating", "GKRating", "CMRating", "LWRating", "CDMRating", "LMRating", "CFRating", "CBRating", "CAMRating", "LBRating", "RBRating", "RMRating", "LWBRating", "RWBRating"] function target(row, data_matrix, col_positions, penalty=5) parent_data = data_matrix[:, row] ratings = parent_data[col_positions.RATINGS, :] ratings_log = log.(ratings) potential_minus_age = 0.15 * parent_data[col_positions.POTENTIAL, :] - 0.6 * parent_data[col_positions.AGE, :] int_reputation = parent_data[col_positions.INT_REPUTATION, :] sumratings = sum(ratings_log) rating_list = diag(ratings_log) # Apply constraints constraint_penalty = 0 if sum(parent_data[col_positions.VALUE_EUR, :]) > 250000000 constraint_penalty += log((sum(parent_data[col_positions.VALUE_EUR, :]) - 250000000)) ^ penalty end if sum(parent_data[col_positions.WAGE_EUR, :]) > 250000 constraint_penalty += log((sum(parent_data[col_positions.WAGE_EUR, :]) - 250000)) ^ penalty end if any(rating_list .< 1.2) constraint_penalty += 1.2 ^ penalty end target_value = -(sumratings + 0.3 * sum(potential_minus_age) + sum(int_reputation)) + constraint_penalty return target_value end - User
Can you optimize that: constraint_penalty = 0 if sum(parent_data.ValueEUR) > 250000000 constraint_penalty += log((sum(parent_data.ValueEUR) - 250000000)) ^ penalty end if sum(parent_data.WageEUR) > 250000 constraint_penalty += log((sum(parent_data.WageEUR) - 250000)) ^ penalty end if any(rating_list .< 1.2) constraint_penalty += 1.2 ^ penalty end ?
- Assistant
Sure! Instead of re-calculating the sums, we can store the sums in variables before checking the constraints. Here is the optimized version of the constraint_penalty calculation:
sum_value_eur = sum(parent_data[col_positions.VALUE_EUR, :]) sum_wage_eur = sum(parent_data[col_positions.WAGE_EUR, :]) constraint_penalty = 0 if sum_value_eur > 250000000 constraint_penalty += log(sum_value_eur - 250000000) ^ penalty end if sum_wage_eur > 250000 constraint_penalty += log(sum_wage_eur - 250000) ^ penalty end if any(rating_list .< 1.2) constraint_penalty += 1.2 ^ penalty endI stored the sums of
parent_data.ValueEURandparent_data.WageEURinsum_value_eurandsum_wage_eurvariables, respectively. This way, we don't need to recalculate the sums in each of theifstatements, resulting in a more efficient constraint penalty check. - User
I need two random columns from matrix in Julia.
- Assistant
To get two random columns from a matrix in Julia, you can use the
randfunction to generate two random indices and then extract the corresponding columns from the matrix. Here's an example function to demonstrate this:using Random function get_random_columns(matrix, num_columns=2) num_total_columns = size(matrix, 2) random_indices = rand(1:num_total_columns, num_columns) random_columns = matrix[:, random_indices] return random_columns endYou can now call this function with your matrix as an argument to get two random columns:
my_matrix = rand(5, 10) # A random 5x10 matrix random_columns = get_random_columns(my_matrix)This will return a new matrix containing the two random columns from
my_matrix. If you want to extract a different number of random columns, you can pass that number as the second argument to the function:random_columns = get_random_columns(my_matrix, 3) # Get 3 random columns - User
Can you make this code: function tournament_selection(parents, t_size, cols,penalty=6) random_indices = rand(1:cols, 2) random_parents = parents[:, random_indices]
random_parents_fitness = [target(parent, penalty, position_ratings, Data) for parent in eachcol(random_parents)] best_parent_idx = argmin(random_parents_fitness) return random_parents[:,best_parent_idx]end more efficent?
- Assistant
To make the
tournament_selectionfunction more efficient, we can pass the cached sums of ValueEUR and WageEUR, as well as the original DataFrame to thetargetfunction directly to avoid unnecessary recomputations. Here's the optimized version of the function:function tournament_selection(parents, t_size, cols, data, col_positions, penalty=6) random_indices = rand(1:cols, 2) random_parents = parents[:, random_indices] random_parents_fitness = [ target(random_parent_columns, data, col_positions, penalty) for random_parent_columns in eachcol(random_parents) ] best_parent_idx = argmin(random_parents_fitness) return random_parents[:, best_parent_idx] endIn this optimized version, we are directly passing the original
dataandcol_positionsto thetargetfunction, allowing it to make use of these inputs more efficiently.Please note that this optimized version assumes you have updated the
targetfunction according to the previous optimizations. - User
Can you optimize that: parent_pop = Matrix{Int}(undef, nrow, cols) for c in 1:population_size parent_pop[:,c] = tournament_selection(parents, tournament_size, cols, penalty) end knowing that population_size is the number of columns in parent_pop?
- Assistant
Certainly! You can optimize the code by replacing the loop with a comprehension combined with the
hcatfunction. Here's the optimized version:function create_parent_pop(parents, nrow, cols, data, col_positions, population_size, tournament_size, penalty) parent_pop = hcat([tournament_selection(parents, tournament_size, cols, data, col_positions, penalty) for _ in 1:population_size]...) return parent_pop end parent_pop = create_parent_pop(parents, nrow, cols, data, col_positions, population_size, tournament_size, penalty)In this optimized version, I replaced the for loop with a comprehension inside the
hcatfunction, which concatenates the generated columns horizontally. This should result in a performance gain, as comprehensions are generally more efficient than loops in Julia. Thecreate_parent_popfunction takes the required inputs and returns theparent_popmatrix.Please note that this optimized version assumes you have updated the
tournament_selectionfunction according to the previous optimizations.