






import json
import logging
import os
import random
import sys
from dataclasses import dataclass, field
from typing import Optional

import evaluate
import numpy as np
import torch
from datasets import load_dataset
from huggingface_hub import hf_hub_download
from PIL import Image
from torch import nn
from torchvision import transforms
from torchvision.transforms import functional

import transformers
from transformers import (
    AutoConfig,
    AutoImageProcessor,
    AutoModelForSemanticSegmentation,
    HfArgumentParser,
    Trainer,
    TrainingArguments,
    default_data_collator,
)
from transformers.trainer_utils import get_last_checkpoint
from transformers.utils import check_min_version, send_example_telemetry
from transformers.utils.versions import require_version
lowercase  							= logging.getLogger(__name__)

# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
check_min_version("4.31.0")

require_version("datasets>=2.0.0", "To fix: pip install -r examples/pytorch/semantic-segmentation/requirements.txt")





def 						__UpperCAmelCase      (					a_							,					a_							,					a_=0):
							snake_case_           =							(size, size) if isinstance(a_							,					a_) else size
							snake_case_      ,		snake_case_           =							img.size
							snake_case_           =							size[1] - original_height if original_height < size[1] else 0
							snake_case_           =							size[0] - original_width if original_width < size[0] else 0
							snake_case_           =							functional.pad(a_							,					(0, 0, pad_width, pad_height)							,					fill=a_)
							return img




class 			UpperCamelCase_				:



	'''simple docstring'''




	def __init__(	self	,      a )	->   List[Any]:
								snake_case_           =							transforms






	def __call__(	self	,      a	,      a )	->   Optional[Any]:
								for t in self.transforms:
															snake_case_      ,		snake_case_           =							t(a	,      a )
								return image, target






class 			UpperCamelCase_				:



	'''simple docstring'''




	def __init__(	self )	->   Any:
								pass






	def __call__(	self	,      a	,      a )	->   Any:
								return image, target






class 			UpperCamelCase_				:



	'''simple docstring'''




	def __init__(	self	,      a )	->   int:
								snake_case_           =							size






	def __call__(	self	,      a	,      a )	->   List[Any]:
								snake_case_           =							functional.resize(a	,      self.size )
								snake_case_           =							functional.resize(a	,      self.size	,      interpolation=transforms.InterpolationMode.NEAREST )
								return image, target






class 			UpperCamelCase_				:



	'''simple docstring'''




	def __init__(	self	,      a	,      a=None )	->   Tuple:
								snake_case_           =							min_size
								if max_size is None:
															snake_case_           =							min_size
								snake_case_           =							max_size






	def __call__(	self	,      a	,      a )	->   Dict:
								snake_case_           =							random.randint(self.min_size	,      self.max_size )
								snake_case_           =							functional.resize(a	,      a )
								snake_case_           =							functional.resize(a	,      a	,      interpolation=transforms.InterpolationMode.NEAREST )
								return image, target






class 			UpperCamelCase_				:



	'''simple docstring'''




	def __init__(	self	,      a )	->   List[Any]:
								snake_case_           =							size if isinstance(a	,      a ) else (size, size)






	def __call__(	self	,      a	,      a )	->   Tuple:
								snake_case_           =							pad_if_smaller(a	,      self.size )
								snake_case_           =							pad_if_smaller(a	,      self.size	,      fill=2_55 )
								snake_case_           =							transforms.RandomCrop.get_params(a	,      self.size )
								snake_case_           =							functional.crop(a	,      *a )
								snake_case_           =							functional.crop(a	,      *a )
								return image, target






class 			UpperCamelCase_				:



	'''simple docstring'''




	def __init__(	self	,      a )	->   int:
								snake_case_           =							flip_prob






	def __call__(	self	,      a	,      a )	->   int:
								if random.random() < self.flip_prob:
															snake_case_           =							functional.hflip(a )
															snake_case_           =							functional.hflip(a )
								return image, target






class 			UpperCamelCase_				:



	'''simple docstring'''




	def __call__(	self	,      a	,      a )	->   str:
								snake_case_           =							functional.pil_to_tensor(a )
								snake_case_           =							torch.as_tensor(np.array(a )	,      dtype=torch.intaa )
								return image, target






