In [0]:
!git clone https://github.com/google/TensorNetwork.git
!pip install ./TensorNetwork
In [0]:
import tensorflow as tf
import tensornetwork as tn
import numpy as np
from tensornetwork.tn_keras.dense import DenseDecomp
from tensornetwork.tn_keras.mpo import DenseMPO
from tensorflow.keras.layers import Dense
from tensorflow.keras.models import Sequential
import math
In [0]:
def dummy_data(input_dim):
np.random.seed(42)
# Generate dummy data for use in tests
data = np.random.randint(10, size=(100, input_dim))
labels = np.concatenate((np.ones((50, 1)), np.zeros((50, 1))), axis=0)
return data, labels
In [0]:
data, labels = dummy_data(1296)
# Build a fully connected network
model = Sequential()
model.add(Dense(512, use_bias=True, activation='relu', input_shape=(data.shape[1],)))
model.add(Dense(128, use_bias=True, activation='relu'))
model.add(Dense(1, use_bias=True, activation='sigmoid'))
# Build the same fully connected network using TN layer DenseDecomp
decomp_model = Sequential()
decomp_model.add(DenseDecomp(512, decomp_size=64, use_bias=True, activation='relu', input_shape=(data.shape[1],)))
decomp_model.add(DenseDecomp(128, decomp_size=64, use_bias=True, activation='relu'))
decomp_model.add(DenseDecomp(1, decomp_size=8, use_bias=True, activation='sigmoid'))
# Build the same fully connected network using TN layer DenseMPO
mpo_model = Sequential()
mpo_model.add(DenseMPO(256, num_nodes=4, bond_dim=8, use_bias=True, activation='relu', input_shape=(1296,)))
mpo_model.add(DenseMPO(81, num_nodes=4, bond_dim=4, use_bias=True, activation='relu'))
mpo_model.add(Dense(1, use_bias=True, activation='sigmoid'))
In [0]:
model.summary()
In [0]:
decomp_model.summary()
In [0]:
mpo_model.summary()
In [0]:
print(f'Compression factor from tensorization with DenseDecomp: {model.count_params() / decomp_model.count_params()}')
print(f'Compression factor from tensorization with DenseMPO: {model.count_params() / mpo_model.count_params()}')
In [0]:
model.compile(optimizer='adam',
loss='binary_crossentropy',
metrics=['accuracy'])
# Train the model for 10 epochs
history = model.fit(data, labels, epochs=10, batch_size=32)
In [0]:
decomp_model.compile(optimizer='adam',
loss='binary_crossentropy',
metrics=['accuracy'])
# Train the tensorized model for 10 epochs
history = decomp_model.fit(data, labels, epochs=10, batch_size=32)
In [0]:
mpo_model.compile(optimizer='adam',
loss='binary_crossentropy',
metrics=['accuracy'])
# Train the tensorized model for 10 epochs
history = mpo_model.fit(data, labels, epochs=10, batch_size=32)
In [0]: