Я пытаюсь создать пользовательский слой, а затем внедрить его в нейронную сеть для достижения большей точности, используя ряд Фурье.
Я извлекаю веса предыдущего NN (A), а затем смещения (B) и подаю их на пользовательский слой, но я не очень знаком с синтаксисом. Также я не совсем уверен насчет размера тензоров.
Чего мне не хватает?
from keras import backend as K
from keras.engine.topology import Layer
import keras
import tensorflow as tf
from sklearn import datasets, preprocessing, model_selection
import matplotlib.pyplot as plt
from keras.optimizers import Adam
from keras import optimizers
from keras.models import Sequential
from keras.layers import Dense, Conv2D, Dropout, Flatten, MaxPooling2D, Activation
import numpy as np
import pandas as pd
from sklearn.pipeline import Pipeline
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler, Normalizer
from keras.layers import Input, Dense, add, Lambda, Activation
from keras.models import Model
from keras.backend import sin
from keras.backend import cos
import random
from keras.utils.generic_utils import get_custom_objects
from keras.wrappers.scikit_learn import KerasClassifier
from math import pi
from keras.utils import to_categorical
mnist = tf.keras.datasets.mnist
(Xtrain, ytrain),(Xtest, ytest) = mnist.load_data()
Xtrain, Xtest = Xtrain / 255.0, Xtest / 255.0
model = Sequential()
model.add(Flatten(input_shape=(28,28)))
model.add(Dense(512, activation=tf.nn.relu))
model.add(Dense(10, activation='softmax'))
model.compile(loss=keras.losses.sparse_categorical_crossentropy,
optimizer=keras.optimizers.adam(),
metrics=['accuracy'])
model.fit(Xtrain, ytrain,
batch_size=32,
epochs=10,
verbose=1,
validation_data=(Xtest, ytest))
score = model.evaluate(Xtest, ytest, verbose=1)
print('Test loss:', score[0])
print('Test accuracy:', score[1])
A = model.layers[2].get_weights()[0]
B = model.layers[2].get_weights()[1]
A = tf.convert_to_tensor(A)
B = tf.convert_to_tensor(B)
print(A)
print(B)
class MyLayer(Layer):
output_dim = 10
def __init__(self, output_dim, **kwargs):
self.units = output_dim
super(MyLayer, self).__init__(**kwargs)
def build(self, input_shape):
self.kernel = self.add_weight('A',shape =A.shape,initializer='uniform',trainable= True)
self.bias = self.add_weight('B',shape = B.shape,initializer='zeros', trainable= True)
super(MyLayer, self).build(input_shape)
def call(self, x):
for i in range(k):
y = 0
y = y + K.dot(A,cos(i*x)) + K.dot(B,sin(i*x))
return y
def compute_output_shape(self, input_shape):
return input_shape[1]
mnist = tf.keras.datasets.mnist
(Xtrain, ytrain),(Xtest, ytest) = mnist.load_data()
Xtrain, Xtest = Xtrain / 255.0, Xtest / 255.0
k = 5
input_shape = 512
output_dim = 10
i = 0
model1 = Sequential()
model1.add(Flatten(input_shape=(28,28)))
x = model1.add(Dense(input_shape, activation='relu'))
model1.add(MyLayer(output_dim))
model1.compile(loss=keras.losses.sparse_categorical_crossentropy,
optimizer=keras.optimizers.Adam(),
metrics=['accuracy'])
model1.fit(Xtrain, ytrain,
batch_size=32,
epochs=10,
verbose=1,
validation_data=(x,y))
score = model.evaluate(x,y, verbose=1)
print('Test loss:', score[0])
print('Test accuracy:', score[1])