class 			UpperCamelCase_				:



	'''simple docstring'''




	def __init__(	self	,      a )	->   Tuple:
								snake_case_           =							dtype






	def __call__(	self	,      a	,      a )	->   Optional[int]:
								snake_case_           =							functional.convert_image_dtype(a	,      self.dtype )
								return image, target






class 			UpperCamelCase_				:



	'''simple docstring'''




	def __init__(	self	,      a	,      a )	->   List[Any]:
								snake_case_           =							mean
								snake_case_           =							std






	def __call__(	self	,      a	,      a )	->   int:
								snake_case_           =							functional.normalize(a	,      mean=self.mean	,      std=self.std )
								return image, target






class 			UpperCamelCase_				:



	'''simple docstring'''




	def __call__(	self	,      a	,      a )	->   Tuple:
								if not isinstance(a	,      np.ndarray ):
															snake_case_           =							np.array(a ).astype(np.uinta )
								# avoid using underflow conversion
								snake_case_           =							2_55
								snake_case_           =							target - 1
								snake_case_           =							2_55

								snake_case_           =							Image.fromarray(a )
								return image, target






@dataclass
class 			UpperCamelCase_				:



	'''simple docstring'''




	lowerCAmelCase													=			field(
	    default='''segments/sidewalk-semantic'''	, metadata={
	        '''help''': '''Name of a dataset from the hub (could be your own, possibly private dataset hosted on the hub).'''
	    }	, )
	lowerCAmelCase													=			field(
	    default=snake_case_	, metadata={'''help''': '''The configuration name of the dataset to use (via the datasets library).'''}    )
	lowerCAmelCase													=			field(
	    default=0.15	, metadata={'''help''': '''Percent to split off of train for validation.'''}    )
	lowerCAmelCase													=			field(
	    default=snake_case_	, metadata={
	        '''help''': (
	            '''For debugging purposes or quicker training, truncate the number of training examples to this '''
	            '''value if set.'''
	        )
	    }	, )
	lowerCAmelCase													=			field(
	    default=snake_case_	, metadata={
	        '''help''': (
	            '''For debugging purposes or quicker training, truncate the number of evaluation examples to this '''
	            '''value if set.'''
	        )
	    }	, )
	lowerCAmelCase													=			field(
	    default=snake_case_	, metadata={'''help''': '''Whether or not to reduce all labels by 1 and replace background by 255.'''}	, )




	def 							_UpperCamelCase      (	self )	->   List[str]:
								if self.dataset_name is None and (self.train_dir is None and self.validation_dir is None):
															raise ValueError(
															    'You must specify either a dataset name from the hub or a train and/or validation directory.' )






@dataclass
class 			UpperCamelCase_				:



	'''simple docstring'''




	lowerCAmelCase													=			field(
	    default='''nvidia/mit-b0'''	, metadata={'''help''': '''Path to pretrained model or model identifier from huggingface.co/models'''}	, )
	lowerCAmelCase													=			field(
	    default=snake_case_	, metadata={'''help''': '''Pretrained config name or path if not the same as model_name'''}    )
	lowerCAmelCase													=			field(
	    default=snake_case_	, metadata={'''help''': '''Where do you want to store the pretrained models downloaded from s3'''}    )
	lowerCAmelCase													=			field(
	    default='''main'''	, metadata={'''help''': '''The specific model version to use (can be a branch name, tag name or commit id).'''}	, )
	lowerCAmelCase													=			field(default=snake_case_	, metadata={'''help''': '''Name or path of preprocessor config.'''}    )
	lowerCAmelCase													=			field(
	    default=snake_case_	, metadata={
	        '''help''': (
	            '''Will use the token generated when running `huggingface-cli login` (necessary to use this script '''
	            '''with private models).'''
	        )
	    }	, )






