


import warnings

import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
from sklearn.metrics import pairwise_distances

warnings.filterwarnings('ignore')

snake_case__  				=			'K-MEANS-CLUST/ '
def 			__SCREAMING_SNAKE_CASE							(					lowercase__	:Optional[Any]   ,    lowercase__	:Optional[int]   ,    lowercase__	:Union[str, Any]=None					)							->	List[Any]:





						if seed is not None:  # useful for obtaining consistent results
												np.random.seed(lowerCAmelCase__					)
						__magic_name__					:				Any				=   data.shape[0]  # number of data points

						# Pick K indices from range [0, N).
						__magic_name__					:				int				=   np.random.randint(0   ,    lowerCAmelCase__   ,    lowerCAmelCase__					)

						# Keep centroids as dense format, as many entries will be nonzero due to averaging.
						# As long as at least one document in a cluster contains a word,
						# it will carry a nonzero weight in the TF-IDF vector of the centroid.
						__magic_name__					:				Optional[Any]				=   data[rand_indices, :]

						return centroids
def 			__SCREAMING_SNAKE_CASE							(					lowercase__	:int   ,    lowercase__	:List[Any]					)							->	str:
						return pairwise_distances(lowerCAmelCase__   ,    lowerCAmelCase__   ,    metric='euclidean'					)
def 			__SCREAMING_SNAKE_CASE							(					lowercase__	:Optional[int]   ,    lowercase__	:Dict					)							->	Union[str, Any]:
						__magic_name__					:				Dict				=   centroid_pairwise_dist(lowerCAmelCase__   ,    lowerCAmelCase__					)

						# Compute cluster assignments for each data point:
						# Fill in the blank (RHS only)
						__magic_name__					:				Union[str, Any]				=   np.argmin(lowerCAmelCase__   ,    axis=1					)

						return cluster_assignment
def 			__SCREAMING_SNAKE_CASE							(					lowercase__	:Dict   ,    lowercase__	:int   ,    lowercase__	:Dict					)							->	Union[str, Any]:
						__magic_name__					:				Optional[Any]				=   []
						for i in range(lowerCAmelCase__					):
												# Select all data points that belong to cluster i. Fill in the blank (RHS only)
												__magic_name__					:				str				=   data[cluster_assignment == i]
												# Compute the mean of the data points. Fill in the blank (RHS only)
												__magic_name__					:				List[Any]				=   member_data_points.mean(axis=0					)
												new_centroids.append(lowerCAmelCase__					)
						__magic_name__					:				List[Any]				=   np.array(lowerCAmelCase__					)

						return new_centroids
def 			__SCREAMING_SNAKE_CASE							(					lowercase__	:List[str]   ,    lowercase__	:int   ,    lowercase__	:List[Any]   ,    lowercase__	:Union[str, Any]					)							->	Tuple:
						__magic_name__					:				Dict				=   0.0
						for i in range(lowerCAmelCase__					):
												# Select all data points that belong to cluster i. Fill in the blank (RHS only)
												__magic_name__					:				Dict				=   data[cluster_assignment == i, :]

												if member_data_points.shape[0] > 0:  # check if i-th cluster is non-empty
																		# Compute distances from centroid to data points (RHS only)
																		__magic_name__					:				List[str]				=   pairwise_distances(
																		    lowerCAmelCase__   ,    [centroids[i]]   ,    metric='euclidean'					)
																		__magic_name__					:				List[Any]				=   distances**2
																		heterogeneity += np.sum(lowerCAmelCase__					)

						return heterogeneity
def 			__SCREAMING_SNAKE_CASE							(					lowercase__	:Optional[Any]   ,    lowercase__	:Tuple					)							->	int:
						plt.figure(figsize=(7, 4)					)
						plt.plot(lowerCAmelCase__   ,    linewidth=4					)
						plt.xlabel('# Iterations'					)
						plt.ylabel('Heterogeneity'					)
						plt.title(f"Heterogeneity of clustering over time, K={k:d}"					)
						plt.rcParams.update({'font.size': 1_6}					)
						plt.show()
