Last active
August 7, 2019 12:53
-
-
Save namakemono/c34e9504735ec08b888a8de0e447c3a4 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
import keras | |
from sklearn.model_selection import train_test_split | |
""" | |
ベクトルx,yは与えられているとする. | |
y = A * x となる行列Aを求める. | |
- 行列とベクトルの積, <https://stackoverflow.com/questions/46570963/keras-lambda-layer-for-matrix-vector-multiplication> | |
""" | |
def build_model(input_dim=3, output_dim=4): | |
x = keras.models.Input(shape=(input_dim,)) | |
A = np.zeros((input_dim, output_dim)) | |
y = keras.layers.Dense(output_dim, trainable=True, use_bias=False, name="matrix")(x) | |
model = keras.models.Model(x, y) | |
return model | |
def load_data(): | |
A = np.random.random((4,3)) | |
print(A) | |
x, y = [], [] | |
for i in range(10000): | |
x_i = np.random.random(3) | |
y_i = np.dot(A, x_i) | |
x.append(x_i) | |
y.append(y_i) | |
x = np.asarray(x) | |
y = np.asarray(y) | |
x_train, x_test, y_train, y_test = train_test_split(x, y) | |
return (x_train, y_train), (x_test, y_test) | |
def run(): | |
(x_train, y_train), (x_test, y_test) = load_data() | |
print(x_train.shape, x_test.shape, y_train.shape) | |
model = build_model() | |
print(model.summary()) | |
model.compile( | |
optimizer='rmsprop', | |
loss='mae', | |
metrics=['accuracy'] | |
) | |
model.fit( | |
x_train, | |
y_train, | |
validation_data=(x_test, y_test), | |
epochs=10, | |
) | |
for layer in model.layers: | |
if layer.name == "matrix": | |
weights = layer.get_weights() | |
print(weights) | |
if __name__ == "__main__": | |
run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment