我有一些从sqlite数据库获取的小批量数据,其中包括整数和浮点类型的数据x,以及二进制标签0和1的数据y。我正在寻找像scikit-learn中的
在Tensorflow 2中,分层似乎不是直接可能的。我的解决方案对我有效,但由于所有的重塑和转置而需要很长时间。
X_train,X_test,y_train,y_test = sklearn.model_selection.train_test_split(y,x,test_size = 0.1,random_state = 1,stratify = True)
这样的东西,其中关键词可以使数据分层(即相同数量的0类和1类实例)。在Tensorflow 2中,分层似乎不是直接可能的。我的解决方案对我有效,但由于所有的重塑和转置而需要很长时间。
def stratify(x, y):
# number of positive instances (the smaller class)
pos = np.sum(y).item() # how many positive bonds there are
x = np.transpose(x)
# number of features
f = np.shape(x)[1]
# filter only class 1
y = tf.transpose(y)
x_pos = tf.boolean_mask(x,
y_pos = tf.boolean_mask(y, y)
# filter only class 1
x_neg = tf.boolean_mask(x, tf.bitwise.invert(y)-254)
x_neg = tf.reshape(x_neg, [f,-1])
y_neg = tf.boolean_mask(y, tf.bitwise.invert(y)-254)
# just take randomy as many class-0 as there are class-1
x_neg = tf.transpose(tf.random.shuffle(tf.transpose(x_neg)))
x_neg = x_neg[:,0:pos]
y_neg = y_neg[0:pos]
# concat the class-1 and class-0 together, then shuffle, and concat back together
x = tf.concat([x_pos,tf.transpose(x_neg)],0)
y = tf.concat([y_pos, tf.transpose(y_neg)],0)
xy = tf.concat([tf.transpose(x), tf.cast(np.reshape(y,[1, -1]), tf.float64)],0)
xy = tf.transpose((tf.random.shuffle(tf.transpose(xy)))) # because there is no axis arg in shuffle
x = xy[0:f,:]
x = tf.transpose(x)
y = xy[f,:]
return x, y
我很高兴看到关于我的函数或新颖、更简单的想法的反馈和改进意见。