博文

目前显示的是 八月, 2023的博文

修正layer_name = 'block1_conv2'

原始程式碼: layer_name = 'block1_conv2' layer = layer_dict[layer_name] activations = get_activations(vgg16, layer, input_img_data) 出現錯誤: ValueError Traceback (most recent call last) Cell In[35], line 3 1 layer_name = 'block1_conv2' 2 layer = layer_dict[layer_name] ----> 3 activations = get_activations(vgg16, layer, input_img_data) Cell In[34], line 2, in get_activations(model, layer, input_img_data) 1 def get_activations(model, layer, input_img_data): ----> 2 activations_f = K.function([model.layers[0].input, K.learning_phase()], [layer.output,]) 3 activations = activations_f((input_img_data, False)) 4 return activations File C:\ProgramData\Anaconda3\lib\site-packages\keras\src\backend.py:4656, in function(inputs, outputs, updates, name, **kwargs) 4650 raise ValueError( 4651 "`updates` argument is not supported during " 4652 "eager execution. You pass...
原始程式碼: <img src=" https://miro.medium.com/ max/1250/1*Gs_ f7aWJQktSkIWLy2m70g.png " width="75%"> 出現錯誤: Cell In[13], line 1 <img src=" https://miro.medium.com/ max/1250/1*Gs_ f7aWJQktSkIWLy2m70g.png " width="75%"> ^   SyntaxError :  invalid syntax   改成這樣就可以了 from IPython.display import Image Image(url="https://miro.medium.com/max/1250/1*Gs_f7aWJQktSkIWLy2m70g.png", width=500)

修正plt.imshow(generate_pattern('block3_conv1', 0))

 原始程式碼: plt.imshow(generate_pattern('block3_conv1', 0)) plt.show() 出現錯誤: RuntimeError Traceback (most recent call last) Cell In[39], line 1 ----> 1 plt.imshow(generate_pattern('block3_conv1', 0)) 2 plt.show() Cell In[36], line 7, in generate_pattern(layer_name, filter_index, size) 4 loss = K.mean(layer_output[:, :, :, filter_index]) 6 # Compute the gradient of this loss with respect to the input image ----> 7 grads = K.gradients(loss, model.input)[0] 9 # Normalize the gradient 10 grads /= (K.sqrt(K.mean(K.square(grads))) + 1e-5) File C:\ProgramData\Anaconda3\lib\site-packages\keras\src\backend.py:4695, in gradients(loss, variables) 4683 @keras_export("keras.backend.gradients") 4684 @doc_controls.do_not_generate_docs 4685 def gradients(loss, variables): 4686 """Returns the gradients of `loss` w.r.t. `variables`. 4687 4688 Args: (...) 4693 A...
原始程式碼: def generate_pattern(layer_name, filter_index, size=150):     # 構建一個最大化激活的 損失函數  loss function     # 考慮的層的 第n個 filter     layer_output = model.get_layer(layer_name). output     loss = K.mean(layer_output[:, :, :, filter_index])     # 計算這種損失的輸入圖像的梯度     grads = K.gradients(loss, model.input)[0]     # Normalization gradient 梯度     grads /= (K.sqrt(K.mean(K.square(grads) )) + 1e-5)     # 函數返回 給定 輸入圖片的 損失 和 梯度     iterate = K.function([model.input], [loss, grads])         # 帶有一些噪音的灰色圖像     input_img_data = np.random.random((1, size, size, 3)) * 20 + 128.     # Run 梯度上升 40步     step = 1.     for i in range(40):         loss_value, grads_value = iterate([input_img_data])         input_img_data += grads_value * step             img = input_img_da...

修正input_img_data = np.random.random((1, 150, 150, 3)) * 20 + 128.

原始碼如下: # 灰色圖像 帶有一些噪音 input_img_data = np.random.random((1, 150, 150, 3)) * 20 + 128. # 40 steps forgradient ascent step = 1. # 每個梯度更新的幅度 for i in range(40): # 計算損失值和梯度值 loss_value, grads_value = iterate([input_img_data]) # 調整輸入圖像的方向,使損失最大化 input_img_data += grads_value * step 出現錯誤: NameError Traceback (most recent call last) Cell In[30], line 9 6 step = 1. # 每個梯度更新的幅度 7 for i in range(40): 8 # 計算損失值和梯度值 ----> 9 loss_value, grads_value = iterate([input_img_data]) 10 # 調整輸入圖像的方向,使損失最大化 11 input_img_data += grads_value * step   NameError: name 'iterate' is not defined   修正成這樣就可以了 import numpy as np import tensorflow as tf from tensorflow.keras import optimizers # The rest of your code remains the same # Compile your model before using it in the gradient computation model.compile(loss='binary_crossentropy',               optimizer=optimizers.RMSpr...

修正iterate = K.function([model.input], [loss, grads])

原始程式碼: iterate = K.function([model.input], [loss, grads]) # 測試一下 import numpy as np loss_value, grads_value = iterate([np.zeros((1, 150, 150, 3))]) 出現錯誤 ValueError Traceback (most recent call last) Cell In[28], line 1 ----> 1 iterate = K . function ( [ model . input ] , [ loss , grads ] ) 3 # 測試一下 4 import numpy as np File C:\ProgramData\Anaconda3\lib\ site-packages\keras\src\ backend.py:4656 , in function (inputs, outputs, updates, name, **kwargs) 4650 raise ValueError ( 4651 " `updates` argument is not supported during " 4652 " eager execution. You passed: %s " % (updates,) 4653 ) 4654 from keras . src import models -> 4656 model = models . Model ( inputs = inputs , outputs = outputs ) 4658 wrap_outputs = isinstance (outputs, list ) and len (outputs) == 1 4660 def func (model_inputs): File C:\ProgramData\Anaconda3\lib\ site-packages...

修正grads /= (K.sqrt(K.mean(K.square(grads))) + 1e-5)

原始程式碼: grads /= (K.sqrt(K.mean(K.square(grads))) + 1e-5) 出現錯誤: ValueError Traceback (most recent call last) Cell In[26], line 3 1 # 1e-5 在劃分之前,以避免意外地 除以 0 ----> 3 grads /= (K.sqrt(K.mean(K.square(grads))) + 1e-5) File C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\util\traceback_utils.py:153, in filter_traceback.<locals>.error_handler(*args, **kwargs) 151 except Exception as e: 152 filtered_tb = _process_traceback_frames(e.__traceback__) --> 153 raise e.with_traceback(filtered_tb) from None 154 finally: 155 del filtered_tb File C:\ProgramData\Anaconda3\lib\site-packages\keras\src\backend.py:3008, in square(x) 2996 @keras_export("keras.backend.square") 2997 @tf.__internal__.dispatch.add_dispatch_support 2998 @doc_controls.do_not_generate_docs 2999 def square(x): 3000 """Element-wise square. 3001 3002 Args: (...) 3006 A tensor. 3007 """ -> ...

修正grads = K.gradients(loss, model.input)[0]

原始程式碼: grads = K.gradients(loss, model.input)[0] 出現錯誤: RuntimeError Traceback (most recent call last) Cell In[19], line 4 1 # 從 gradient 返回一個張量列表(在這種情況下大小為1) 2 # 因此我們只保留第一個元素 - 這是一個張量。 ----> 4 grads = K.gradients(loss, model.input)[0] File C:\ProgramData\Anaconda3\lib\site-packages\keras\src\backend.py:4695, in gradients(loss, variables) 4683 @keras_export("keras.backend.gradients") 4684 @doc_controls.do_not_generate_docs 4685 def gradients(loss, variables): 4686 """Returns the gradients of `loss` w.r.t. `variables`. 4687 4688 Args: (...) 4693 A gradients tensor. 4694 """ -> 4695 return tf.compat.v1.gradients( 4696 loss, variables, colocate_gradients_with_ops=True 4697 ) File C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\ops\gradients_impl.py:165, in gradients(ys, xs, grad_ys, name, colocate_gradients_with_ops, gate_gradients, aggregation_met...

修正test_loss, test_acc = model.evaluate_generator(test_generator, steps=50)錯誤

 原程式碼: test_loss, test_acc = model.evaluate_generator(test_generator, steps=50) 出現錯誤: C:\Users\User\AppData\Local\Temp\ipykernel_7968\2530680794.py:1: UserWarning: `Model.evaluate_generator` is deprecated and will be removed in a future version. Please use `Model.evaluate`, which supports generators. test_loss, test_acc = model.evaluate_generator(test_generator, steps=50) 修正成這樣就好了 test_loss, test_acc = model.evaluate(test_generator, steps=50)

修正%%time history = model.fit_generator錯誤

 原程式碼: %%time history = model.fit_generator( train_generator, steps_per_epoch=100, epochs = 10, # epoch 100 validation_data = validation_generator, validation_steps = 50) 出現錯誤 <timed exec>:1: UserWarning: `Model.fit_generator` is deprecated and will be removed in a future version. Please use `Model.fit`, which supports generators. 修正成這樣就好了 import numpy as np from tensorflow.keras.utils import Sequence from tensorflow.keras.preprocessing.image import ImageDataGenerator class MyImageDataGenerator(Sequence): def __init__(self, data_directory, batch_size, target_size, shuffle=True): self.data_directory = data_directory self.batch_size = batch_size self.target_size = target_size self.shuffle = shuffle self.image_datagen = ImageDataGenerator( rescale=1.0 / 255.0, # Normalize pixel values between 0 and 1 shear_range=0.2, zoom_range=0.2, h...

修正model.save('cats_and_dogs_small_1.h5') # Ver: 001

 原程式碼: model.save('cats_and_dogs_small_1.h5') # Ver: 001 出現錯誤: C:\ProgramData\Anaconda3\lib\site-packages\keras\src\engine\training.py:3000: UserWarning: You are saving your model as an HDF5 file via `model.save()`. This file format is considered legacy. We recommend using instead the native Keras format, e.g. `model.save('my_model.keras')`. saving_api.save_model( 修正成這樣就好了 model.save('cats_and_dogs_small_1.keras')  # or any other desired file name with the .keras extension

修正history = model.fit_generator

 原程式碼 history = model.fit_generator( train_generator, steps_per_epoch=100, epochs = 30 , # 30 validation_data = validation_generator, validation_steps = 50) 出現錯誤 C:\Users\User\AppData\Local\Temp\ipykernel_7968\3385221972.py:1: UserWarning: `Model.fit_generator` is deprecated and will be removed in a future version. Please use `Model.fit`, which supports generators. history = model.fit_generator( 修正成這樣就好了 history = model.fit( train_generator, steps_per_epoch=100, epochs=30, validation_data=validation_generator, validation_steps=50 )

修正model.compile(optimizer=optimizers.RMSprop(lr=1e-4), loss='binary_crossentropy', metrics=['acc'])

 原程式碼: model.compile(optimizer=optimizers.RMSprop(lr=1e-4), loss='binary_crossentropy', metrics=['acc']) 出現錯誤: WARNING:absl:`lr` is deprecated in Keras optimizer, please use `learning_rate` or use the legacy optimizer, e.g.,tf.keras.optimizers.legacy.RMSprop. 只要修正成這樣就好了 model.compile(optimizer=optimizers.RMSprop(learning_rate=1e-4), loss='binary_crossentropy', metrics=['acc'])

修正prediction=model.predict_classes(x_test_normalize)

 原程式碼:prediction=model.predict_classes(x_test_normalize)  出現錯誤: AttributeError Traceback (most recent call last) Cell In[62], line 1 ----> 1 prediction = model . predict_classes (x_test_normalize) AttributeError : 'Sequential' object has no attribute 'predict_classes' 修正成這樣就好了 import numpy as np # Assuming you have defined and compiled your Keras model # model = Sequential() # Your model definition # model.compile(...) # Your model compilation # Assuming you have normalized test data `x_test_normalize` # Use the predict method to get probability scores probabilities = model.predict(x_test_normalize) # Use np.argmax to find the predicted class indices predicted_classes = np.argmax(probabilities, axis=1)
原程式碼:model.save('cifar10_trained_model.h6') 出現錯誤: FailedPreconditionError Traceback (most recent call last) Cell In[56], line 1 ----> 1 model . save ( ' cifar10_trained_model.h6 ' ) File C:\ProgramData\Anaconda3\lib\site-packages\keras\src\utils\traceback_utils.py:70 , in filter_traceback.<locals>.error_handler (*args, **kwargs) 67 filtered_tb = _process_traceback_frames(e . __traceback__) 68 # To get the full stack trace, call: 69 # `tf.debugging.disable_traceback_filtering()` ---> 70 raise e . with_traceback(filtered_tb) from None 71 finally : 72 del filtered_tb File C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\lib\io\file_io.py:513 , in recursive_create_dir_v2 (path) 501 @tf_export ( " io.gfile.makedirs " ) 502 def recursive_create_dir_v2 (path): 503 """Creates a directory and all parent/intermediate directories. ...

修正import matplotlib.pyplot as plt show_train_history(train_history)

原程式碼:import matplotlib.pyplot as plt   show_train_history(train_history)   出現錯誤: KeyError Traceback (most recent call last) Cell In[51], line 2 1 import matplotlib . pyplot as plt ----> 2 show_train_history ( train_history ) Cell In[50], line 5 , in show_train_history (train_history) 3 fig . set_size_inches( 16 , 6 ) 4 plt . subplot( 121 ) ----> 5 plt . plot( train_history . history [ " acc " ] ) 6 plt . plot(train_history . history[ " val_acc " ]) 7 plt . title( " Train History " ) KeyError : 'acc' 修正成這樣就好了 import matplotlib.pyplot as plt def show_train_history(history):     fig, ax = plt.subplots(figsize=(16, 6))     # Accessing the history data from the History object     plt.plot(history.history["accuracy"], label='Training Accuracy')     plt.plot(history.history["val_accuracy"], label='Validation Accuracy')     plt.xlabel...

修正from keras.utils import np_utils

原程式碼:from keras.utils import np_utils y_train_onehot=np_utils.to_categorical(y_train_label) y_test_onehot=np_utils.to_categorical(y_test_label) 出現錯誤: ImportError Traceback (most recent call last) Cell In[42], line 1 ----> 1 from keras . utils import np_utils 2 y_train_onehot = np_utils . to_categorical(y_train_label) 3 y_test_onehot = np_utils . to_categorical(y_test_label) ImportError : cannot import name 'np_utils' from 'keras.utils' (C:\ProgramData\Anaconda3\lib\site-packages\keras\utils\__init__.py) 修正成這樣就好了 from tensorflow.keras.utils import to_categorical y_train_onehot = to_categorical(y_train_label) y_test_onehot = to_categorical(y_test_label)