Я пытаюсь вычислить матрицу Якоби в Tensorflow для следующей сети: но она не работает с моей нейронной сетью!
Я нашел код матрицы Якоби в https://medium.com/unit8-machine-learning-publication/computing-the-jacobian-matrix-of-a-neural-network-in-python-4f162e5db180
К сожалению, это не работает с моей сетью ... сообщение о проблеме "ValueError: Невозможно передать значение shape (1, 51000) для Tensor 'density_1_input: 0', который имеет форму" (?, 6 ) '"
Я думаю, что это проблема в функции l oop внутри функции jacobian_tensorflow?
# Importing some Libraries
from keras.models import Sequential
from keras.layers import Dense
from keras.optimizers import SGD
import numpy as np
import statsmodels.api as sm
from sklearn.metrics import mean_squared_error
import matplotlib.pyplot as plt
from tqdm import tqdm
import tensorflow as tf
# Simulation of some data
np.random.seed (245)
nobs =10000
# Definition normalverteilte Features
x1= np.random.normal(size=nobs ,scale=1)
x2= np.random.normal(size=nobs ,scale=1)
x3= np.random.normal(size=nobs ,scale=1)
x4= np.random.normal(size=nobs ,scale=1)
x5= np.random.normal(size=nobs ,scale=1)
# Features
X= np.c_[np.ones((nobs ,1)),x1,x2,x3,x4,x5]
y= np.cos(x1) + np.sin(x2) + 2*x3 + x4 + 0.01*x5 + np.random.normal(size=nobs , scale=0.01)
#Learningrate
LR=0.05
# Number of Neurons
Neuron_Out=1
Neuron_Hidden1=64
Neuron_Hidden2=32
#The Activation function
Activate_output='linear' # für letzte Schicht verwende ich linear
Activate_hidden='relu' # unterschied ist Hidden-Layer-Neuronen werden nicht linear transformiert
#The Optimizer
Optimizer= SGD(lr=LR)
# The loss function
loss='mean_squared_error'
# Splitting Data
from sklearn.model_selection import train_test_split
x_train , x_test , y_train , y_test = train_test_split(X, y, test_size =0.15, random_state =77)
## Neural Network
from tensorflow import set_random_seed
set_random_seed (245)
# As in Medium Essa
sess = tf.InteractiveSession()
sess.run(tf.initialize_all_variables())
#Initialize the ANN
model_ANN= Sequential()
# Hidden Layer-> hier wird Hidden Layer definiert-> Anzahl der Neuronen hier sind 64, 32
# input ist 6 (also 1,x1,x2,x3,x4,x5)-> one is the first column in X Matrix
model_ANN.add(Dense(Neuron_Hidden1, activation=Activate_hidden, input_shape=(6,), use_bias=True))
model_ANN.add(Dense(Neuron_Hidden2, activation=Activate_hidden, use_bias=True))
#Output Layer-> hier wird Output-Layer defniniert
model_ANN.add(Dense(Neuron_Out, activation=Activate_output,use_bias=True))
model_ANN.summary()
#Fit the model
history_ANN=model_ANN.fit(
x_train, # training data
y_train, # training targets
epochs=125)
def jacobian_tensorflow(x):
jacobian_matrix = []
for m in range(Neuron_Out):
# We iterate over the M elements of the output vector
grad_func = tf.gradients(model_ANN.output[:, m], model_ANN.input)
gradients = sess.run(grad_func, feed_dict={model_ANN.input: x.reshape((1, x.size))})
jacobian_matrix.append(gradients[0][0,:])
return np.array(jacobian_matrix)
#Jacobian matrix computation
def jacobian_tensorflow(x):
jacobian_matrix = []
for m in range(Neuron_Out):
# We iterate over the M elements of the output vector
grad_func = tf.gradients(model_ANN.output[:, m], model_ANN.input)
gradients = sess.run(grad_func, feed_dict={model_ANN.input: x.reshape((1, x.size))})
jacobian_matrix.append(gradients[0][0,:])
return np.array(jacobian_matrix)
jacobian_tensorflow(x_train)
Как я могу использовать функцию вычисления Якобиана для моей сети?
Заранее спасибо