AttributeError: 'SymbolicTensor' object has no attribute 'numpy'を解決したい

Python

1# 必要なライブラリのインストール2!pip install tensorflow 3 4import pandas as pd 5import numpy as np 6import tensorflow as tf 7from tensorflow.keras.models import Sequential 8from tensorflow.keras.layers import Dense, Dropout 9from sklearn.model_selection import train_test_split 10from sklearn.metrics import classification_report, confusion_matrix, f1_score 11 12# カスタムF1スコアメトリックの定義13class F1ScoreMacro(tf.keras.metrics.Metric):14 def __init__(self, name='f1_score_macro', **kwargs):15 super(F1ScoreMacro, self).__init__(name=name, **kwargs)16 self.f1 = self.add_weight(name='f1', initializer='zeros', dtype=tf.float32)17 18 def update_state(self, y_true, y_pred, sample_weight=None):19 y_true = tf.argmax(y_true, axis=1, output_type=tf.int32)20 y_pred = tf.argmax(y_pred, axis=1, output_type=tf.int32)21 22 # Extract class labels from one-hot encoded tensors23 y_true_labels = tf.argmax(y_true, axis=1)24 y_pred_labels = tf.argmax(y_pred, axis=1)25 26 y_true_np = y_true.numpy()27 y_pred_np = y_pred.numpy()28 29 f1 = tf.py_function(func=custom_f1_score, inp=[y_true_np, y_pred_np], Tout=tf.float32, name='f1_score')30 self.f1.assign_add(f1)31 32 def result(self):33 return self.f1 34 35 def reset_states(self):36 self.f1.assign(0.0)37 38#39,,,40(dataの読込、分割)41,,,42 43# モデルの構築44model = Sequential()45model.add(Dense(64, input_dim=X_train_split.shape[1], activation='relu'))46model.add(Dropout(0.5))47model.add(Dense(32, activation='relu'))48model.add(Dropout(0.5))49model.add(Dense(3, activation='softmax')) # 出力層、クラス数は350 51# モデルのコンパイル52model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=[F1ScoreMacro()])53 54# モデルのトレーニング55history = model.fit(X_train_split, y_train_split, validation_data=(X_val, y_val), epochs=50, batch_size=32, verbose=1)

コメントを投稿

0 コメント