【发布时间】:2020-08-11 23:52:38
【问题描述】:
我想通过将数据与稀疏矩阵相乘来在损失函数中执行线性变换。
我已经为它写了一些虚拟代码,请帮我转换一下:
from __future__ import absolute_import, division, print_function, unicode_literals
import numpy as np
import pandas as pd
from scipy import sparse
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
# I have a 0-1 sparse matrix
sparse_matix = sparse.random(1000, 20, density=.2, format='coo', data_rvs=np.ones,dtype='f' ).astype('int8')
sparse_matix # <1000x20 sparse matrix of type '<class 'numpy.int8'>' with 4000 stored elements in COOrdinate format>
# Dummy data generator
def data_gen():
for i in range(100):
yield np.random.normal(size=(500, 1000)).astype('float32')
dataset = tf.data.Dataset.from_generator(data_gen, output_types=np.dtype('float32'), output_shapes=(500, 1000)).batch(5)
dataset_batch = dataset.__iter__().__next__()
dataset_batch.shape # TensorShape([5, 500, 1000])
def fn(dataset_batch): # i want this function to written completly in tensorflow, so that i can use this in my loss function
dataset_batch = dataset_batch.numpy()
return np.array([dataset_batch[i]*sparse_matix for i in range(dataset_batch.shape[0])]) # mutiple with sparse matrix
fn(dataset_batch).shape # (5, 500, 20)
请帮助我使用 tensorflow 编写 fn。一个 Tensorflow 层就可以了
【问题讨论】:
标签: python numpy tensorflow matrix keras