desert_ranger
desert_ranger

Reputation: 1743

InvalidArgumentError: Expected 'tf.Tensor(False, shape=(), dtype=bool)' to be true

I am using PCA to reduce the dimensions of images before comparing them using the Structural Similarity Index. After using PCA, tf.image.ssim throws an error.

I am comparing images here without the use of PCA. This works perfectly -

import numpy as np
import tensorflow as tf
import time
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data(
    path='mnist.npz'
)
start = time.time()
for i in range(1,6000):
    x_train_zero = np.expand_dims(x_train[0], axis=2)
    x_train_expanded = np.expand_dims(x_train[i], axis=2)
    print(tf.image.ssim(x_train_zero, x_train_expanded, 255))
print(time.time()-start)

I have applied PCA here to reduce the dimensions of images, so that SSIM takes lesser time to compare images -

from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
x_train = x_train.reshape(60000,-1)
scaler = StandardScaler()
X_scaled = scaler.fit_transform(x_train)
pca = PCA()
pca = PCA(n_components = 11)
X_pca = pca.fit_transform(X_scaled).reshape(60000,11,1)
start = time.time()
for i in range(1,6000):
    X_pca_zero = np.expand_dims(X_pca[0], axis=2)
    X_pca_expanded = np.expand_dims(X_pca[i], axis=2)
    print(tf.image.ssim(X_pca_zero, X_pca_expanded, 255))
print(time.time()-start)

This chunk of code throws the error - InvalidArgumentError: Expected 'tf.Tensor(False, shape=(), dtype=bool)' to be true. Summarized data: 11, 1, 1 11

Upvotes: 0

Views: 3341

Answers (1)

Mr. For Example
Mr. For Example

Reputation: 4313

So, in short, that error happen because in tf.image.ssim, the inputs X_pca_zero and X_pca_expanded size doesn't match filter_size, if you have filter_size=11 then the X_pca_zero and X_pca_expanded must be at least 11x11, example of how you could change your code:

import tensorflow as tf
import time
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA

(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data(
    path='mnist.npz'
)

x_train = x_train.reshape(60000,-1)
scaler = StandardScaler()
X_scaled = scaler.fit_transform(x_train)
pca = PCA()
pca = PCA(n_components = 16) # or 12      ->       3, 4  filter_size=3
X_pca = pca.fit_transform(X_scaled).reshape(60000, 4, 4, 1)
start = time.time()
X_pca_zero = X_pca[0]
for i in range(1,6000):
    X_pca_expanded = X_pca[i]
    print(tf.image.ssim(X_pca_zero, X_pca_expanded, 255, filter_size=4))
print(time.time()-start)

Upvotes: 3

Related Questions