def 			__SCREAMING_SNAKE_CASE							(					lowercase__	:List[Any]   ,    lowercase__	:List[str]   ,    lowercase__	:str   ,    lowercase__	:str=5_0_0   ,    lowercase__	:List[str]=None   ,    lowercase__	:List[Any]=False					)							->	Union[str, Any]:
						__magic_name__					:				Tuple				=   initial_centroids[:]
						__magic_name__					:				str				=   None

						for itr in range(lowerCAmelCase__					):
												if verbose:
																		print(lowerCAmelCase__   ,    end=''					)

												# 1. Make cluster assignments using nearest centroids
												__magic_name__					:				Optional[int]				=   assign_clusters(lowerCAmelCase__   ,    lowerCAmelCase__					)

												# 2. Compute a new centroid for each of the k clusters, averaging all data
												#    points assigned to that cluster.
												__magic_name__					:				List[str]				=   revise_centroids(lowerCAmelCase__   ,    lowerCAmelCase__   ,    lowerCAmelCase__					)

												# Check for convergence: if none of the assignments changed, stop
												if (
												    prev_cluster_assignment is not None
												    and (prev_cluster_assignment == cluster_assignment).all()
												):
																		break

												# Print number of new assignments
												if prev_cluster_assignment is not None:
																		__magic_name__					:				Any				=   np.sum(prev_cluster_assignment != cluster_assignment					)
																		if verbose:
																								print(
																								    f"    {num_changed:5d} elements changed their cluster assignment."					)

        # Record heterogeneity convergence metric
												if record_heterogeneity is not None:
																		# YOUR CODE HERE
																		__magic_name__					:				List[Any]				=   compute_heterogeneity(lowerCAmelCase__   ,    lowerCAmelCase__   ,    lowerCAmelCase__   ,    lowerCAmelCase__					)
																		record_heterogeneity.append(lowerCAmelCase__					)

												__magic_name__					:				Optional[Any]				=   cluster_assignment[:]

						return centroids, cluster_assignment


# Mock test below
if False:  # change to true to run this test case.
			from sklearn import datasets as ds

			snake_case__  				=			ds.load_iris()
			snake_case__  				=			3
			snake_case__  				=			[]
			snake_case__  				=			get_initial_centroids(dataset['data'], k, seed=0)
			snake_case__				,  snake_case__  				=			kmeans(
			    dataset['data'],
			    k,
			    initial_centroids,
			    maxiter=400,
			    record_heterogeneity=heterogeneity,
			    verbose=True,
			)
			plot_heterogeneity(heterogeneity, k)