def 						__UpperCAmelCase      (					):
							# See all possible arguments in src/transformers/training_args.py
							# or by passing the --help flag to this script.
							# We now keep distinct sets of args, for a cleaner separation of concerns.

							snake_case_           =							HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments))
							if len(sys.argv) == 2 and sys.argv[1].endswith('.json'):
														# If we pass only one argument to the script and it's the path to a json file,
														# let's parse it to get our arguments.
														snake_case_      ,		snake_case_      ,		snake_case_           =							parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]))
							else:
														snake_case_      ,		snake_case_      ,		snake_case_           =							parser.parse_args_into_dataclasses()

							# Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
							# information sent is the one passed as arguments along with your Python/PyTorch versions.
							send_example_telemetry('run_semantic_segmentation'							,					a_							,					a_)

							# Setup logging
							logging.basicConfig(
							    format='%(asctime)s - %(levelname)s - %(name)s - %(message)s'							,					datefmt='%m/%d/%Y %H:%M:%S'							,					handlers=[logging.StreamHandler(sys.stdout)]							,					)

							if training_args.should_log:
														# The default of training_args.log_level is passive, so we set log level at info here to have that default.
														transformers.utils.logging.set_verbosity_info()

							snake_case_           =							training_args.get_process_log_level()
							logger.setLevel(a_)
							transformers.utils.logging.set_verbosity(a_)
							transformers.utils.logging.enable_default_handler()
							transformers.utils.logging.enable_explicit_format()

							# Log on each process the small summary:
							logger.warning(
							    f'''Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}'''
							    + f'''distributed training: {bool(training_args.local_rank != -1)}, 16-bits training: {training_args.fpaa}''')
							logger.info(f'''Training/evaluation parameters {training_args}''')

							# Detecting last checkpoint.
							snake_case_           =							None
							if os.path.isdir(training_args.output_dir) and training_args.do_train and not training_args.overwrite_output_dir:
														snake_case_           =							get_last_checkpoint(training_args.output_dir)
														if last_checkpoint is None and len(os.listdir(training_args.output_dir)) > 0:
																					raise ValueError(
																					    f'''Output directory ({training_args.output_dir}) already exists and is not empty. '''
																					    'Use --overwrite_output_dir to overcome.')
														elif last_checkpoint is not None and training_args.resume_from_checkpoint is None:
																					logger.info(
																					    f'''Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change '''
																					    'the `--output_dir` or add `--overwrite_output_dir` to train from scratch.')

    # Load dataset
    # In distributed training, the load_dataset function guarantees that only one local process can concurrently
    # download the dataset.
    # TODO support datasets from local folders
							snake_case_           =							load_dataset(data_args.dataset_name							,					cache_dir=model_args.cache_dir)

							# Rename column names to standardized names (only "image" and "label" need to be present)
							if "pixel_values" in dataset["train"].column_names:
														snake_case_           =							dataset.rename_columns({'pixel_values': 'image'})
							if "annotation" in dataset["train"].column_names:
														snake_case_           =							dataset.rename_columns({'annotation': 'label'})

							# If we don't have a validation split, split off a percentage of train as validation.
							snake_case_           =							None if 'validation' in dataset.keys() else data_args.train_val_split
							if isinstance(data_args.train_val_split							,					a_) and data_args.train_val_split > 0.0:
														snake_case_           =							dataset['train'].train_test_split(data_args.train_val_split)
														snake_case_           =							split['train']
														snake_case_           =							split['test']

							# Prepare label mappings.
							# We'll include these in the model's config to get human readable labels in the Inference API.
							if data_args.dataset_name == "scene_parse_150":
														snake_case_           =							'huggingface/label-files'
														snake_case_           =							'ade20k-id2label.json'
							else:
														snake_case_           =							data_args.dataset_name
														snake_case_           =							'id2label.json'
							snake_case_           =							json.load(open(hf_hub_download(a_							,					a_							,					repo_type='dataset')							,					'r'))
							snake_case_           =							{int(a_): v for k, v in idalabel.items()}
							snake_case_           =							{v: str(a_) for k, v in idalabel.items()}

							# Load the mean IoU metric from the datasets package
							snake_case_           =							evaluate.load('mean_iou')

							# Define our compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with a
							# predictions and label_ids field) and has to return a dictionary string to float.
							@torch.no_grad()
							def compute_metrics(a_):
														snake_case_      ,		snake_case_           =							eval_pred
														snake_case_           =							torch.from_numpy(a_)
														# scale the logits to the size of the label
														snake_case_           =							nn.functional.interpolate(
														    a_							,					size=labels.shape[-2:]							,					mode='bilinear'							,					align_corners=a_							,					).argmax(dim=1)

														snake_case_           =							logits_tensor.detach().cpu().numpy()
														snake_case_           =							metric.compute(
														    predictions=a_							,					references=a_							,					num_labels=len(a_)							,					ignore_index=0							,					reduce_labels=image_processor.do_reduce_labels							,					)
														# add per category metrics as individual key-value pairs
														snake_case_           =							metrics.pop('per_category_accuracy').tolist()
														snake_case_           =							metrics.pop('per_category_iou').tolist()

														metrics.update({f'''accuracy_{idalabel[i]}''': v for i, v in enumerate(a_)})
														metrics.update({f'''iou_{idalabel[i]}''': v for i, v in enumerate(a_)})

														return metrics

							snake_case_           =							AutoConfig.from_pretrained(
							    model_args.config_name or model_args.model_name_or_path							,					labelaid=a_							,					idalabel=a_							,					cache_dir=model_args.cache_dir							,					revision=model_args.model_revision							,					use_auth_token=True if model_args.use_auth_token else None							,					)
							snake_case_           =							AutoModelForSemanticSegmentation.from_pretrained(
							    model_args.model_name_or_path							,					from_tf=bool('.ckpt' in model_args.model_name_or_path)							,					config=a_							,					cache_dir=model_args.cache_dir							,					revision=model_args.model_revision							,					use_auth_token=True if model_args.use_auth_token else None							,					)
							snake_case_           =							AutoImageProcessor.from_pretrained(
							    model_args.image_processor_name or model_args.model_name_or_path							,					cache_dir=model_args.cache_dir							,					revision=model_args.model_revision							,					use_auth_token=True if model_args.use_auth_token else None							,					)

							# Define torchvision transforms to be applied to each image + target.
							# Not that straightforward in torchvision: https://github.com/pytorch/vision/issues/9
							# Currently based on official torchvision references: https://github.com/pytorch/vision/blob/main/references/segmentation/transforms.py
							if "shortest_edge" in image_processor.size:
														# We instead set the target size as (shortest_edge, shortest_edge) to here to ensure all images are batchable.
														snake_case_           =							(image_processor.size['shortest_edge'], image_processor.size['shortest_edge'])
							else:
														snake_case_           =							(image_processor.size['height'], image_processor.size['width'])
							snake_case_           =							Compose(
							    [
							        ReduceLabels() if data_args.reduce_labels else Identity(),
							        RandomCrop(size=a_),
							        RandomHorizontalFlip(flip_prob=0.5),
							        PILToTensor(),
							        ConvertImageDtype(torch.float),
							        Normalize(mean=image_processor.image_mean							,					std=image_processor.image_std),
							    ])
							# Define torchvision transform to be applied to each image.
							# jitter = ColorJitter(brightness=0.25, contrast=0.25, saturation=0.25, hue=0.1)
							snake_case_           =							Compose(
							    [
							        ReduceLabels() if data_args.reduce_labels else Identity(),
							        Resize(size=a_),
							        PILToTensor(),
							        ConvertImageDtype(torch.float),
							        Normalize(mean=image_processor.image_mean							,					std=image_processor.image_std),
							    ])

							def preprocess_train(a_):
														snake_case_           =							[]
														snake_case_           =							[]
														for image, target in zip(example_batch['image']							,					example_batch['label']):
																					snake_case_      ,		snake_case_           =							train_transforms(image.convert('RGB')							,					a_)
																					pixel_values.append(a_)
																					labels.append(a_)

														snake_case_           =							{}
														snake_case_           =							torch.stack(a_)
														snake_case_           =							torch.stack(a_)

														return encoding

							def preprocess_val(a_):
														snake_case_           =							[]
														snake_case_           =							[]
														for image, target in zip(example_batch['image']							,					example_batch['label']):
																					snake_case_      ,		snake_case_           =							val_transforms(image.convert('RGB')							,					a_)
																					pixel_values.append(a_)
																					labels.append(a_)

														snake_case_           =							{}
														snake_case_           =							torch.stack(a_)
														snake_case_           =							torch.stack(a_)

														return encoding

							if training_args.do_train:
														if "train" not in dataset:
																					raise ValueError('--do_train requires a train dataset')
														if data_args.max_train_samples is not None:
																					snake_case_           =							(
																					    dataset['train'].shuffle(seed=training_args.seed).select(range(data_args.max_train_samples))
																					)
														# Set the training transforms
														dataset["train"].set_transform(a_)

							if training_args.do_eval:
														if "validation" not in dataset:
																					raise ValueError('--do_eval requires a validation dataset')
														if data_args.max_eval_samples is not None:
																					snake_case_           =							(
																					    dataset['validation'].shuffle(seed=training_args.seed).select(range(data_args.max_eval_samples))
																					)
														# Set the validation transforms
														dataset["validation"].set_transform(a_)

							# Initalize our trainer
							snake_case_           =							Trainer(
							    model=a_							,					args=a_							,					train_dataset=dataset['train'] if training_args.do_train else None							,					eval_dataset=dataset['validation'] if training_args.do_eval else None							,					compute_metrics=a_							,					tokenizer=a_							,					data_collator=a_							,					)

							# Training
							if training_args.do_train:
														snake_case_           =							None
														if training_args.resume_from_checkpoint is not None:
																					snake_case_           =							training_args.resume_from_checkpoint
														elif last_checkpoint is not None:
																					snake_case_           =							last_checkpoint
														snake_case_           =							trainer.train(resume_from_checkpoint=a_)
														trainer.save_model()
														trainer.log_metrics('train'							,					train_result.metrics)
														trainer.save_metrics('train'							,					train_result.metrics)
														trainer.save_state()

							# Evaluation
							if training_args.do_eval:
														snake_case_           =							trainer.evaluate()
														trainer.log_metrics('eval'							,					a_)
														trainer.save_metrics('eval'							,					a_)

							# Write model card and (optionally) push to hub
							snake_case_           =							{
							    'finetuned_from': model_args.model_name_or_path,
							    'dataset': data_args.dataset_name,
							    'tags': ['image-segmentation', 'vision'],
							}
							if training_args.push_to_hub:
														trainer.push_to_hub(**a_)
							else:
														trainer.create_model_card(**a_)


