小编ppl*_*lat的帖子

为什么scikit-learn的最近邻居似乎没有返回适当的余弦相似距离?

我试图使用scikit的最近邻实现,从随机值矩阵中找到最接近给定列向量的列向量.

该代码应该找到第21列的最近邻居,然后检查这些邻居与第21列的实际余弦相似性.

from sklearn.neighbors import NearestNeighbors
import sklearn.metrics.pairwise as smp
import numpy as np

test=np.random.randint(0,5,(50,50))
nbrs = NearestNeighbors(n_neighbors=5, algorithm='auto', metric=smp.cosine_similarity).fit(test)
distances, indices = nbrs.kneighbors(test)

x=21   

for idx,d in enumerate(indices[x]):

    sim2 = smp.cosine_similarity(test[:,x],test[:,d])


    print "sklearns cosine similarity would be ", sim2
    print 'sklearns reported distance is', distances[x][idx]
    print 'sklearns if that distance was cosine, the similarity would be: ' ,1- distances[x][idx]
Run Code Online (Sandbox Code Playgroud)

输出看起来像

sklearns cosine similarity would be  [[ 0.66190748]]
sklearns reported distance is 0.616586738214
sklearns if that distance was cosine, the …
Run Code Online (Sandbox Code Playgroud)

nearest-neighbor python-2.7 cosine-similarity scikit-learn

5
推荐指数
1
解决办法
4723
查看次数

C - 又一个strtok()和free()问题

我试图了解如何在调用后完全释放内存strtok().我在这里阅读了大部分已回答的问题,似乎没有一个问题可以解决我的困惑.如果这是一个副本,请随时指出我回答我的问题的方向

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main()
{
    char * aliteral = "Hello/world/fine/you";

    char * allocatedstring;

    char * token;
    int i=0;


    allocatedstring=(char *) malloc(sizeof(allocatedstring)*21);
    allocatedstring=strcpy(allocatedstring,aliteral);

    token = strtok(allocatedstring, "/");
    token = strtok(NULL, "/");
    token = strtok(NULL, "/");
    token = strtok(NULL, "/");



    printf("%s\n",allocatedstring);
    printf("%s\n",token);

    free(allocatedstring);


    return 0;
}
Run Code Online (Sandbox Code Playgroud)

allocatedstring在这里释放只会将字符串释放到\0替换strtok分隔符的第一个字符.所以它只会在"你好"之前清除.我检查了使用eclipse调试器并监视内存地址.

我如何清除剩下的部分?我尝试了两件事,有一个额外的指针指向allocatestring的开始并释放(没有工作)并在调用后释放令牌strtok()(也没有工作)

那么如何清理allocatedstring现在之间\0的部分呢?

编辑:为了澄清,看到eclipse调试器中的内存地址块,我在最初通过调用分配的内存块中看到字符串"HELLO WORLD FINE YOU" malloc.在调用之后free(),包含"HELLO"和第一个的块\0变成了乱码,但其余的块保留了字符"FINE YOU".我认为这意味着他们没有被释放.

c free strtok

2
推荐指数
1
解决办法
293
查看次数