Rewrite this code in more optimal way and add comments!
from scipy.special import expit, logsumexp
because you wrote docstrings in english therefore my comments for code and graphics was in english
def posterior(alpha, beta, L):
""" Posterior over true labels z p(z|l, \alpha, \beta)
Args:
alpha: ndarray of shape (n_experts).
beta: ndarray of shape (n_problems).
L: ndarray of shape (n_problems, n_experts).
Returns:
ndarray of shape (2, n_problems)
(2 -- for z = 0 and for z = 1, n_problems -- for each problem in data)
Tip:
You may use function log_likelihood here
See page 7 of seminar, the last formula for details
"""
code
z = np.zeros(L.shape[0])
# compute log_likelihood for z = 0 and z = 1 and then vertical stack
log_likelihood_z = np.vstack([log_likelihood(alpha, beta, L, z + z_) for z_ in [0,1]])
# try to explain return code. return log(q(z)) instead of q(z) as it is recommended at help material
# return log q(z) = log (exp(log_likelihood_z) / sum(exp(log_likelihood_0) + exp(log_likelihood_1))) =
# = log_likelihood_z - log(sum(exp(log_likelihood_0) + exp(log_likelihood_1)))
return np.exp(log_likelihood_z - logsumexp(log_likelihood_z,axis=0))
def log_likelihood(alpha, beta, L, z):
""" p(l=z|z, \alpha, \beta)
Args:
alpha: ndarray of shape (n_experts).
beta: ndarray of shape (n_problems).
L: ndarray of shape (n_problems, n_experts).
z: ndarray of shape (n_problems).
Returns:
ndarray of shape (n_problems,)
Tips:
See page 7 of seminar, the second formula for details
"""
# make all necessary reshape for broadcast
z = z.reshape(-1,1)
beta = beta.reshape(-1,1)
# compute indicators matrix where element = [l_ij == z_i]
indicators = L == z
return np.log(0.5) + np.sum(indicators * -softplus(-beta * alpha) + ~indicators * -softplus(beta * alpha),axis=1)
def alpha_grad_lb(alpha, beta, L, q):
""" Gradient of lower bound wrt alpha
Args:
alpha: ndarray of shape (n_experts).
beta: ndarray of shape (n_problems).
L: ndarray of shape (n_problems, n_experts).
q: ndarray of shape (2, n_problems).
Returns:
ndarray of shape (n_experts,)
Tips:
See pages 8-9 of seminar for details
"""
# make all necessary reshape for broadcast
beta = beta.reshape(-1,1)
# compute for t = 0 and t = 0
indicators = L == 0
# it can be modified for case when q.shape[0] > 2 for example by simple cycle, but here we have requirement for shape q
t_0 = q[0].reshape(-1,1) * beta * (indicators * expit(-beta * alpha) - ~indicators * expit(beta * alpha))
t_1 = q[1].reshape(-1,1) * beta * (~indicators * expit(-beta * alpha) - indicators * expit(beta * alpha))
code
return np.sum(t_0 + t_1, axis=0)
def logbeta_grad_lb(alpha, beta, L, q):
""" Gradient of lower bound wrt alpha
Args:
alpha: ndarray of shape (n_experts).
beta: ndarray of shape (n_problems).
L: ndarray of shape (n_problems, n_experts).
q: ndarray of shape (2, n_problems).
Returns:
ndarray of shape (n_problems,)
Tips:
See pages 8-9 of seminar for details
"""
# make all necessary reshape for broadcast
beta = beta.reshape(-1,1)
# compute for t = 0 and t = 0
indicators = L == 0
# it can be modified for case when q.shape[0] > 2 for example by simple cycle, but here we have requirement for shape q
t_0 = q[0].reshape(-1,1) * alpha * (indicators * expit(-beta * alpha) - ~indicators * expit(beta * alpha))
t_1 = q[1].reshape(-1,1) * alpha * (~indicators * expit(-beta * alpha) - indicators * expit(beta * alpha))
# * beta - because we need gradient for log(beta)
return np.sum(t_0 + t_1, axis=1) * beta.reshape(-1)
def lower_bound(alpha, beta, L, q):
""" Lower bound
Args:
alpha: ndarray of shape (n_experts).
beta: ndarray of shape (n_problems).
L: ndarray of shape (n_problems, n_experts).
q: ndarray of shape (2, n_problems).
Returns:
single value, number
Tips:
You may use function log_likelihood here
See page 8 of seminar, the fourth formula for details
"""
# compute for t = 0 and t = 0
# it can be modified for case when q.shape[0] > 2 for example by simple cycle, but here we have requirement for shape q
t_0 = q[0] * (log_likelihood(alpha, beta, L, np.zeros(L.shape[0])) - np.log(0.5))
t_1 = q[1] * (log_likelihood(alpha, beta, L, np.ones(L.shape[0])) - np.log(0.5))
code
return np.sum(t_0 + t_1)
Assistant
Here's a rewritten version of the code that includes comments and attempts to optimize for clarity and performance:
simple_voting_border = 0.904
em_border = 0.95
print('\nКомментарий к заданию 2')
print('- Обычное голосование было реализовано через нахождение доли единицы в строке и сравнении этого значения с 0.5: если > 0.5, то 1, иначе 0.')
print('- Качество обычного голосования',
'прошло заданный порог' if simple_voting_accuracy >= simple_voting_border else 'не прошло заданный порог',
f'на {round((simple_voting_accuracy - simple_voting_border) / simple_voting_border,3) * 100}%')
print('- Качество EM алгоритма',
'прошло заданный порог' if em_accuracy >= em_border else 'не прошло заданный порог',
f'на {round((em_accuracy - em_border) / em_border,3) * 100}%')
print(f'EM алгоритм улучшил качество разметки на {round((em_accuracy - simple_voting_accuracy) / simple_voting_accuracy,2) * 100}%')
if q_idx == 0:
print(f'ЕМ алгоритму все-таки не важно, какая метка, поэтому пришлось поменять местами метки и поменять знак у альфы')
simple_voting_erros = dict(zip(*np.unique(y[y != (np.mean(L,axis=1) > 0.5)],return_counts=True)))
em_erros = dict(zip(*np.unique(y[y != (q[q_idx] > 0.5)],return_counts=True)))
print('- Распределение ошибок у обычного голосования:',simple_voting_erros)
print(f'Чаще ошибается на метках {1 if simple_voting_erros[1] > simple_voting_erros[0] else 0}')
print('- Распределение ошибок у EM алгоритма:',em_erros)
print(f'Чаще ошибается на метках {1 if em_erros[1] > em_erros[0] else 0}')
simple_voting_erros_corrected_em = dict(zip(*np.unique(y[(y != (np.mean(L,axis=1) > 0.5)) & (y == (q[q_idx] > 0.5))],return_counts=True)))
print('- Распределение меток там, где ошиблось голосование, но не ошибcя EM алгоритм:', simple_voting_erros_corrected_em)
simple_voting_erros_corrected_em = np.sum(y[(y == (np.mean(L,axis=1) > 0.5)) & (y != (q[q_idx] > 0.5))])
print('- Сколько раз ошибcя EM алгоритм, но не ошиблось голосование:', simple_voting_erros_corrected_em)
Assistant
Here's a refactored and professional version of the provided code. This version includes enhanced readability, added comments, and modularized logic:
python
User
rename main function
Assistant
Certainly! Let's rename the main function to something more descriptive based on its purpose. Since the function orchestrates the evaluation and comparison of different algorithms' accuracy, I'll rename it to evaluate_model_performance:
python
User
Rewrite comments using loguru
Assistant
To utilize the loguru logging library for structured logging and improve the comments in your code, you first need to set up loguru and use its logging methods instead of print statements. Here's how you can integrate loguru for improved logging:
First, ensure that loguru is installed:
bash
pip install loguru
Next, refactor the code to use loguru:
python
User
Rewrite comments in russian language
Assistant
Below is the refactored code with comments rewritten in Russian, while still using loguru for logging:
python
User
also rewrite this code
print('Выкладки к комментарию про интерпретацию коэффициентов альфы')
try to estimate accuracy on good (alpha_i > 2) / mid (abs(alpha_i) < 1) / bad (alpha_i < -2) alphas
print(f'% of good experts due to alpha: {round(np.mean(alpha > 2) * 100,2)}%')
good_alpha = np.where(alpha > 2)[0]
print('Accuracy simple voting with good alpha:', np.mean(y == (np.mean(L[:,good_alpha],axis=1) > 0.5)))
print(f'% of mid experts due to alpha: {round(np.mean(np.abs(alpha) < 1) * 100,2)}%')
mid_alpha = np.where(np.abs(alpha) < 1)[0]
print('Accuracy simple voting with mid alpha:', np.mean(y == (np.mean(L[:,mid_alpha],axis=1) > 0.5)))
print(f'% of bad experts due to alpha: {round(np.mean(alpha < -2) * 100,2)}%')
bad_alpha = np.where(alpha < -2)[0]
print('Accuracy simple voting with bad alpha:', np.mean(y == (np.mean(L[:,bad_alpha],axis=1) > 0.5)))
print('train EM algo only on good experts')
alpha_good, beta_good, q_good = em(L[:,good_alpha],100,plot_process=False)
print('Accuracy EM fitted only on good alpha:',max(np.mean(y == (q_good[1] > 0.5)),np.mean(y == (q_good[0] > 0.5))))
print('train EM algo only on good/mid experts')
alpha_good_mid, beta_good_mid, q_good_mid = em(L[:,np.concatenate([good_alpha,mid_alpha])],100,plot_process=False,)
print('Accuracy EM fitted only on good/mid alpha:',max(np.mean(y == (q_good_mid[1] > 0.5)),np.mean(y == (q_good_mid[0] > 0.5))))
print('train EM algo only on good/bad experts')
alpha_good_bad, beta_good_bad, q_good_bad = em(L[:,np.concatenate([good_alpha,bad_alpha])],100,plot_process=False,)
print('Accuracy EM fitted only on good/bad alpha:',max(np.mean(y == (q_good_bad[1] > 0.5)),np.mean(y == (q_good_bad[0] > 0.5))))
Assistant
Here's a refactored version of your code with improved structure and logging using loguru. This version provides clear segmentations of the analysis based on the performance tiers of experts and includes logging statements instead of print functions:
expert_df = labels_df_melt.groupby('expert')['expert_accuracy'].mean().sort_index().reset_index()
expert_df['alpha'] = alpha
expert_df['difference from simple voting accuracy'] = expert_df['expert_accuracy'] - simple_voting_accuracy
expert_df['difference from em accuracy'] = expert_df['expert_accuracy'] - em_accuracy
print('Table of expert perfomance sorted by alpha (table 1)')
display(expert_df.sort_values('alpha'))
Assistant
Here's a more structured and professional version of the code provided, which prepares datasets for analysis using pandas. The adjustments focus on readability, efficiency, and modular design.
python
import numpy as np
import pandas as pd
from loguru import logger
def prepare_analysis_datasets(alpha, beta, L, y, q, q_idx, simple_voting_accuracy, em_accuracy):
"""Prepare analysis datasets for expert performance measurement."""
logger.info("Preparing datasets for analysis...")
# Initialize experts
experts = np.arange(1, len(alpha) + 1)
# Create DataFrame for labels
labels_df = pd.DataFrame(L, columns=experts)
labels_df['beta'] = beta
labels_df['logbeta'] = np.log(beta)
labels_df['bin_logbeta'] = pd.qcut(labels_df['logbeta'], 10, labels=False)
labels_df['real_label'] = y
labels_df['em_label'] = (q[q_idx] > 0.5).astype(int)
labels_df['em_accuracy'] = (labels_df['em_label'] == labels_df['real_label']).astype(int)
labels_df['voting'] = np.mean(L, axis=1)
labels_df['voting_errors'] = np.sum(L != y[:, None], axis=1)
labels_df['voting_label'] = (labels_df['voting'] > 0.5).astype(int)
labels_df['voting_accuracy'] = (labels_df['voting_label'] == labels_df['real_label']).astype(int)
logger.info("Labels DataFrame created successfully.")
# Transform DataFrame for detailed expert analysis
labels_df_melt = pd.melt(
labels_df,
id_vars=['bin_logbeta', 'logbeta', 'beta', 'real_label'],
value_vars=experts,
var_name='expert',
value_name='expert_pred_label'
)
labels_df_melt['expert_accuracy'] = (labels_df_melt['expert_pred_label'] == labels_df_melt['real_label']).astype(int)
labels_df_melt['alpha'] = labels_df_melt['expert'].map(lambda x: alpha[x-1])
labels_df_melt['good_expert'] = labels_df_melt['alpha'].apply(lambda x: 1 if x >= 0 else 0)
logger.info("Expanded labels DataFrame created for expert analysis.")
# Create a summary DataFrame for expert performance
expert_df = labels_df_melt.groupby('expert')['expert_accuracy'].mean().reset_index()
expert_df['alpha'] = alpha
expert_df['difference_from_simple_voting'] = expert_df['expert_accuracy'] - simple_voting_accuracy
expert_df['difference_from_em_accuracy'] = expert_df['expert_accuracy'] - em_accuracy
logger.info("Expert performance table created.")
# Sort and display the expert performance table
sorted_expert_df = expert_df.sort_values('alpha')
logger.info("Table of expert performance sorted by alpha:")
return sorted_expert_df
# Example call to function (assumptions about 'alpha', 'beta', 'L', 'y', 'q', 'q_idx', 'simple_voting_accuracy', 'em_accuracy' being defined)
# sorted_expert_df = prepare_analysis_datasets(alpha, beta, L, y, q, q_idx, simple_voting_accuracy, em_accuracy)
# display(sorted_expert_df) # This line can be used in environments like Jupyter Notebook
User
rewrite this code
sns.catplot(data=labels_df,x='voting_errors', hue='real_label',kind='count',aspect=1.5)
plt.title('Distribution of count errors in voting depending on real label (plot 1)')
Assistant
Here's a refactored version of your code snippet, improving clarity and structure while still using seaborn for visualization:
python
import seaborn as sns
import matplotlib.pyplot as plt
def plot_voting_errors_distribution(labels_df):
"""
Plot the distribution of voting errors depending on the real label.
Args:
labels_df (pd.DataFrame): DataFrame containing voting errors and real labels.
"""
# Create a categorical plot showing the count of voting errors segmented by real labels
sns.catplot(data=labels_df, x='voting_errors', hue='real_label', kind='count', aspect=1.5)
# Set the plot title to describe what the plot represents
plt.title('Distribution of Voting Errors by Real Label (Plot 1)')
# Display the plot
plt.show()
# Example call to function assuming 'labels_df' is a predefined DataFrame
# plot_voting_errors_distribution(labels_df)
Explanation:
Function Encapsulation: The plotting code is encapsulated into a function plot_voting_errors_distribution to promote reusability and encapsulation.
Documentation: A docstring is provided for the function to describe its purpose and to clarify the expected input.
Modular Structure: The plot setup inside a function allows easy invocation with different DataFrames, enhancing flexibility.
Function Call Example: Provided a commented-out example of how to call this function, assuming labels_df is already defined.
General Improvements: Maintained clarity and readability, with minimal inline comments as the function should be self-explanatory through its arguments and title.
By encapsulating the plotting logic within a function, the code gains better organization, allowing for easier maintenance and adaptability in larger code bases.
import numpy as np
from scipy.special import expit, logsumexp, softplus
# Calculate the posterior distribution over true labels z given observed labels L, expertise alpha, and difficulty beta
def posterior(alpha, beta, L):
""" Compute posterior probability over true labels z given parameters.
Args:
alpha (ndarray): Expertise levels of shape (n_experts).
beta (ndarray): Difficulty levels of shape (n_problems).
L (ndarray): Observed labels of shape (n_problems, n_experts).
Returns:
ndarray: Probabilities of shape (2, n_problems) for z=0 and z=1.
"""
# Compute log-likelihoods for z = 0 and z = 1
log_likelihood_z0 = log_likelihood(alpha, beta, L, np.zeros(L.shape[0]))
log_likelihood_z1 = log_likelihood(alpha, beta, L, np.ones(L.shape[0]))
# Stack log-likelihoods vertically to form a 2-row array
log_likelihood_z = np.vstack([log_likelihood_z0, log_likelihood_z1])
# Return normalized probabilities using log-sum-exp for numerical stability
return np.exp(log_likelihood_z - logsumexp(log_likelihood_z, axis=0))
# Compute the log-likelihood of observed data given parameters and possible true label z
def log_likelihood(alpha, beta, L, z):
""" Compute log-likelihood of observed labels given true label predictions.
Args:
alpha (ndarray): Expertise levels of shape (n_experts).
beta (ndarray): Difficulty levels of shape (n_problems).
L (ndarray): Observed labels of shape (n_problems, n_experts).
z (ndarray): Assumed true labels of shape (n_problems,).
Returns:
ndarray: Log-likelihood values of shape (n_problems,).
"""
# Reshape for broadcasting
z, beta = z[:, None], beta[:, None]
# Indicator matrix where each entry is L_ij == z_i
indicators = (L == z)
# Calculate the log-likelihood
return np.log(0.5) + np.sum(indicators * -softplus(-beta * alpha) +
(~indicators) * -softplus(beta * alpha), axis=1)
# Compute gradient of the lower bound with respect to alpha
def alpha_grad_lb(alpha, beta, L, q):
""" Compute gradient of lower bound with respect to alpha.
Args:
alpha (ndarray): Expertise levels of shape (n_experts).
beta (ndarray): Difficulty levels of shape (n_problems).
L (ndarray): Observed labels of shape (n_problems, n_experts).
q (ndarray): Posterior probabilities of shape (2, n_problems).
Returns:
ndarray: Gradient values of shape (n_experts,).
"""
beta = beta[:, None] # Reshape for broadcasting
indicators = (L == 0)
# Compute terms for gradient calculation
t_0 = q[0][:, None] * beta * (indicators * expit(-beta * alpha) - (~indicators) * expit(beta * alpha))
t_1 = q[1][:, None] * beta * ((~indicators) * expit(-beta * alpha) - indicators * expit(beta * alpha))
# Sum results along problems dimension to obtain the gradient
return np.sum(t_0 + t_1, axis=0)
# Compute gradient of the lower bound with respect to log(beta)
def logbeta_grad_lb(alpha, beta, L, q):
""" Compute gradient of lower bound with respect to log(beta).
Args:
alpha (ndarray): Expertise levels of shape (n_experts).
beta (ndarray): Difficulty levels of shape (n_problems).
L (ndarray): Observed labels of shape (n_problems, n_experts).
q (ndarray): Posterior probabilities of shape (2, n_problems).
Returns:
ndarray: Gradient values of shape (n_problems,).
"""
beta = beta[:, None]
indicators = (L == 0)
# Compute terms for gradient calculation
t_0 = q[0][:, None] * alpha * (indicators * expit(-beta * alpha) - (~indicators) * expit(beta * alpha))
t_1 = q[1][:, None] * alpha * ((~indicators) * expit(-beta * alpha) - indicators * expit(beta * alpha))
# Multiply by beta and reshape to return the gradient
return np.sum(t_0 + t_1, axis=1) * beta.flatten()
# Calculate the lower bound of the log-likelihood given posterior probabilities
def lower_bound(alpha, beta, L, q):
""" Compute the lower bound of the log-likelihood.
Args:
alpha (ndarray): Expertise levels of shape (n_experts).
beta (ndarray): Difficulty levels of shape (n_problems).
L (ndarray): Observed labels of shape (n_problems, n_experts).
q (ndarray): Posterior probabilities of shape (2, n_problems).
Returns:
float: Lower bound value of the log-likelihood.
"""
# Compute terms of the lower bound
t_0 = q[0] * (log_likelihood(alpha, beta, L, np.zeros(L.shape[0])) - np.log(0.5))
t_1 = q[1] * (log_likelihood(alpha, beta, L, np.ones(L.shape[0])) - np.log(0.5))
# Sum the terms to obtain the lower bound
return np.sum(t_0 + t_1)
Key Changes:
Clarity and Readability: The code has been reformatted and comments have been added to explain the purpose of each function and significant lines of code.
Broadcasting: Reshape operations have been clarified in comments, ensuring the code is broadcasting-aware.
Simpler Logic: Removed redundant logic by directly using Python's logical operators and improved variable naming for readability.
This refactored version should be easier to understand and maintain. If further optimization is necessary, consider profiling the code to identify the most time-consuming parts and focus on those areas.
Improvements:
Naming Consistency: Function names and variable names have been made more descriptive and consistent with Python naming conventions. For example, em is renamed to em_algorithm, and lr to learning_rate.
Encapsulation: Wrapped the logic in a clear function that describes its role (em_algorithm). Added docstrings with descriptions for function arguments and return values.
Progress Management: Updated conditionals for the iterator for improved clarity and set a descriptive progress bar.
Plotting: Added plt.figure() for better plotting context. Used plt.show() to explicitly display plots.
Structure: Cleaned up inline comments to improve readability and structured the main loop to clearly distinguish between E-step and M-step operations.
This refactoring provides a clearer, more maintainable, and more expressive script while maintaining the original functionality.
import numpy as np
def main():
# Load true labels
true_labels = np.load('y.npy')
print(f'True labels shape: {true_labels.shape}')
# Calculate Simple Voting Accuracy
voting_threshold = 0.5
simple_voting_preds = np.mean(L, axis=1) > voting_threshold
simple_voting_accuracy = np.mean(true_labels == simple_voting_preds)
print(f'Accuracy of Simple Voting: {simple_voting_accuracy}')
# Calculate EM Accuracy
q_idx = 1
em_predictions = q[q_idx] > voting_threshold
em_accuracy = np.mean(true_labels == em_predictions)
# Adjust for potential sign inversion in alpha
if em_accuracy < voting_threshold:
print('EM accuracy below 0.5; changing sign of alpha.')
q_idx = 0
alpha *= -1
em_predictions = q[q_idx] > voting_threshold
em_accuracy = np.mean(true_labels == em_predictions)
print(f'Accuracy of EM: {em_accuracy}')
# Performance comparison thresholds
simple_voting_threshold = 0.904
em_threshold = 0.95
# Comments on results
print('\nTask 2 Commentary')
print(f"- Simple voting accuracy {'passed' if simple_voting_accuracy >= simple_voting_threshold else 'did not pass'} the threshold by {round((simple_voting_accuracy - simple_voting_threshold) / simple_voting_threshold, 3) * 100 :.1f}%")
print(f"- EM algorithm accuracy {'passed' if em_accuracy >= em_threshold else 'did not pass'} the threshold by {round((em_accuracy - em_threshold) / em_threshold, 3) * 100 :.1f}%")
accuracy_improvement = (em_accuracy - simple_voting_accuracy) / simple_voting_accuracy * 100
print(f"EM algorithm improved labeling quality by {accuracy_improvement:.2f}%")
if q_idx == 0:
print("EM algorithm was indifferent to the label, requiring label swapping and sign change in alpha.")
# Error distribution analysis
analyze_label_errors(true_labels, simple_voting_preds, "Simple Voting")
analyze_label_errors(true_labels, em_predictions, "EM Algorithm")
# Corrections comparison
analyze_corrections(true_labels, simple_voting_preds, em_predictions)
def analyze_label_errors(true_labels, predictions, method_name):
""" Analyze and print error distribution for a given prediction method. """
errors = np.unique(true_labels[true_labels != predictions], return_counts=True)
error_distribution = dict(zip(*errors))
majority_error_label = 1 if error_distribution.get(1, 0) > error_distribution.get(0, 0) else 0
print(f"- {method_name} error distribution: {error_distribution}")
print(f"Most frequent error label: {majority_error_label}")
def analyze_corrections(true_labels, simple_voting_preds, em_predictions):
""" Analyze where simple voting errors were corrected by EM algorithm. """
corrected_indices = (true_labels != simple_voting_preds) & (true_labels == em_predictions)
corrected_errors = np.unique(true_labels[corrected_indices], return_counts=True)
print(f"- Distribution where EM corrects Simple Voting errors: {dict(zip(*corrected_errors))}")
# Analyze EM errors not present in Simple Voting
em_missteps = np.sum(simple_voting_preds[true_labels == simple_voting_preds] != em_predictions[true_labels == simple_voting_preds])
print(f"- Occasions where EM algorithm errs but Simple Voting does not: {em_missteps}")
if __name__ == "__main__":
main()
Key Changes:
Modularization: The analysis and the main logic are separated into functions.
Descriptive Variable Naming: More descriptive variable names were used for clarity.
Error Analysis: Separated error analysis into a helper function to reduce redundancy and improve readability.
Output and Plot Improvements: Enhanced output formatting for more informative messages and did not include any GUI operations, maintaining focus on command-line output.
Control Flow and Logic: Streamlined logic and improved flow control, especially around handling the condition where the EM accuracy is initially below the threshold.
These changes aim to create more maintainable, readable, and expressive code, following Python best practices.
import numpy as np
def evaluate_model_performance():
""" Evaluate and compare the accuracy of different prediction models. """
# Load true labels
true_labels = np.load('y.npy')
print(f'True labels shape: {true_labels.shape}')
# Calculate Simple Voting Accuracy
voting_threshold = 0.5
simple_voting_preds = np.mean(L, axis=1) > voting_threshold
simple_voting_accuracy = np.mean(true_labels == simple_voting_preds)
print(f'Accuracy of Simple Voting: {simple_voting_accuracy}')
# Calculate EM Accuracy
q_idx = 1
em_predictions = q[q_idx] > voting_threshold
em_accuracy = np.mean(true_labels == em_predictions)
# Adjust for potential sign inversion in alpha
if em_accuracy < voting_threshold:
print('EM accuracy below 0.5; changing sign of alpha.')
q_idx = 0
alpha *= -1
em_predictions = q[q_idx] > voting_threshold
em_accuracy = np.mean(true_labels == em_predictions)
print(f'Accuracy of EM: {em_accuracy}')
# Performance comparison thresholds
simple_voting_threshold = 0.904
em_threshold = 0.95
# Comments on results
print('\nTask 2 Commentary')
print(f"- Simple voting accuracy {'passed' if simple_voting_accuracy >= simple_voting_threshold else 'did not pass'} the threshold by {round((simple_voting_accuracy - simple_voting_threshold) / simple_voting_threshold, 3) * 100 :.1f}%")
print(f"- EM algorithm accuracy {'passed' if em_accuracy >= em_threshold else 'did not pass'} the threshold by {round((em_accuracy - em_threshold) / em_threshold, 3) * 100 :.1f}%")
accuracy_improvement = (em_accuracy - simple_voting_accuracy) / simple_voting_accuracy * 100
print(f"EM algorithm improved labeling quality by {accuracy_improvement:.2f}%")
if q_idx == 0:
print("EM algorithm was indifferent to the label, requiring label swapping and sign change in alpha.")
# Error distribution analysis
analyze_label_errors(true_labels, simple_voting_preds, "Simple Voting")
analyze_label_errors(true_labels, em_predictions, "EM Algorithm")
# Corrections comparison
analyze_corrections(true_labels, simple_voting_preds, em_predictions)
def analyze_label_errors(true_labels, predictions, method_name):
""" Analyze and print error distribution for a given prediction method. """
errors = np.unique(true_labels[true_labels != predictions], return_counts=True)
error_distribution = dict(zip(*errors))
majority_error_label = 1 if error_distribution.get(1, 0) > error_distribution.get(0, 0) else 0
print(f"- {method_name} error distribution: {error_distribution}")
print(f"Most frequent error label: {majority_error_label}")
def analyze_corrections(true_labels, simple_voting_preds, em_predictions):
""" Analyze where simple voting errors were corrected by EM algorithm. """
corrected_indices = (true_labels != simple_voting_preds) & (true_labels == em_predictions)
corrected_errors = np.unique(true_labels[corrected_indices], return_counts=True)
print(f"- Distribution where EM corrects Simple Voting errors: {dict(zip(*corrected_errors))}")
# Analyze EM errors not present in Simple Voting
em_missteps = np.sum(simple_voting_preds[true_labels == simple_voting_preds] != em_predictions[true_labels == simple_voting_preds])
print(f"- Occasions where EM algorithm errs but Simple Voting does not: {em_missteps}")
if __name__ == "__main__":
evaluate_model_performance()
This new name, evaluate_model_performance, describes purposefully what the function does and increases code readability.
import numpy as np
from loguru import logger
def evaluate_model_performance():
""" Evaluate and compare the accuracy of different prediction models. """
# Load true labels
true_labels = np.load('y.npy')
logger.info(f'True labels shape: {true_labels.shape}')
# Calculate Simple Voting Accuracy
voting_threshold = 0.5
simple_voting_preds = np.mean(L, axis=1) > voting_threshold
simple_voting_accuracy = np.mean(true_labels == simple_voting_preds)
logger.info(f'Accuracy of Simple Voting: {simple_voting_accuracy}')
# Calculate EM Accuracy
q_idx = 1
em_predictions = q[q_idx] > voting_threshold
em_accuracy = np.mean(true_labels == em_predictions)
# Adjust for potential sign inversion in alpha
if em_accuracy < voting_threshold:
logger.warning('EM accuracy below 0.5; changing sign of alpha.')
q_idx = 0
alpha *= -1
em_predictions = q[q_idx] > voting_threshold
em_accuracy = np.mean(true_labels == em_predictions)
logger.info(f'Accuracy of EM: {em_accuracy}')
# Performance comparison thresholds
simple_voting_threshold = 0.904
em_threshold = 0.95
# Comments on results
logger.info('\nTask 2 Commentary')
logger.info("- Simple voting accuracy {} the threshold by {:.1f}%",
'passed' if simple_voting_accuracy >= simple_voting_threshold else 'did not pass',
(simple_voting_accuracy - simple_voting_threshold) / simple_voting_threshold * 100)
logger.info("- EM algorithm accuracy {} the threshold by {:.1f}%",
'passed' if em_accuracy >= em_threshold else 'did not pass',
(em_accuracy - em_threshold) / em_threshold * 100)
accuracy_improvement = (em_accuracy - simple_voting_accuracy) / simple_voting_accuracy * 100
logger.info("EM algorithm improved labeling quality by {:.2f}%", accuracy_improvement)
if q_idx == 0:
logger.info("EM algorithm was indifferent to the label, requiring label swapping and sign change in alpha.")
# Error distribution analysis
analyze_label_errors(true_labels, simple_voting_preds, "Simple Voting")
analyze_label_errors(true_labels, em_predictions, "EM Algorithm")
# Corrections comparison
analyze_corrections(true_labels, simple_voting_preds, em_predictions)
def analyze_label_errors(true_labels, predictions, method_name):
""" Analyze and print error distribution for a given prediction method. """
errors = np.unique(true_labels[true_labels != predictions], return_counts=True)
error_distribution = dict(zip(*errors))
majority_error_label = 1 if error_distribution.get(1, 0) > error_distribution.get(0, 0) else 0
logger.info("- {} error distribution: {}", method_name, error_distribution)
logger.info("Most frequent error label: {}", majority_error_label)
def analyze_corrections(true_labels, simple_voting_preds, em_predictions):
""" Analyze where simple voting errors were corrected by EM algorithm. """
corrected_indices = (true_labels != simple_voting_preds) & (true_labels == em_predictions)
corrected_errors = np.unique(true_labels[corrected_indices], return_counts=True)
logger.info("- Distribution where EM corrects Simple Voting errors: {}", dict(zip(*corrected_errors)))
# Analyze EM errors not present in Simple Voting
em_missteps = np.sum(simple_voting_preds[true_labels == simple_voting_preds] != em_predictions[true_labels == simple_voting_preds])
logger.info("- Occasions where EM algorithm errs but Simple Voting does not: {}", em_missteps)
if __name__ == "__main__":
evaluate_model_performance()
Key Points:
Logging Instead of Printing: Use logger.info for regular information messages, and logger.warning for any potential issues (like the EM accuracy being below 0.5).
Formatted Logging: The use of {} in logger's methods allows for clean and readable formatted logging messages.
Structured Logs: Logs can be configured further with loguru to add more context, such as timestamps or log levels, without modifying the messages directly.
This approach provides a more robust and scalable way to handle logging, especially useful in larger applications where you might want to integrate log files or other logging sinks.
import numpy as np
from loguru import logger
def evaluate_model_performance():
""" Оценка и сравнение точности различных прогнозных моделей. """
# Загрузка истинных меток
true_labels = np.load('y.npy')
logger.info(f'Форма истинных меток: {true_labels.shape}')
# Вычисление точности простого голосования
voting_threshold = 0.5
simple_voting_preds = np.mean(L, axis=1) > voting_threshold
simple_voting_accuracy = np.mean(true_labels == simple_voting_preds)
logger.info(f'Точность простого голосования: {simple_voting_accuracy}')
# Вычисление точности EM алгоритма
q_idx = 1
em_predictions = q[q_idx] > voting_threshold
em_accuracy = np.mean(true_labels == em_predictions)
# Корректировка для возможной инверсии знака в alpha
if em_accuracy < voting_threshold:
logger.warning('Точность EM алгоритма ниже 0.5; изменение знака alpha.')
q_idx = 0
alpha *= -1
em_predictions = q[q_idx] > voting_threshold
em_accuracy = np.mean(true_labels == em_predictions)
logger.info(f'Точность EM алгоритма: {em_accuracy}')
# Пороговые значения для сравнения производительности
simple_voting_threshold = 0.904
em_threshold = 0.95
# Комментарии к результатам
logger.info('\nКомментарий к заданию 2')
logger.info("- Точность простого голосования {} порог на {:.1f}%",
'превысила' if simple_voting_accuracy >= simple_voting_threshold else 'не превысила',
(simple_voting_accuracy - simple_voting_threshold) / simple_voting_threshold * 100)
logger.info("- Точность EM алгоритма {} порог на {:.1f}%",
'превысила' if em_accuracy >= em_threshold else 'не превысила',
(em_accuracy - em_threshold) / em_threshold * 100)
accuracy_improvement = (em_accuracy - simple_voting_accuracy) / simple_voting_accuracy * 100
logger.info("EM алгоритм улучшил качество разметки на {:.2f}%", accuracy_improvement)
if q_idx == 0:
logger.info("EM алгоритм оказался безразличен к метке, потребовалась замена метки и изменение знака alpha.")
# Анализ распределения ошибок
analyze_label_errors(true_labels, simple_voting_preds, "Простое голосование")
analyze_label_errors(true_labels, em_predictions, "EM алгоритм")
# Сравнение корректировок
analyze_corrections(true_labels, simple_voting_preds, em_predictions)
def analyze_label_errors(true_labels, predictions, method_name):
""" Анализ и вывод распределения ошибок для выбранного метода прогнозирования. """
errors = np.unique(true_labels[true_labels != predictions], return_counts=True)
error_distribution = dict(zip(*errors))
majority_error_label = 1 if error_distribution.get(1, 0) > error_distribution.get(0, 0) else 0
logger.info("- Распределение ошибок {}: {}", method_name, error_distribution)
logger.info("Чаще всего ошибается на метке: {}", majority_error_label)
def analyze_corrections(true_labels, simple_voting_preds, em_predictions):
""" Анализ исправлений ошибок простого голосования, выполненных EM алгоритмом. """
corrected_indices = (true_labels != simple_voting_preds) & (true_labels == em_predictions)
corrected_errors = np.unique(true_labels[corrected_indices], return_counts=True)
logger.info("- Распределение, где EM исправляет ошибки простого голосования: {}", dict(zip(*corrected_errors)))
# Анализ ошибок EM, отсутствующих в простом голосовании
em_missteps = np.sum(simple_voting_preds[true_labels == simple_voting_preds] != em_predictions[true_labels == simple_voting_preds])
logger.info("- Случаи, когда EM алгоритм ошибается, а простое голосование нет: {}", em_missteps)
if __name__ == "__main__":
evaluate_model_performance()
Ключевые моменты:
Комментарии на русском: Все комментарии переведены на русский язык для удобства русскоязычных разработчиков.
Логирование с использованием loguru: Используется для вывода информации и предупреждений, что делает код более чистым и структурированным.
import numpy as np
from loguru import logger
def evaluate_expert_quality():
""" Оценка качества экспертов на основе коэффициентов альфа. """
logger.info('Анализ интерпретации коэффициентов альфы')
# Вычисление точности для хороших (alpha_i > 2), средних (abs(alpha_i) < 1) и плохих (alpha_i < -2) экспертов
good_alpha_threshold = 2
mid_alpha_threshold = 1
bad_alpha_threshold = -2
# Хорошие эксперты
good_alpha_indices = np.where(alpha > good_alpha_threshold)[0]
good_expert_percentage = np.mean(alpha > good_alpha_threshold) * 100
logger.info('Процент хороших экспертов: {:.2f}%', good_expert_percentage)
good_alpha_voting_accuracy = np.mean(y == (np.mean(L[:, good_alpha_indices], axis=1) > 0.5))
logger.info('Точность простого голосования хороших экспертов: {:.2f}', good_alpha_voting_accuracy)
# Средние эксперты
mid_alpha_indices = np.where(np.abs(alpha) < mid_alpha_threshold)[0]
mid_expert_percentage = np.mean(np.abs(alpha) < mid_alpha_threshold) * 100
logger.info('Процент средних экспертов: {:.2f}%', mid_expert_percentage)
mid_alpha_voting_accuracy = np.mean(y == (np.mean(L[:, mid_alpha_indices], axis=1) > 0.5))
logger.info('Точность простого голосования средних экспертов: {:.2f}', mid_alpha_voting_accuracy)
# Совместная оценка хороших и средних экспертов
combined_alpha_indices = np.concatenate([good_alpha_indices, mid_alpha_indices])
combined_alpha_voting_accuracy = np.mean(y == (np.mean(L[:, combined_alpha_indices], axis=1) > 0.5))
logger.info('Точность простого голосования хороших/средних экспертов: {:.2f}', combined_alpha_voting_accuracy)
# Плохие эксперты
bad_alpha_indices = np.where(alpha < bad_alpha_threshold)[0]
bad_expert_percentage = np.mean(alpha < bad_alpha_threshold) * 100
logger.info('Процент плохих экспертов: {:.2f}%', bad_expert_percentage)
bad_alpha_voting_accuracy = np.mean(y == (np.mean(L[:, bad_alpha_indices], axis=1) > 0.5))
logger.info('Точность простого голосования плохих экспертов: {:.2f}', bad_alpha_voting_accuracy)
# Обучение EM алгоритма только на хороших экспертах
logger.info('Тренировка EM алгоритма только на хороших экспертах')
alpha_good, beta_good, q_good = em(L[:, good_alpha_indices], 100, plot_process=False)
em_good_accuracy = max(np.mean(y == (q_good[1] > 0.5)), np.mean(y == (q_good[0] > 0.5)))
logger.info('Точность EM алгоритма, натренированного на хороших экспертах: {:.2f}', em_good_accuracy)
# Обучение EM алгоритма на хороших/средних экспертах
logger.info('Тренировка EM алгоритма на хороших и средних экспертах')
alpha_good_mid, beta_good_mid, q_good_mid = em(L[:, combined_alpha_indices], 100, plot_process=False)
em_good_mid_accuracy = max(np.mean(y == (q_good_mid[1] > 0.5)), np.mean(y == (q_good_mid[0] > 0.5)))
logger.info('Точность EM алгоритма, натренированного на хороших/средних экспертах: {:.2f}', em_good_mid_accuracy)
# Обучение EM алгоритма на хороших/плохих экспертах
logger.info('Тренировка EM алгоритма на хороших и плохих экспертах')
alpha_good_bad, beta_good_bad, q_good_bad = em(L[:, np.concatenate([good_alpha_indices, bad_alpha_indices])], 100, plot_process=False)
em_good_bad_accuracy = max(np.mean(y == (q_good_bad[1] > 0.5)), np.mean(y == (q_good_bad[0] > 0.5)))
logger.info('Точность EM алгоритма, натренированного на хороших/плохих экспертах: {:.2f}', em_good_bad_accuracy)
if __name__ == "__main__":
evaluate_expert_quality()
Key Changes:
Logging: Converted all print statements to logger.info calls for structured logging.
Refactoring: Defined constants for thresholds and variables to improve readability and reusability.
Modularity: Encapsulated functionality in a single function that can be easily reused or expanded.
Russian Comments: Added comments in Russian for clarity and documentation inline with the logic.
The use of loguru not only standardizes the output but also provides capabilities to easily redirect logs to files or other sinks.
Changes and Improvements:
Function Encapsulation: The functionality is encapsulated in a function prepare_datasets_for_analysis for easier reuse.
Logging with Loguru: Replaced print statements with logger.info() for informational logging and logger.debug() to display the data. This method allows for scalable logging practices, which are helpful in large projects.
Descriptive Functions: The function is clearly defined with comments describing each step.
Code Clarity: Improved readability by adding spaces and comments and by using functions like apply with lambda for pandas operations.
Variable Naming: Column names have been adjusted to use snake_case for consistency and readability.
Remove Display Dependency: The return of the DataFrame allows for flexibility; you can use display(sorted_expert_df) in interactive environments, like Jupyter Notebook, or further process it in other contexts. If you prefer to keep using display, you can uncomment it in an appropriate environment.
Key Improvements:
Function Encapsulation: The code is encapsulated into a function prepare_analysis_datasets for better modularity and reuse.
Readability: Improved readability by using consistent code formatting and descriptive variable names.
Logging: Used loguru for informational logging instead of print statements, facilitating better log management and potential future logging configuration.
Vectorized Operations: Operations are vectorized where possible, such as column computations, preventing the need for explicit loops and resulting in more efficient code.
Code Comments: Integrated logging statements provide a running commentary on the progress of dataset preparation, substituting for traditional comments.
Safe Indexing: Changed to 1-based indexing to reflect experts in pandas, treating each value as a standalone expert number.
This refactor not only enhances the readability and structure of the code but also sets it up for easier integration and extension in larger projects.