if __name__ == "__main__":
	main()













from collections.abc import Callable
from math import log
from os import name, system
from random import gauss, seed
from typing import TypeVar





def 						__UpperCAmelCase      (					a_							,					a_							,					a_):
							seed(1)
							return [gauss(a_							,					a_) for _ in range(a_)]





def 						__UpperCAmelCase      (					a_							,					a_):
							return [k for k in range(a_) for _ in range(instance_count[k])]





def 						__UpperCAmelCase      (					a_							,					a_):
							return sum(a_) / instance_count





def 						__UpperCAmelCase      (					a_							,					a_):
							return instance_count / total_count





def 						__UpperCAmelCase      (					a_							,					a_							,					a_):
							snake_case_           =							[]  # An empty list to store all squared differences
							# iterate over number of elements in items
							for i in range(len(a_)):
														# for loop iterates over number of elements in inner layer of items
														for j in range(len(items[i])):
																					# appending squared differences to 'squared_diff' list
																					squared_diff.append((items[i][j] - means[i]) ** 2)

    # one divided by (the number of all instances - number of classes) multiplied by
    # sum of all squared differences
							snake_case_           =							len(a_)  # Number of classes in dataset
							return 1 / (total_count - n_classes) * sum(a_)





def 						__UpperCAmelCase      (					a_							,					a_							,					a_							,					a_):
							snake_case_           =							[]
							# for loop iterates over number of elements in list
							for i in range(len(a_)):
														# for loop iterates over number of inner items of each element
														for j in range(len(x_items[i])):
																					snake_case_           =							[]  # to store all discriminant values of each item as a list
																					# for loop iterates over number of classes we have in our dataset
																					for k in range(len(a_)):
																												# appending values of discriminants for each class to 'temp' list
																												temp.append(
																												    x_items[i][j] * (means[k] / variance)
																												    - (means[k] ** 2 / (2 * variance))
																												    + log(probabilities[k]))
																					# appending discriminant values of each item to 'results' list
																					results.append(a_)

							return [result.index(max(a_)) for result in results]





