Right now this generates a balenced experiment for a single observer can you update it so it generates for a specific nr of observers?
Assistant
Sure, you can update the code by adding a variable for the number of observers and modifying the code accordingly. Here's the updated code:
python
User
-- coding: utf-8 --
"""
Created on Tue May 23 09:06:44 2023
@author: Del Pin
"""
Assistant
To make the count as even as possible, you can incrementally adjust the number of distortions for each observer so that the distribution of distortions is more balanced.
Here is the updated script:
python
User
Assistant
A more efficient approach would be to ensure that each observer gets a balanced number of distortions for each category without needing to generate multiple experiments. We can do this by creating the distortions once and then reusing them for each observer, rather than generating a new set of distortions for each observer:
User
The approach you presented will not effectively lower the variance while keeping each observer seeing images in the same way as currently specified. The reason is that the generate_images_for_observer function in your code is still creating a single set of images for each observer, which means that the images and distortions will be the same for all observers.
Assistant
I apologize for the confusion, and I agree that simply reusing the same distortions without reshuffling for each observer is incorrect. Here's an alternative approach that creates a balanced experiment by generating a single set of images with the appropriate number of distortions for all observers and then shuffling the distortions within each chunk for each observer. This ensures that each observer has a balanced number of distortions for each category while minimizing the variance.
User
Assistant
import pandas as pd
import random
num_samples = 360 # Change this to the desired number of samples
num_images = 540 # Change this to the desired number of images
num_observers = 5 # Change this to the desired number of observers
# Take list (with 3 equal chunks)
# Give each chunk the same number of distortions
chunk_size = num_samples // 3
imgs_chunk1 = random.sample(range(1, num_images // 3 + 1), chunk_size)
imgs_chunk2 = random.sample(range(num_images // 3 + 1, 2 * num_images // 3 + 1), chunk_size)
imgs_chunk3 = random.sample(range(2 * num_images // 3 + 1, num_images + 1), chunk_size)
imgs = imgs_chunk1 + imgs_chunk2 + imgs_chunk3
# Create letters for each chunk
distortions = [f'{d}{l}' for d in [1, 2, 3] for l in ['a', 'b', 'c']] + ['original']
num_distortions = len(distortions)
num_chunks = 3
let = pd.Series(distortions * (num_samples // (num_distortions * num_chunks)))
# Combine chunks, each randomized
test = pd.concat([let.sample(frac=1) for _ in range(num_chunks * num_observers)], ignore_index=True)
# Check that each chunk has the same number of letters for all observers
for observer in range(num_observers):
start = observer * num_chunks * chunk_size
end = (observer + 1) * num_chunks * chunk_size
sub_test = test[start:end]
print(f"Observer {observer + 1}")
print(sub_test[0:chunk_size].value_counts())
print(sub_test[chunk_size:2 * chunk_size].value_counts())
print(sub_test[2 * chunk_size:3 * chunk_size].value_counts())
# Combine and shuffle for all observers
images = pd.DataFrame({'imgs': imgs * num_observers, 'test': test})
images = images.sample(frac=1).reset_index(drop=True)
This code will generate a balanced experiment for the specified number of observers.
import pandas as pd
import random
def generate_images(num_samples, num_images):
# Take list (with 3 equal chunks)
# Give each chunk the same number of distortions
chunk_size = num_samples // 3
code
imgs_chunk1 = random.sample(range(1, num_images // 3 + 1), chunk_size)
imgs_chunk2 = random.sample(range(num_images // 3 + 1, 2 * num_images // 3 + 1), chunk_size)
imgs_chunk3 = random.sample(range(2 * num_images // 3 + 1, num_images + 1), chunk_size)
imgs = imgs_chunk1 + imgs_chunk2 + imgs_chunk3
# Create letters for each chunk
distortions = [f'{d}{l}' for d in [1, 2, 3] for l in ['a', 'b', 'c']] + ['original']
num_distortions = len(distortions)
num_chunks = 3
let = pd.Series(distortions * (num_samples // (num_distortions * num_chunks)))
# Combine chunks, each randomized
test = pd.concat([let.sample(frac=1) for _ in range(num_chunks)], ignore_index=True)
# Check that each chunk has the same number of letters
test = test.astype('category') # Convert to category for overview
# Combine and shuffle
images = pd.DataFrame({'imgs': imgs, 'test': test})
return images
num_samples = 420 # Change this to the desired number of samples
num_images = 540 # Change this to the desired number of images
num_observers = 60 # Number of observers
Create an empty list to store the DataFrames for each observer
observer_dfs = []
Generate images for each observer and store the DataFrames in the list
for observer in range(1, num_observers + 1):
observer_images = generate_images(num_samples, num_images)
observer_images['observer_nr'] = observer # Add observer number column
observer_dfs.append(observer_images)
Concatenate the DataFrames from each observer into a single result DataFrame
This script adjusts the number of distortions for each observer so that the total count of each combination is as even as possible. It calculates the surplus distortions and distributes the additional distortions evenly among the observers.
This script generates a lot of experiments and selects the one with lowest variance thereby bruteforceing the lowest distribution. Is there a way to do this better all the time making sure that each observer sees each a balanced number of distortions for each category?
-- coding: utf-8 --
"""
Created on Tue May 23 09:06:44 2023
@author: Del Pin
"""
import pandas as pd
import random
import numpy as np
def generate_images(num_samples, num_images):
# Take list (with 3 equal chunks)
# Give each chunk the same number of distortions
chunk_size = num_samples // 3
code
imgs_chunk1 = random.sample(range(1, num_images // 3 + 1), chunk_size)
imgs_chunk2 = random.sample(range(num_images // 3 + 1, 2 * num_images // 3 + 1), chunk_size)
imgs_chunk3 = random.sample(range(2 * num_images // 3 + 1, num_images + 1), chunk_size)
imgs = imgs_chunk1 + imgs_chunk2 + imgs_chunk3
# Create letters for each chunk
distortions = [f'{d}{l}' for d in [1, 2, 3] for l in ['a', 'b', 'c']] + ['original']
num_distortions = len(distortions)
num_chunks = 3
let = pd.Series(distortions * (num_samples // (num_distortions * num_chunks)))
# Combine chunks, each randomized
test = pd.concat([let.sample(frac=1) for _ in range(num_chunks)], ignore_index=True)
# Check that each chunk has the same number of letters
test = test.astype('category') # Convert to category for overview
# Combine and shuffle
images = pd.DataFrame({'imgs': imgs, 'test': test})
return images
num_samples = 420 # Change this to the desired number of samples
num_images = 540 # Change this to the desired number of images
num_observers = 80 # Number of observers
num_runs = 1000 # Number of runs to perform
for run in range(1, num_runs + 1):
# Create an empty list to store the DataFrames for each observer
observer_dfs = []
code
# Generate images for each observer and store the DataFrames in the list
for observer in range(1, num_observers + 1):
observer_images = generate_images(num_samples, num_images)
observer_images['observer_nr'] = observer # Add observer number column
observer_dfs.append(observer_images)
# Concatenate the DataFrames from each observer into a single result DataFrame
result_df = pd.concat(observer_dfs, ignore_index=True)
# Convert 'imgs' and 'test' columns to category data type for overview
result_df['imgs'] = result_df['imgs'].astype('category')
result_df['test'] = result_df['test'].astype('category')
# Count the occurrences of each combination
combination_counts = result_df.groupby(['imgs', 'test']).size().reset_index(name='count')
# Measure the variance in the count
variance = np.var(combination_counts['count'])
print(f"Run {run}: Variance in count: {variance}")
# Check if this run has the lowest variance so far
if variance < min_variance:
min_variance = variance
min_variance_df = result_df.copy()
This approach takes the repeated image chunks as input and reshuffles the distortions within each chunk for each observer while maintaining a balanced number of distortions for each category. It also results in a lower variance in the counts of combinations for each observer.
Please update this code so it can run on multiple cores from a python prompt
import pandas as pd
import random
import numpy as np
def generate_images(num_samples, num_images):
# Take list (with 3 equal chunks)
# Give each chunk the same number of distortions
chunk_size = num_samples // 3
code
imgs_chunk1 = random.sample(range(1, num_images // 3 + 1), chunk_size)
imgs_chunk2 = random.sample(range(num_images // 3 + 1, 2 * num_images // 3 + 1), chunk_size)
imgs_chunk3 = random.sample(range(2 * num_images // 3 + 1, num_images + 1), chunk_size)
imgs = imgs_chunk1 + imgs_chunk2 + imgs_chunk3
# Create letters for each chunk
distortions = [f'{d}{l}' for d in [1, 2, 3] for l in ['a', 'b', 'c']] + ['original']
num_distortions = len(distortions)
num_chunks = 3
let = pd.Series(distortions * (num_samples // (num_distortions * num_chunks)))
# Combine chunks, each randomized
test = pd.concat([let.sample(frac=1) for _ in range(num_chunks)], ignore_index=True)
# Check that each chunk has the same number of letters
test = test.astype('category') # Convert to category for overview
# Combine and shuffle
images = pd.DataFrame({'imgs': imgs, 'test': test})
return images
num_samples = 420 # Change this to the desired number of samples
num_images = 540 # Change this to the desired number of images
num_observers = 80 # Number of observers
num_runs = 10 # Number of runs to perform
for run in range(1, num_runs + 1):
# Set the seed for reproducibility
seed = run
random.seed(seed)
np.random.seed(seed)
code
# Create an empty list to store the DataFrames for each observer
observer_dfs = []
# Generate images for each observer and store the DataFrames in the list
for observer in range(1, num_observers + 1):
observer_images = generate_images(num_samples, num_images)
observer_images['observer_nr'] = observer # Add observer number column
observer_dfs.append(observer_images)
# Concatenate the DataFrames from each observer into a single result DataFrame
result_df = pd.concat(observer_dfs, ignore_index=True)
# Convert 'imgs' and 'test' columns to category data type for overview
result_df['imgs'] = result_df['imgs'].astype('category')
result_df['test'] = result_df['test'].astype('category')
# Count the occurrences of each combination
combination_counts = result_df.groupby(['imgs', 'test']).size().reset_index(name='count')
# Measure the variance in the count
variance = np.var(combination_counts['count'])
print(f"Run {run}: Variance in count: {variance}")
# Check if this run has the lowest variance so far
if variance < min_variance:
min_variance = variance
min_variance_df = result_df.copy()
min_variance_seed = seed
variance = np.var(combination_counts['count'])
print(f"Variance in count: {variance}")
Plot the distribution with the least variance
import matplotlib.pyplot as plt
You can use the concurrent.futures module to parallelize the runs across multiple cores for faster execution. I created a function called perform_run that combines the codes for generating images for each observer and calculating the variance. The run_simulation function creates a pool of workers to parallelize the execution of the perform_run function across the number of specified runs.
python
import pandas as pd
import random
import numpy as np
from concurrent.futures import ProcessPoolExecutor
def perform_run(seed, num_samples, num_images, num_observers):
random.seed(seed)
np.random.seed(seed)
observer_dfs = []
for observer in range(1, num_observers + 1):
observer_images = generate_images(num_samples, num_images)
observer_images['observer_nr'] = observer
observer_dfs.append(observer_images)
result_df = pd.concat(observer_dfs, ignore_index=True)
result_df['imgs'] = result_df['imgs'].astype('category')
result_df['test'] = result_df['test'].astype('category')
combination_counts = result_df.groupby(['imgs', 'test']).size().reset_index(name='count')
variance = np.var(combination_counts['count'])
return variance, result_df, seed
def run_simulation(num_runs, num_samples, num_images, num_observers):
min_variance = float('inf')
min_variance_df = None
min_variance_seed = None
with ProcessPoolExecutor() as executor:
futures = [executor.submit(perform_run, run, num_samples, num_images, num_observers) for run in range(1, num_runs + 1)]
for future in futures:
variance, result_df, seed = future.result()
print(f"Run {seed}: Variance in count: {variance}")
if variance < min_variance:
min_variance = variance
min_variance_df = result_df.copy()
min_variance_seed = seed
return min_variance_df
num_samples = 420
num_images = 540
num_observers = 80
num_runs = 10
min_variance_df = run_simulation(num_runs, num_samples, num_images, num_observers)
combination_counts = min_variance_df.groupby(['imgs', 'test']).size().reset_index(name='count')
variance = np.var(combination_counts['count'])
print(f"Variance in count: {variance}")
This code does the following:
Parallelizes the execution of the perform_run function using the ProcessPoolExecutor.
Waits for each of the concurrent task's results and checks if the result has the lowest variance so far.
Returns the DataFrame with the minimum variance.
By parallelizing the execution, you can speed up the processing time across multiple cores, resulting in much faster execution.