如何使用sgd找到转换矩阵

时间:2018-03-20 04:09:42

标签: python matrix transformation stochastic

这看起来很简单,但我无法让事情发挥作用。我100维向量空间,我在每个空间中有几个匹配的向量。我想找到转换矩阵(W),以便:

向量空间中的

a_vector [0]在向量空间B中的x W = b_vector [0](或近似值)。

所以一篇论文提到了这个公式。

enter image description here

所以没有偏见术语,我们通常看不到激活。

我尝试过使用sklearns Linear Regression而没有取得多大成功。

from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error

regression_model = LinearRegression(fit_intercept=True)
regression_model.fit(X_train, y_train)

regression_model.score(X_test, y_test)
> -1451478.4589335269 (!!???)

y_predict = regression_model.predict(X_test)

regression_model_mse = mean_squared_error(y_predict, y_test)

regression_model_mse = 524580.06

尝试张量流没有太大的成功。不要关心这个工具 - tensorflow,sklearn - 只是寻求解决方案的帮助。

感谢。

修改

所以我手动滚动下面的代码 - 最大化余弦sim(表示预测点与实际点的接近程度 - 1.00 =完美匹配) - 但它非常慢。

shape = (100,100)
W1 = np.random.randn(*shape).astype(np.float64) / np.sqrt(sum(shape))
avgs = []
for x in range(1000):
    shuffle(endevec)
    distance = [0]
for i,x in enumerate(endevec):
    pred1 = x[0].dot(W1) 
    cosine = 1 - scipy.spatial.distance.cosine(pred1, x[1])
    distance.append(cosine)
    diff = pred1 - x[0]
    gradient = W1.T.dot(diff) / W1.shape[0]
    W1 += -gradient * .0001
avgs.append(np.mean(distance))
sys.stdout.write('\r')
# the exact output you're looking for:
sys.stdout.write(str(avgs[-1]))
sys.stdout.flush()

编辑2

下面的Jeanne Dark对于使用以下方法找到转换矩阵有一个很好的答案:     M = np.linalg.lstsq(source_mtrx [:N],target_mtrx [:N])[0]

在我匹配的vecs的数据集中,使用此方法找到的TM的预测vecs是:

minmax=(-0.09405095875263214, 0.9940633773803711)
mean=0.972490919224675 (1.0 being a perfect match) 
variance=0.0011325349465895844
skewness=-18.317443753033665
kurtosis=516.5701661370497

有很多非常大的异常值。

余弦sim的情节是:

enter image description here

1 个答案:

答案 0 :(得分:1)

昨天我遇到了完全相同的问题。我最终使用numpy.linalg.lstsq ,我认为它有效。

# find tranformation matrix M so that: source_matrix∙M = target_matrix based 
          #on top n most frequent terms in the target corpus
n=500  # the choice of n depends on the size of your vocabulary
M=np.linalg.lstsq(source_mtrx[:n],target_mtrx[:n])[0]
print M.shape # returns (100,100)

# apply this tranformation to source matrix:
new_mtrx= np.array([np.dot(i, M) for i in source_mtrx])

另请参阅本文Lexical Comparison Between Wikipedia and Twitter Corpora by Using Word Embeddings。它们基于您提到的论文,并且它们遵循相同的方法,但它们更详细地解释了实现。例如,他们建议为了找到变换矩阵M,我们只使用前n个最常用项的向量,然后,在我们将变换应用于源矩阵之后,我们计算出其余条款的相似性。

如果您找到另一种基于SGD计算M的解决方案,请告诉我。

相关问题