Home>

Image anomaly detection using Variational Autoencoder Part 2 (Shiojiri ML Mokumokukai # 7)
We would like to detect anomalies using VAE and the original data set by referring to the code of the site at the above URL.

-------------------------------------------------- -----------------------
AttributeError Traceback (most recent call last)<ipython-input-37-02dbf7abd247>in<module>    2 if y_train [i] == 1: # 7 for sneakers
      3 temp = x_train [i,:,:,:]
---->4 x_train_b.numpy.append (temp.reshape ((x_train_shape [1],],

x_train_shape [2],

x_train_shape [3]))))
      Five 
      6 x_train_b = np.array (x_train_b)
AttributeError:'numpy.ndarray' object has no attribute'numpy'


I get the above error in the middle of the code and I don't know how to improve the code.

code
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from keras.layers import Lambda, Input, Dense, Reshape
from keras.models import Model
from keras.losses import mse
from keras.utils import plot_model
from keras import backend as K
from keras.layers import BatchNormalization, Activation, Flatten
from keras.layers.convolutional import Conv2DTranspose, Conv2D
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as colors
import os
from sklearn import metrics
os.chdir ('/ Users/user_name/desktop/VAE')
os.getcwd ()
def result_score (model, x, name, height = 80, width = 80, move = 2):
    score = []
    for k in range (len (x)):
        max_score = -1000000000if k% 100 == 0:
          print (k)
        for i in range (int ((x.shape [1] -height)/move) +1):
            for j in range (int ((x.shape [2] -width)/move) +1):
                x_sub = x [k, i * move: i * move + height, j * move: j * move + width, 0]
                x_sub = x_sub.reshape (1, height, width, 1)
                #Conventional method
                if name == "old_":
                    #Score
                    temp_score = model.evaluate (x_sub, batch_size = 1, verbose = 0)
                    if temp_score>max_score:
                        max_score = temp_score
                #Proposed method
                else: else:
                    #Score
                    mu, sigma = model.predict (x_sub, batch_size = 1, verbose = 0)
                    loss = 0
                    for o in range (height):
                        for l in range (width):
                            loss + = 0.5 * (x_sub [0, o, l, 0] --mu [0, o, l, 0]) ** 2/sigma [0, o, l, 0]
                    if loss>max_score:
                       max_score = loss
        score.append (max_score)
    return (score)
def cut_img (x, number, height = 224, width = 224):
    print ("cutting images ...")
    x_out = []
    x_shape = x.shape
    for i in range (number):
        shape_0 = np.random.randint (0, x_shape [0])
        shape_1 = np.random.randint (0, x_shape [1]-height)
        shape_2 = np.random.randint (0, x_shape [2]-width)
        temp = x [shape_0, shape_1: shape_1 + height, shape_2: shape_2 + width, 0]
        x_out.append (temp.reshape ((height, width, x_shape [3])))
    print ("Complete.")
    x_out = np.array (x_out)
    return x_out
# reparameterization trick
# instead of sampling from Q (z | X), sample eps = N (0, I)
# z = z_mean + sqrt (var) * eps
def sampling (args):z_mean, z_log_var = args
    batch = K.shape (z_mean) [0]
    dim = K.int_shape (z_mean) [1]
    # by default, random_normal has mean = 0 and std = 1.0
    epsilon = K.random_normal (shape = (batch, dim))
    return z_mean + K.exp (0.5 * z_log_var) * epsilon
# dataset
from bcn_dataset import BCN_Dataset2
(x_train, y_train), (x_test, y_test) = BCN_Dataset2.create_bcn ()
x_train = x_train.reshape (x_train.shape [0],

 224, 224, 3)
x_test = x_test.reshape (x_test.shape [0],

 224, 224, 3)
x_train = x_train.astype ('float32')/255
x_test = x_test.astype ('float32')/255
x_train_b = []
x_test_b = []
x_test_n = []
x_train_shape = x_train.shape
for i in range (len (x_train)):
  if y_train [i] == 1: # 7 for sneakers
    temp = x_train [i,:,:,:]
    x_train_b.numpy.append (temp.reshape ((x_train_shape [1],],

x_train_shape [2],

x_train_shape [3]))))
x_train_b = np.array (x_train_b)
x_train_b = cut_img (x_train_b, 50)
print ("train data:", len (x_train_b))
What i am trying

'numpy.ndarray' object has no attribute'append' error
Last time, I asked a similar question, and the respondent said, "ndarrayToappend ()There is no method.numpy.append ()There is a method of. I tried the code by trial and error (such as adding numpy before append), but it didn't work and the same error occurred. I'm worried about my head.
I'm very sorry if you have to change all the code or if the dataset you created is created incorrectly, but any small thing is fine, so please give me some advice.

Supplement

My PC is macOS Catalina version 10.15.5
Python version is 3.6.5
I'm using a Jupiter notebook

  • Answer # 1

    Since numpy.append is a function, its usage is as follows.

    numpy.append (original array, target array)

    Since it is a function, it has a return value. So, please define the return value with some variable and perform the subsequent processing.

  • Answer # 2

    'numpy.ndarray' object has no attribute'numpy'

    'numpy.ndarray' does not have an attribute called'numpy'.
    You say
    What's in x_train_b?

  • Answer # 3

    import numpy as npSo in the codenumpyWhen you want to callnpLet's write.