o  i@sddlmZddlZddlZddlmZddlmZed\Z Z GdddeZ dd d Z d d!ddZ d"ddZ d#d$ddZdS)%) annotationsN)Metric)optional_importscipyc@seZdZdZd ddZdS) FIDMetrica Frechet Inception Distance (FID). The FID calculates the distance between two distributions of feature vectors. Based on: Heusel M. et al. "Gans trained by a two time-scale update rule converge to a local nash equilibrium." https://arxiv.org/abs/1706.08500. The inputs for this metric should be two groups of feature vectors (with format (number images, number of features)) extracted from a pretrained network. Originally, it was proposed to use the activations of the pool_3 layer of an Inception v3 pretrained with Imagenet. However, others networks pretrained on medical datasets can be used as well (for example, RadImageNwt for 2D and MedicalNet for 3D images). If the chosen model output is not a scalar, a global spatia average pooling should be used. y_pred torch.TensoryreturncCs t||S)N) get_fid_score)selfrr r S/home/dell461/cl/sdc2/last_ska_mid/HISourceFinder-master-l/src/monai/metrics/fid.py__call__$s zFIDMetric.__call__Nrrr rr r)__name__ __module__ __qualname____doc__rr r r rrs rrrr r cCsf|}|}|dkrtdtj|dd}t|dd}tj|dd}t|dd}t||||S)aComputes the FID score metric on a batch of feature vectors. Args: y_pred: feature vectors extracted from a pretrained network run on generated images. y: feature vectors extracted from a pretrained network run on images from the real data distribution. z=Inputs should have (number images, number of features) shape.r)dimF)rowvar)double ndimension ValueErrortorchmean_covcompute_frechet_distance)rr Z mu_y_predZ sigma_y_predmu_ysigma_yr r rr (s   r T input_datarboolcCsn|dkr |dd}|s|ddkr|}d|dd}|tj|ddd}|||S)a  Estimate a covariance matrix of the variables. Args: input_data: A 1-D or 2-D array containing multiple variables and observations. Each row of `m` represents a variable, and each column a single observation of all those variables. rowvar: If rowvar is True (default), then each row represents a variable, with observations in the columns. Otherwise, the relationship is transposed: each column represents a variable, while the rows contain observations. rrg?T)rkeepdim)rviewsizetrrmatmulsqueeze)r!rfactorr r rr=s rcCs2tjj|tjdd\}}t |S)z$Compute the square root of a matrix.F)disp) rlinalgsqrtmdetachcpunumpyastypenpfloat64r from_numpy)r!Z scipy_res_r r r_sqrtmSs( r7ư>mu_xsigma_xrr epsilonfloatc Cs||}t||}t|s4td|dtj|d|j|j d|}t||||}t |r]tj t |j tjdtjdddsZtdtt|j d |j}t|}||t|t|d |S) z?The Frechet distance between multivariate normal distributions.z2FID calculation produces singular product; adding z$ to diagonal of covariance estimatesr)devicedtype)r>gMbP?)atolzImaginary component z too high.r)r7mmrisfiniteallprinteyer'r=r> is_complexallclosediagonalimagtensorrrmaxabsrealtracedot) r9r:rr r;diffZcovmeanoffsetZ tr_covmeanr r rrYs $ &rr)T)r!rrr"r r)r!rr r)r8) r9rr:rrrr rr;r<r r) __future__rr1r3rZmonai.metrics.metricr monai.utilsrrr6rr rr7rr r r rs