【问题标题】:Random sampling from multiple vectors in pythonpython中多个向量的随机抽样
【发布时间】:2020-10-19 08:05:04
【问题描述】:

所以我有一个任务来编码随机梯度体面,基本上我发现从多个向量中随机采样同时保持顺序不变有点问题。我的代码如下:

import numpy as np 
import matplotlib.pyplot as plt
import random

x = np.array([0.,0.,0.,100.,100.,300.,300.,900.,900.,900.])
y = np.array([0.,0.,1.,0.,1.,1.,1.,0.,1.,1.])


def f(b0,b1,x,y):
    vec = [y[i]*np.log(1/(1+np.exp(-b0-b1*x[i]))) + (1-y[i])*np.log(1 - (1/(1+np.exp(-b0-b1*x[i])))) for i in range(len(y))]
    return sum(vec)

def dervf0(b0,b1,x,y):
    vec = [-y[i] + (1/(1+np.exp(-b0-b1*x[i]))) for i in range(len(y))]
    return sum(vec)
def dervf1(b0,b1,x,y):
    vec = [-x[i]*(y[i]-(1/(1+np.exp(-b0-b1*x[i])))) for i in range(len(y))]
    return sum(vec)

def SGD(v,x,y,tol,maxiter):
    x = #random selection
    y= #random selection
    for i in range(maxiter):
        theta_new = v - 0.001*np.array(
            [dervf0(v[0], v[1], x, y),
             dervf1(v[0], v[1], x, y)])
        if np.linalg.norm(theta_new - v) < tol: 
            break
        else:
            v = theta_new
            #print('i\t{}\tv\t{}\ttheta_new\t{}'.format(i, v, theta_new))
    return theta_new,i

如您所见,我有 2 个向量,x 和 y,它们是链接的,例如 x[0] 是一个实验,它给了我们 y[0] = 0。在这里没有结构的随机抽样是没有意义的在我看来。我正在努力做的是在 SGD 函数中,我想要 x 的 n 点和 y 的 n 点,但结构正确!任何帮助表示赞赏!

是的

【问题讨论】:

    标签: python random sgd stochastic-gradient


    【解决方案1】:

    您可以使用以下方法获取要采样的索引列表-

    import random
    
    x = ['This', 'is', 'a', 'random', 'sampling', 'example']
    
    n = len(x)
    k = 5
    indices_to_sample = sorted(random.sample(range(n),k)) # Chooses k out of n indices and sorts them
    for i in indices_to_sample:
        print(x[i]) # Gets x at index i
    

    阅读更多random.sample docs

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-07
      • 1970-01-01
      • 1970-01-01
      • 2017-06-22
      • 2021-11-02
      • 1970-01-01
      • 1970-01-01
      • 2018-09-12
      相关资源
      最近更新 更多