def 			__SCREAMING_SNAKE_CASE							(					lowercase__	:pd.DataFrame   ,    lowercase__	:np.ndarray   ,    lowercase__	:str=None					)							->	Any:





						if fill_missing_report:
												__magic_name__					:				int				=   df.fillna(value=lowerCAmelCase__					)
						__magic_name__					:				List[Any]				=   1
						__magic_name__					:				Union[str, Any]				=   df.select_dtypes(np.number					).columns
						__magic_name__					:				str				=   (
						    df.groupby(['Cluster']					)[  # construct report dataframe
						        numeric_cols
						    ]  # group by cluster number
						    .agg(
						        [
						            ('sum', np.sum),
						            ('mean_with_zeros', lambda lowercase__					: np.mean(np.nan_to_num(lowerCAmelCase__					)					)),
						            ('mean_without_zeros', lambda lowercase__					: x.replace(0   ,    np.NaN					).mean()),
						            (
						                'mean_25-75',
						                lambda lowercase__					: np.mean(
						                    np.nan_to_num(
						                        sorted(lowerCAmelCase__					)[
						                            round(len(lowerCAmelCase__					) * 2_5 / 1_0_0					) : round(len(lowerCAmelCase__					) * 7_5 / 1_0_0					)
						                        ]					)					),
						            ),
						            ('mean_with_na', np.mean),
						            ('min', lambda lowercase__					: x.min()),
						            ('5%', lambda lowercase__					: x.quantile(0.0_5					)),
						            ('25%', lambda lowercase__					: x.quantile(0.2_5					)),
						            ('50%', lambda lowercase__					: x.quantile(0.5_0					)),
						            ('75%', lambda lowercase__					: x.quantile(0.7_5					)),
						            ('95%', lambda lowercase__					: x.quantile(0.9_5					)),
						            ('max', lambda lowercase__					: x.max()),
						            ('count', lambda lowercase__					: x.count()),
						            ('stdev', lambda lowercase__					: x.std()),
						            ('mode', lambda lowercase__					: x.mode()[0]),
						            ('median', lambda lowercase__					: x.median()),
						            ('# > 0', lambda lowercase__					: (x > 0).sum()),
						        ]					)
						    .T.reset_index()
						    .rename(index=lowerCAmelCase__   ,    columns={'level_0': 'Features', 'level_1': 'Type'}					)
						)  # rename columns
						# calculate the size of cluster(count of clientID's)
						__magic_name__					:				Union[str, Any]				=   report[
						    (report["""Features"""] == """dummy""") & (report["""Type"""] == """count""")
						].copy()  # avoid SettingWithCopyWarning
						__magic_name__					:				str				=   (
						    """ClusterSize"""  # rename created cluster df to match report column names
						)
						__magic_name__					:				Dict				=   """# of Customers"""
						__magic_name__					:				Optional[int]				=   pd.DataFrame(
						    clustersize.iloc[:, 2:].values
						    / clustersize.iloc[:, 2:].values.sum()					)
						__magic_name__					:				List[str]				=   """% of Customers"""  # rename created cluster df to match report column names
						__magic_name__					:				Tuple				=   """ClusterProportion"""
						__magic_name__					:				Union[str, Any]				=   clusterproportion.columns.tolist()
						__magic_name__					:				Any				=   cols[-2:] + cols[:-2]
						__magic_name__					:				Any				=   clusterproportion[cols]  # rearrange columns to match report
						__magic_name__					:				str				=   report.columns
						__magic_name__					:				Dict				=   pd.DataFrame(
						    abs(
						        report[report['Type'] == 'count'].iloc[:, 2:].values
						        - clustersize.iloc[:, 2:].values					)					)  # generating df with count of nan values
						__magic_name__					:				Optional[int]				=   0
						__magic_name__					:				int				=   """# of nan"""
						__magic_name__					:				List[Any]				=   report[
						    report["""Type"""] == """count"""
						].Features.tolist()  # filling values in order to match report
						__magic_name__					:				str				=   a.columns.tolist()
						__magic_name__					:				List[Any]				=   cols[-2:] + cols[:-2]
						__magic_name__					:				Optional[int]				=   a[cols]  # rearrange columns to match report
						__magic_name__					:				Any				=   report.columns  # rename columns to match report
						__magic_name__					:				Union[str, Any]				=   report.drop(
						    report[report.Type == 'count'].index					)  # drop count values except cluster size
						__magic_name__					:				Any				=   pd.concat(
						    [report, a, clustersize, clusterproportion]   ,    axis=0					)  # concat report with clustert size and nan values
						__magic_name__					:				Tuple				=   report["""Features"""].isin(lowerCAmelCase__					)
						__magic_name__					:				Optional[int]				=   report.columns.tolist()
						__magic_name__					:				List[Any]				=   cols[0:2] + cols[-1:] + cols[2:-1]
						__magic_name__					:				Tuple				=   report[cols]
						__magic_name__					:				List[str]				=   {
						    """ClusterSize""": 9,
						    """ClusterProportion""": 8,
						    """mean_with_zeros""": 7,
						    """mean_with_na""": 6,
						    """max""": 5,
						    """50%""": 4,
						    """min""": 3,
						    """25%""": 2,
						    """75%""": 1,
						    """# of nan""": 0,
						    """# > 0""": -1,
						    """sum_with_na""": -2,
						}
						__magic_name__					:				int				=   (
						    report.assign(
						        Sortera=lambda lowercase__					: x.Type.map(lowerCAmelCase__					)   ,    Sortera=lambda lowercase__					: list(reversed(range(len(lowerCAmelCase__					)					)					)					)   ,    )
						    .sort_values(['Sorter1', 'Mark', 'Sorter2']   ,    ascending=lowerCAmelCase__					)
						    .drop(['Sorter1', 'Sorter2']   ,    axis=1					)
						)
						__magic_name__					:				str				=   """"""
						__magic_name__					:				int				=   report.reset_index()
						__magic_name__					:				Any				=   report.drop(columns=['index']					)
						return report