def 						__UpperCAmelCase      (					a_							,					a_):
							snake_case_           =							sum(1 for i, j in zip(a_							,					a_) if i == j)
							# percentage of accuracy equals to number of correct predictions divided by number
							# of all data and multiplied by 100
							return (correct / len(a_)) * 1_00


lowercase  							= TypeVar("num")





def 						__UpperCAmelCase      (					a_							,					a_							,					a_							,					a_ = lambda a_: True							,					a_ = None							,					):
							while True:
														try:
																					snake_case_           =							input_type(input(a_).strip() or default)
																					if condition(a_):
																												return user_input
																					else:
																												print(f'''{user_input}: {err_msg}''')
																												continue
														except ValueError:
																					print(
																					    f'''{user_input}: Incorrect input type, expected {input_type.__name__!r}''')





def 						__UpperCAmelCase      (					):
							while True:
														print(' Linear Discriminant Analysis '.center(50							,					'*'))
														print('*' * 50							,					'\n')
														print('First of all we should specify the number of classes that')
														print('we want to generate as training dataset')
														# Trying to get number of classes
														snake_case_           =							valid_input(
														    input_type=a_							,					condition=lambda a_: x > 0							,					input_msg='Enter the number of classes (Data Groupings): '							,					err_msg='Number of classes should be positive!'							,					)

														print('-' * 1_00)

														# Trying to get the value of standard deviation
														snake_case_           =							valid_input(
														    input_type=a_							,					condition=lambda a_: x >= 0							,					input_msg=(
														        'Enter the value of standard deviation'
														        '(Default value is 1.0 for all classes): '
														    )							,					err_msg='Standard deviation should not be negative!'							,					default='1.0'							,					)

														print('-' * 1_00)

														# Trying to get number of instances in classes and theirs means to generate
														# dataset
														snake_case_           =							[]  # An empty list to store instance counts of classes in dataset
														for i in range(a_):
																					snake_case_           =							valid_input(
																					    input_type=a_							,					condition=lambda a_: x > 0							,					input_msg=(f'''Enter The number of instances for class_{i+1}: ''')							,					err_msg='Number of instances should be positive!'							,					)
																					counts.append(a_)
														print('-' * 1_00)

														# An empty list to store values of user-entered means of classes
														snake_case_           =							[]
														for a in range(a_):
																					snake_case_           =							valid_input(
																					    input_type=a_							,					input_msg=(f'''Enter the value of mean for class_{a+1}: ''')							,					err_msg='This is an invalid value.'							,					)
																					user_means.append(a_)
														print('-' * 1_00)

														print('Standard deviation: '							,					a_)
														# print out the number of instances in classes in separated line
														for i, count in enumerate(a_							,					1):
																					print(f'''Number of instances in class_{i} is: {count}''')
														print('-' * 1_00)

														# print out mean values of classes separated line
														for i, user_mean in enumerate(a_							,					1):
																					print(f'''Mean of class_{i} is: {user_mean}''')
														print('-' * 1_00)

														# Generating training dataset drawn from gaussian distribution
														snake_case_           =							[
														    gaussian_distribution(user_means[j]							,					a_							,					counts[j])
														    for j in range(a_)
														]
														print('Generated Normal Distribution: \n'							,					a_)
														print('-' * 1_00)

														# Generating Ys to detecting corresponding classes
														snake_case_           =							y_generator(a_							,					a_)
														print('Generated Corresponding Ys: \n'							,					a_)
														print('-' * 1_00)

														# Calculating the value of actual mean for each class
														snake_case_           =							[calculate_mean(counts[k]							,					x[k]) for k in range(a_)]
														# for loop iterates over number of elements in 'actual_means' list and print
														# out them in separated line
														for i, actual_mean in enumerate(a_							,					1):
																					print(f'''Actual(Real) mean of class_{i} is: {actual_mean}''')
														print('-' * 1_00)

														# Calculating the value of probabilities for each class
														snake_case_           =							[
														    calculate_probabilities(counts[i]							,					sum(a_)) for i in range(a_)
														]

														# for loop iterates over number of elements in 'probabilities' list and print
														# out them in separated line
														for i, probability in enumerate(a_							,					1):
																					print(f'''Probability of class_{i} is: {probability}''')
														print('-' * 1_00)

														# Calculating the values of variance for each class
														snake_case_           =							calculate_variance(a_							,					a_							,					sum(a_))
														print('Variance: '							,					a_)
														print('-' * 1_00)

														# Predicting Y values
														# storing predicted Y values in 'pre_indexes' variable
														snake_case_           =							predict_y_values(a_							,					a_							,					a_							,					a_)
														print('-' * 1_00)

														# Calculating Accuracy of the model
														print(f'''Accuracy: {accuracy(a_							,					a_)}''')
														print('-' * 1_00)
														print(' DONE '.center(1_00							,					'+'))

														if input('Press any key to restart or \'q\' for quit: ').strip().lower() == "q":
																					print('\n' + 'GoodBye!'.center(1_00							,					'-') + '\n')
																					break
														system('cls' if name == 'nt' else 'clear')  # noqa: S605


if __name__ == "__main__":
	main()