if __name__ == "__main__":
			import doctest

			doctest.testmod()







'''simple docstring'''
from __future__ import annotations

import inspect
import unittest
from typing import List, Tuple

from transformers import ConvNextConfig
from transformers.testing_utils import require_tf, require_vision, slow
from transformers.utils import cached_property, is_tf_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
					import tensorflow as tf

					from transformers import TFConvNextForImageClassification, TFConvNextModel


if is_vision_available():
					from PIL import Image

					from transformers import ConvNextImageProcessor



class _A	:





		def __init__(  self			,							__UpperCAmelCase			,							__UpperCAmelCase=13			,							__UpperCAmelCase=32			,							__UpperCAmelCase=3			,							__UpperCAmelCase=4			,							__UpperCAmelCase=[10, 20, 30, 40]			,							__UpperCAmelCase=[2, 2, 3, 2]			,							__UpperCAmelCase=True			,							__UpperCAmelCase=True			,							__UpperCAmelCase=37			,							__UpperCAmelCase="gelu"			,							__UpperCAmelCase=10			,							__UpperCAmelCase=0.02			,							__UpperCAmelCase=3			,							__UpperCAmelCase=None			,							)							->  Any:

					'''simple docstring'''
					__UpperCAmelCase :   Optional[int]    					=  parent
					__UpperCAmelCase :   Optional[Any]    					=  batch_size
					__UpperCAmelCase :   List[str]    					=  image_size
					__UpperCAmelCase :   Optional[Any]    					=  num_channels
					__UpperCAmelCase :   int    					=  num_stages
					__UpperCAmelCase :   List[Any]    					=  hidden_sizes
					__UpperCAmelCase :   Optional[Any]    					=  depths
					__UpperCAmelCase :   List[str]    					=  is_training
					__UpperCAmelCase :   Tuple    					=  use_labels
					__UpperCAmelCase :   Optional[Any]    					=  intermediate_size
					__UpperCAmelCase :   Dict    					=  hidden_act
					__UpperCAmelCase :   List[str]    					=  type_sequence_label_size
					__UpperCAmelCase :   Union[str, Any]    					=  initializer_range
					__UpperCAmelCase :   Optional[Any]    					=  scope





		def 				__A							(  self					)							->  Optional[Any]:

					'''simple docstring'''
					__UpperCAmelCase :   List[Any]    					=  floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]					)

					__UpperCAmelCase :   str    					=  None
					if self.use_labels:
								__UpperCAmelCase :   Optional[Any]    					=  ids_tensor([self.batch_size]			,							self.type_sequence_label_size					)

					__UpperCAmelCase :   Optional[int]    					=  self.get_config()

					return config, pixel_values, labels





		def 				__A							(  self					)							->  Optional[Any]:

					'''simple docstring'''
					return ConvNextConfig(
					    num_channels=self.num_channels			,							hidden_sizes=self.hidden_sizes			,							depths=self.depths			,							num_stages=self.num_stages			,							hidden_act=self.hidden_act			,							is_decoder=__UpperCAmelCase			,							initializer_range=self.initializer_range			,							)





		def 				__A							(  self			,							__UpperCAmelCase			,							__UpperCAmelCase			,							__UpperCAmelCase					)							->  List[Any]:

					'''simple docstring'''
					__UpperCAmelCase :   List[Any]    					=  TFConvNextModel(config=__UpperCAmelCase					)
					__UpperCAmelCase :   List[Any]    					=  model(__UpperCAmelCase			,							training=__UpperCAmelCase					)
					# expected last hidden states: B, C, H // 32, W // 32
					self.parent.assertEqual(
					    result.last_hidden_state.shape			,							(self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32)			,							)





		def 				__A							(  self			,							__UpperCAmelCase			,							__UpperCAmelCase			,							__UpperCAmelCase					)							->  Optional[int]:

					'''simple docstring'''
					__UpperCAmelCase :   Optional[int]    					=  self.type_sequence_label_size
					__UpperCAmelCase :   List[Any]    					=  TFConvNextForImageClassification(__UpperCAmelCase					)
					__UpperCAmelCase :   List[str]    					=  model(__UpperCAmelCase			,							labels=__UpperCAmelCase			,							training=__UpperCAmelCase					)
					self.parent.assertEqual(result.logits.shape			,							(self.batch_size, self.type_sequence_label_size)					)





		def 				__A							(  self					)							->  Union[str, Any]:

					'''simple docstring'''
					__UpperCAmelCase :   List[str]    					=  self.prepare_config_and_inputs()
					__UpperCAmelCase					,	__UpperCAmelCase					,	__UpperCAmelCase :   Optional[int]    					=  config_and_inputs
					__UpperCAmelCase :   Union[str, Any]    					=  {"""pixel_values""": pixel_values}
					return config, inputs_dict



@require_tf
class _A	(     __SCREAMING_SNAKE_CASE						,					__SCREAMING_SNAKE_CASE						,					unittest.TestCase     ):
		_SCREAMING_SNAKE_CASE       :     Dict       =      (TFConvNextModel, TFConvNextForImageClassification) if is_tf_available() else ()
		_SCREAMING_SNAKE_CASE       :     Optional[Any]       =      (
		    {"feature-extraction": TFConvNextModel, "image-classification": TFConvNextForImageClassification}
		    if is_tf_available()
		    else {}
		)

		_SCREAMING_SNAKE_CASE       :     Tuple       =      False
		_SCREAMING_SNAKE_CASE       :     Tuple       =      False
		_SCREAMING_SNAKE_CASE       :     Union[str, Any]       =      False
		_SCREAMING_SNAKE_CASE       :     Optional[Any]       =      False
		_SCREAMING_SNAKE_CASE       :     str       =      False





		def 				__A							(  self					)							->  List[Any]:

					'''simple docstring'''
					__UpperCAmelCase :   Dict    					=  TFConvNextModelTester(self					)
					__UpperCAmelCase :   Optional[int]    					=  ConfigTester(
					    self			,							config_class=__UpperCAmelCase			,							has_text_modality=__UpperCAmelCase			,							hidden_size=37			,							)





		@unittest.skip(reason="""ConvNext does not use inputs_embeds"""					)
		def 				__A							(  self					)							->  str:

					'''simple docstring'''
					pass





		@unittest.skipIf(
		    not is_tf_available() or len(tf.config.list_physical_devices("""GPU"""					)					) == 0			,							reason="""TF does not support backprop for grouped convolutions on CPU."""			,							)
		@slow
		def 				__A							(  self					)							->  Optional[int]:

					'''simple docstring'''
					super().test_keras_fit()





		@unittest.skip(reason="""ConvNext does not support input and output embeddings"""					)
		def 				__A							(  self					)							->  Dict:

					'''simple docstring'''
					pass





		def 				__A							(  self					)							->  str:

					'''simple docstring'''
					__UpperCAmelCase					,	__UpperCAmelCase :   List[str]    					=  self.model_tester.prepare_config_and_inputs_for_common()

					for model_class in self.all_model_classes:
								__UpperCAmelCase :   List[Any]    					=  model_class(__UpperCAmelCase					)
								__UpperCAmelCase :   str    					=  inspect.signature(model.call					)
								# signature.parameters is an OrderedDict => so arg_names order is deterministic
								__UpperCAmelCase :   Tuple    					=  [*signature.parameters.keys()]

								__UpperCAmelCase :   Tuple    					=  ["""pixel_values"""]
								self.assertListEqual(arg_names[:1]			,							__UpperCAmelCase					)





		def 				__A							(  self					)							->  Dict:

					'''simple docstring'''
					__UpperCAmelCase :   Dict    					=  self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_model(*__UpperCAmelCase					)





		@unittest.skipIf(
		    not is_tf_available() or len(tf.config.list_physical_devices("""GPU"""					)					) == 0			,							reason="""TF does not support backprop for grouped convolutions on CPU."""			,							)
		def 				__A							(  self					)							->  Union[str, Any]:

					'''simple docstring'''
					super().test_dataset_conversion()





		def 				__A							(  self					)							->  Optional[int]:

					'''simple docstring'''
					def check_hidden_states_output(__UpperCAmelCase			,							__UpperCAmelCase			,							__UpperCAmelCase					):
								__UpperCAmelCase :   Optional[int]    					=  model_class(__UpperCAmelCase					)

								__UpperCAmelCase :   str    					=  model(**self._prepare_for_class(__UpperCAmelCase			,							__UpperCAmelCase					)					)
								__UpperCAmelCase :   List[str]    					=  outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

								__UpperCAmelCase :   Optional[int]    					=  self.model_tester.num_stages
								self.assertEqual(len(__UpperCAmelCase					)			,							expected_num_stages + 1					)

								# ConvNext's feature maps are of shape (batch_size, num_channels, height, width)
								self.assertListEqual(
								    list(hidden_states[0].shape[-2:]					)			,							[self.model_tester.image_size // 4, self.model_tester.image_size // 4]			,							)

					__UpperCAmelCase					,	__UpperCAmelCase :   Union[str, Any]    					=  self.model_tester.prepare_config_and_inputs_for_common()

					for model_class in self.all_model_classes:
								__UpperCAmelCase :   List[str]    					=  True
								check_hidden_states_output(__UpperCAmelCase			,							__UpperCAmelCase			,							__UpperCAmelCase					)

								# check that output_hidden_states also work using config
								del inputs_dict["output_hidden_states"]
								__UpperCAmelCase :   Optional[Any]    					=  True

								check_hidden_states_output(__UpperCAmelCase			,							__UpperCAmelCase			,							__UpperCAmelCase					)





		def 				__A							(  self					)							->  Tuple:

					'''simple docstring'''
					__UpperCAmelCase					,	__UpperCAmelCase :   Any    					=  self.model_tester.prepare_config_and_inputs_for_common()

					def check_equivalence(__UpperCAmelCase			,							__UpperCAmelCase			,							__UpperCAmelCase			,							__UpperCAmelCase={}					):
								__UpperCAmelCase :   Optional[Any]    					=  model(__UpperCAmelCase			,							return_dict=__UpperCAmelCase			,							**__UpperCAmelCase					)
								__UpperCAmelCase :   Optional[int]    					=  model(__UpperCAmelCase			,							return_dict=__UpperCAmelCase			,							**__UpperCAmelCase					).to_tuple()

								def recursive_check(__UpperCAmelCase			,							__UpperCAmelCase					):
											if isinstance(__UpperCAmelCase			,							(List, Tuple)					):
														for tuple_iterable_value, dict_iterable_value in zip(__UpperCAmelCase			,							__UpperCAmelCase					):
																	recursive_check(__UpperCAmelCase			,							__UpperCAmelCase					)
											elif tuple_object is None:
														return
											else:
														self.assertTrue(
														    all(tf.equal(__UpperCAmelCase			,							__UpperCAmelCase					)					)			,							msg=(
														        """Tuple and dict output are not equal. Difference:"""
														        f' {tf.math.reduce_max(tf.abs(tuple_object - dict_object					)					)}'
														    )			,							)

											recursive_check(__UpperCAmelCase			,							__UpperCAmelCase					)

					for model_class in self.all_model_classes:
								__UpperCAmelCase :   Dict    					=  model_class(__UpperCAmelCase					)

								__UpperCAmelCase :   Optional[int]    					=  self._prepare_for_class(__UpperCAmelCase			,							__UpperCAmelCase					)
								__UpperCAmelCase :   Tuple    					=  self._prepare_for_class(__UpperCAmelCase			,							__UpperCAmelCase					)
								check_equivalence(__UpperCAmelCase			,							__UpperCAmelCase			,							__UpperCAmelCase					)

								__UpperCAmelCase :   Union[str, Any]    					=  self._prepare_for_class(__UpperCAmelCase			,							__UpperCAmelCase			,							return_labels=__UpperCAmelCase					)
								__UpperCAmelCase :   Union[str, Any]    					=  self._prepare_for_class(__UpperCAmelCase			,							__UpperCAmelCase			,							return_labels=__UpperCAmelCase					)
								check_equivalence(__UpperCAmelCase			,							__UpperCAmelCase			,							__UpperCAmelCase					)

								__UpperCAmelCase :   Optional[Any]    					=  self._prepare_for_class(__UpperCAmelCase			,							__UpperCAmelCase					)
								__UpperCAmelCase :   List[str]    					=  self._prepare_for_class(__UpperCAmelCase			,							__UpperCAmelCase					)
								check_equivalence(__UpperCAmelCase			,							__UpperCAmelCase			,							__UpperCAmelCase			,							{"""output_hidden_states""": True}					)

								__UpperCAmelCase :   List[Any]    					=  self._prepare_for_class(__UpperCAmelCase			,							__UpperCAmelCase			,							return_labels=__UpperCAmelCase					)
								__UpperCAmelCase :   Dict    					=  self._prepare_for_class(__UpperCAmelCase			,							__UpperCAmelCase			,							return_labels=__UpperCAmelCase					)
								check_equivalence(__UpperCAmelCase			,							__UpperCAmelCase			,							__UpperCAmelCase			,							{"""output_hidden_states""": True}					)





		def 				__A							(  self					)							->  Tuple:

					'''simple docstring'''
					__UpperCAmelCase :   int    					=  self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_for_image_classification(*__UpperCAmelCase					)





		@slow
		def 				__A							(  self					)							->  Tuple:

					'''simple docstring'''
					__UpperCAmelCase :   Union[str, Any]    					=  TFConvNextModel.from_pretrained("""facebook/convnext-tiny-224"""					)
					self.assertIsNotNone(__UpperCAmelCase					)


def 	lowercase_						( ):

			"""simple docstring"""





			__UpperCAmelCase :   str    					=  Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""			)
			return image






@require_tf
@require_vision
class _A	(     unittest.TestCase     ):





		@cached_property
		def 				__A							(  self					)							->  Any:

					'''simple docstring'''
					return ConvNextImageProcessor.from_pretrained("""facebook/convnext-tiny-224"""					) if is_vision_available() else None





		@slow
		def 				__A							(  self					)							->  int:

					'''simple docstring'''
					__UpperCAmelCase :   Tuple    					=  TFConvNextForImageClassification.from_pretrained("""facebook/convnext-tiny-224"""					)

					__UpperCAmelCase :   List[Any]    					=  self.default_image_processor
					__UpperCAmelCase :   int    					=  prepare_img()
					__UpperCAmelCase :   Optional[Any]    					=  image_processor(images=__UpperCAmelCase			,							return_tensors="""tf"""					)

					# forward pass
					__UpperCAmelCase :   List[Any]    					=  model(**__UpperCAmelCase					)

					# verify the logits
					__UpperCAmelCase :   List[str]    					=  tf.TensorShape((1, 1_000)					)
					self.assertEqual(outputs.logits.shape			,							__UpperCAmelCase					)

					__UpperCAmelCase :   str    					=  tf.constant([-0.0260, -0.4739, 0.1911]					)

					tf.debugging.assert_near(outputs.logits[0, :3]			,							__UpperCAmelCase			,							atol=1E-4					)




