python类linspace()的实例源码

p4 momentum SGD.py 文件源码 项目:mlbasic 作者: tsycnh 项目源码 文件源码 阅读 40 收藏 0 点赞 0 评论 0
def draw_hill(x,y):
    a = np.linspace(-20,20,100)
    print(a)
    b = np.linspace(-20,20,100)
    x = np.array(x)
    y = np.array(y)

    allSSE = np.zeros(shape=(len(a),len(b)))
    for ai in range(0,len(a)):
        for bi in range(0,len(b)):
            a0 = a[ai]
            b0 = b[bi]
            SSE = calc_loss(a=a0,b=b0,x=x,y=y)
            allSSE[ai][bi] = SSE

    a,b = np.meshgrid(a, b)

    return [a,b,allSSE]
p6 adagrad.py 文件源码 项目:mlbasic 作者: tsycnh 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def draw_hill(x,y):
    a = np.linspace(-20,20,100)
    print(a)
    b = np.linspace(-20,20,100)
    x = np.array(x)
    y = np.array(y)

    allSSE = np.zeros(shape=(len(a),len(b)))
    for ai in range(0,len(a)):
        for bi in range(0,len(b)):
            a0 = a[ai]
            b0 = b[bi]
            SSE = calc_loss(a=a0,b=b0,x=x,y=y)
            allSSE[ai][bi] = SSE

    a,b = np.meshgrid(a, b)

    return [a,b,allSSE]
#  ????
p5 Nesterov momentum.py 文件源码 项目:mlbasic 作者: tsycnh 项目源码 文件源码 阅读 63 收藏 0 点赞 0 评论 0
def draw_hill(x,y):
    a = np.linspace(-20,20,100)
    print(a)
    b = np.linspace(-20,20,100)
    x = np.array(x)
    y = np.array(y)

    allSSE = np.zeros(shape=(len(a),len(b)))
    for ai in range(0,len(a)):
        for bi in range(0,len(b)):
            a0 = a[ai]
            b0 = b[bi]
            SSE = calc_loss(a=a0,b=b0,x=x,y=y)
            allSSE[ai][bi] = SSE

    a,b = np.meshgrid(a, b)

    return [a,b,allSSE]
#  ????
p8 adam.py 文件源码 项目:mlbasic 作者: tsycnh 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def draw_hill(x,y):
    a = np.linspace(-20,20,100)
    print(a)
    b = np.linspace(-20,20,100)
    x = np.array(x)
    y = np.array(y)

    allSSE = np.zeros(shape=(len(a),len(b)))
    for ai in range(0,len(a)):
        for bi in range(0,len(b)):
            a0 = a[ai]
            b0 = b[bi]
            SSE = calc_loss(a=a0,b=b0,x=x,y=y)
            allSSE[ai][bi] = SSE

    a,b = np.meshgrid(a, b)

    return [a,b,allSSE]
#  ????
p4 momentum.py 文件源码 项目:mlbasic 作者: tsycnh 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def draw_hill(x,y):
    a = np.linspace(-20,20,100)
    print(a)
    b = np.linspace(-20,20,100)
    x = np.array(x)
    y = np.array(y)

    allSSE = np.zeros(shape=(len(a),len(b)))
    for ai in range(0,len(a)):
        for bi in range(0,len(b)):
            a0 = a[ai]
            b0 = b[bi]
            SSE = calc_loss(a=a0,b=b0,x=x,y=y)
            allSSE[ai][bi] = SSE

    a,b = np.meshgrid(a, b)

    return [a,b,allSSE]
#  ????
p7 adadelta.py 文件源码 项目:mlbasic 作者: tsycnh 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def draw_hill(x,y):
    a = np.linspace(-20,20,100)
    print(a)
    b = np.linspace(-20,20,100)
    x = np.array(x)
    y = np.array(y)

    allSSE = np.zeros(shape=(len(a),len(b)))
    for ai in range(0,len(a)):
        for bi in range(0,len(b)):
            a0 = a[ai]
            b0 = b[bi]
            SSE = calc_loss(a=a0,b=b0,x=x,y=y)
            allSSE[ai][bi] = SSE

    a,b = np.meshgrid(a, b)

    return [a,b,allSSE]
#  ????
coordinates.py 文件源码 项目:pyrsss 作者: butala 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def mag_parallels(date, parallels=range(-75, 76, 15), height=350, N=1000):
    """
    Return a mapping between magnetic latitudes specified by
    *parallels* to the tuple of mapped geographic latitudes and
    longitudes. The mapping is made across *N* uniformly spaced
    geographic longitudes, on :class:`datetime` *date*, and at
    *height* (in [km]) in apex geomagnetic coordinates. If *date* is
    None, use the current date and time in the coordinate
    transformation.
    """
    apex = Apex(date=date)
    parallel_map = OrderedDict()
    lons = NP.linspace(-180, 180, N)
    for parallel in parallels:
        glat, glon = apex.convert(parallel,
                                  lons,
                                  source='apex',
                                  dest='geo')
        # sort by geographic longitude
        glat, glon = zip(*sorted(zip(glat, glon), key=lambda x: x[1]))
        parallel_map[parallel] = glat, glon
    return parallel_map
Sol_Analysis.py 文件源码 项目:BISIP 作者: clberube 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
def plot_mean_debye(sol, ax):
    x = np.log10(sol[0]["data"]["tau"])
    x = np.linspace(min(x), max(x),100)
    list_best_rtd = [100*np.sum([a*(x**i) for (i, a) in enumerate(s["params"]["a"])], axis=0) for s in sol]
#    list_best_rtd = [s["fit"]["best"] for s in sol]
    y = np.mean(list_best_rtd, axis=0)
    y_min = 100*np.sum([a*(x**i) for (i, a) in enumerate(sol[0]["params"]["a"] - sol[0]["params"]["a_std"])], axis=0)
    y_max = 100*np.sum([a*(x**i) for (i, a) in enumerate(sol[0]["params"]["a"] + sol[0]["params"]["a_std"])], axis=0)
    ax.errorbar(10**x[(x>-6)&(x<2)], y[(x>-6)&(x<2)], None, None, "-", color='blue',linewidth=2, label="Mean RTD", zorder=10)
    plt.plot(10**x[(x>-6)&(x<2)], y_min[(x>-6)&(x<2)], color='lightgray', alpha=1, zorder=-1, label="RTD range")
    plt.plot(10**x[(x>-6)&(x<2)], y_max[(x>-6)&(x<2)], color='lightgray', alpha=1, zorder=-1)
    plt.fill_between(sol[0]["data"]["tau"], 100*(sol[0]["params"]["m_"]-sol[0]["params"]["m__std"])  , 100*(sol[0]["params"]["m_"]+sol[0]["params"]["m__std"]), color='lightgray', alpha=1, zorder=-1, label="RTD SD")

    ax.set_xlabel("Relaxation time (s)", fontsize=14)
    ax.set_ylabel("Chargeability (%)", fontsize=14)
    plt.yticks(fontsize=14), plt.xticks(fontsize=14)
    plt.xscale("log")
    ax.set_xlim([1e-6, 1e1])
    ax.set_ylim([0, 5.0])
    ax.legend(loc=1, fontsize=12)
#    ax.set_title(title+" step method", fontsize=14)
Sol_Analysis.py 文件源码 项目:BISIP 作者: clberube 项目源码 文件源码 阅读 37 收藏 0 点赞 0 评论 0
def plot_mean_debye(sol, ax):
    x = np.log10(sol[0]["data"]["tau"])
    x = np.linspace(min(x), max(x),100)
    list_best_rtd = [100*np.sum([a*(x**i) for (i, a) in enumerate(s["params"]["a"])], axis=0) for s in sol]
#    list_best_rtd = [s["fit"]["best"] for s in sol]
    y = np.mean(list_best_rtd, axis=0)
    y_min = 100*np.sum([a*(x**i) for (i, a) in enumerate(sol[0]["params"]["a"] - sol[0]["params"]["a_std"])], axis=0)
    y_max = 100*np.sum([a*(x**i) for (i, a) in enumerate(sol[0]["params"]["a"] + sol[0]["params"]["a_std"])], axis=0)
    ax.errorbar(10**x[(x>-6)&(x<2)], y[(x>-6)&(x<2)], None, None, "-", color='blue',linewidth=2, label="Mean RTD", zorder=10)
    plt.plot(10**x[(x>-6)&(x<2)], y_min[(x>-6)&(x<2)], color='lightgray', alpha=1, zorder=-1, label="RTD range")
    plt.plot(10**x[(x>-6)&(x<2)], y_max[(x>-6)&(x<2)], color='lightgray', alpha=1, zorder=-1)
    plt.fill_between(sol[0]["data"]["tau"], 100*(sol[0]["params"]["m_"]-sol[0]["params"]["m__std"])  , 100*(sol[0]["params"]["m_"]+sol[0]["params"]["m__std"]), color='lightgray', alpha=1, zorder=-1, label="RTD SD")

    ax.set_xlabel("Relaxation time (s)", fontsize=14)
    ax.set_ylabel("Chargeability (%)", fontsize=14)
    plt.yticks(fontsize=14), plt.xticks(fontsize=14)
    plt.xscale("log")
    ax.set_xlim([1e-6, 1e1])
    ax.set_ylim([0, 5.0])
    ax.legend(loc=1, fontsize=12)
#    ax.set_title(title+" step method", fontsize=14)
mesh.py 文件源码 项目:Feon 作者: YaoyaoBae 项目源码 文件源码 阅读 45 收藏 0 点赞 0 评论 0
def create_cube(x_lim, y_lim,z_lim,size):
    nx = int(size[0])
    ny = int(size[1])
    nz = int(size[2])
    X = np.linspace(x_lim[0],x_lim[1],nx+1)
    Y = np.linspace(y_lim[0],y_lim[1],ny+1)
    Z = np.linspace(z_lim[0],z_lim[1],nz+1)
    p = np.array([(i,j,k) for i in X for j in Y for k in Z])
    e_cell = np.array([((nz+1)*(ny+1)*i[0]+(nz+1)*j[0]+k[0],
                        (nz+1)*(ny+1)*i[0]+(nz+1)*j[1]+k[0],
                        (nz+1)*(ny+1)*i[0]+(nz+1)*j[1]+k[1],
                        (nz+1)*(ny+1)*i[0]+(nz+1)*j[0]+k[1],
                        (nz+1)*(ny+1)*i[1]+(nz+1)*j[0]+k[0],
                        (nz+1)*(ny+1)*i[1]+(nz+1)*j[1]+k[0],
                        (nz+1)*(ny+1)*i[1]+(nz+1)*j[1]+k[1],
                        (nz+1)*(ny+1)*i[1]+(nz+1)*j[0]+k[1],)
                       for i in pair_wise(range(nx+1))
                       for j in pair_wise(range(ny+1))
                       for k in pair_wise(range(nz+1))],dtype = int)
    return p, e_cell
pose_model.py 文件源码 项目:Face-Pose-Net 作者: fengju514 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def _meshgrid(self, height, width):
    with tf.variable_scope('_meshgrid'):
      # This should be equivalent to:
      #  x_t, y_t = np.meshgrid(np.linspace(-1, 1, width),
      #                         np.linspace(-1, 1, height))
      #  ones = np.ones(np.prod(x_t.shape))
      #  grid = np.vstack([x_t.flatten(), y_t.flatten(), ones])
      x_t = tf.matmul(tf.ones(shape=tf.pack([height, 1])),
                        tf.transpose(tf.expand_dims(tf.linspace(-1.0, 1.0, width), 1), [1, 0]))
      y_t = tf.matmul(tf.expand_dims(tf.linspace(-1.0, 1.0, height), 1),
                        tf.ones(shape=tf.pack([1, width])))

      x_t_flat = tf.reshape(x_t, (1, -1))
      y_t_flat = tf.reshape(y_t, (1, -1))

      ones = tf.ones_like(x_t_flat)
      grid = tf.concat(0, [x_t_flat, y_t_flat, ones])
      return grid
plot.py 文件源码 项目:sound_field_analysis-py 作者: QULab 项目源码 文件源码 阅读 35 收藏 0 点赞 0 评论 0
def genSphCoords():
    """ Generates cartesian (x,y,z) and spherical (theta, phi) coordinates of a sphere
    Returns
    -------
    coords : named tuple
        holds cartesian (x,y,z) and spherical (theta, phi) coordinates
    """
    coords = namedtuple('coords', ['x', 'y', 'z', 'az', 'el'])
    az = _np.linspace(0, 2 * _np.pi, 360)
    el = _np.linspace(0, _np.pi, 181)
    coords.x = _np.outer(_np.cos(az), _np.sin(el))
    coords.y = _np.outer(_np.sin(az), _np.sin(el))
    coords.z = _np.outer(_np.ones(360), _np.cos(el))

    coords.el, coords.az = _np.meshgrid(_np.linspace(0, _np.pi, 181),
                                        _np.linspace(0, 2 * _np.pi, 360))
    return coords
sph.py 文件源码 项目:sound_field_analysis-py 作者: QULab 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def kr_full_spec(fs, radius, NFFT, temperature=20):
    """Returns full spectrum kr

    Parameters
    ----------
    fs : int
       Sampling rate in Hertz
    radius : float
       Radius
    NFFT : int
       Number of frequency bins
    temperature : float, optional
       Temperature in degree Celcius (Default: 20 C)

    Returns
    -------
    kr : array_like
       kr vector of length NFFT/2 + 1 spanning the frequencies of 0:fs/2
    """
    freqs = _np.linspace(0, fs / 2, NFFT / 2 + 1)
    return kr(freqs, radius, temperature)

# DEBUG
gen.py 文件源码 项目:sound_field_analysis-py 作者: QULab 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def radial_filter_fullspec(max_order, NFFT, fs, array_configuration, amp_maxdB=40):
    """Generate NFFT/2 + 1 modal radial filter of orders 0:max_order for frequencies 0:fs/2, wraps radial_filter()

    Parameters
    ----------
    max_order : int
       Maximum order
    NFFT : int
       Order of FFT (number of bins), should be a power of 2.
    fs : int
       Sampling frequency
    array_configuration : ArrayConfiguration
       List/Tuple/ArrayConfiguration, see io.ArrayConfiguration
    amp_maxdB : int, optional
       Maximum modal amplification limit in dB [Default: 40]

    Returns
    -------
    dn : array_like
       Vector of modal frequency domain filter of shape [max_order + 1 x NFFT / 2 + 1]
    """

    freqs = _np.linspace(0, fs / 2, NFFT / 2 + 1)
    orders = _np.r_[0:max_order + 1]
    return radial_filter(orders, freqs, array_configuration, amp_maxdB=amp_maxdB)
util.py 文件源码 项目:croissance 作者: biosustain 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def resample(series, *, factor=10, size=None):
    """
    Returns a new series re-sampled to a given number of points.

    :param series:
    :param factor: a number of points per unit time to scale the series to.
    :param size: a number of points to scale the series to.
    :return:
    """
    series = series.dropna()
    start, end = series.index[0], series.index[-1]

    if size is None:
        size = (end - start) * factor

    index = numpy.linspace(start, end, size)
    spline = InterpolatedUnivariateSpline(series.index, series.values)
    return pandas.Series(index=index, data=spline(index))
test_psi.py 文件源码 项目:Psi-staircase 作者: NNiehof 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def test_gamma_equal_lambda():
    mu = np.linspace(-100, 100, 2)
    sigma = np.linspace(2, 200, 2)
    x = np.linspace(-200, 200, 3)
    lapse = np.linspace(0, 0.1, 4)
    guess = lapse
    psi = PsiMarginal.Psi(x, Pfunction='cGauss', nTrials=50, threshold=mu, thresholdPrior=('uniform', None),
                          slope=sigma, slopePrior=('uniform', None),
                          guessRate=guess, guessPrior=('uniform', None), lapseRate=lapse, lapsePrior=('uniform', None),
                          marginalize=True)
    assert psi.gammaEQlambda == True
    guess = np.array([0.5], dtype='float')
    psi2 = PsiMarginal.Psi(x, Pfunction='cGauss', nTrials=50, threshold=mu, thresholdPrior=('uniform', None),
                           slope=sigma, slopePrior=('uniform', None),
                           guessRate=guess, guessPrior=('uniform', None), lapseRate=lapse, lapsePrior=('uniform', None),
                           marginalize=True)
    assert psi2.gammaEQlambda == False
graphics.py 文件源码 项目:activity-browser 作者: LCA-ActivityBrowser 项目源码 文件源码 阅读 34 收藏 0 点赞 0 评论 0
def __init__(self, parent):
        fig = Figure(figsize=(4, 4), dpi=100, tight_layout=True)
        super(DefaultGraph, self).__init__(fig)
        self.setParent(parent)
        sns.set(style="dark")

        for index, s in zip(range(9), np.linspace(0, 3, 10)):
            axes = fig.add_subplot(3, 3, index + 1)
            x, y = np.random.randn(2, 50)
            cmap = sns.cubehelix_palette(start=s, light=1, as_cmap=True)
            sns.kdeplot(x, y, cmap=cmap, shade=True, cut=5, ax=axes)
            axes.set_xlim(-3, 3)
            axes.set_ylim(-3, 3)
            axes.set_xticks([])
            axes.set_yticks([])

        fig.suptitle("Activity Browser", y=0.5, fontsize=30, backgroundcolor=(1, 1, 1, 0.5))

        self.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
        self.updateGeometry()
gridsearch_optimizer.py 文件源码 项目:OptML 作者: johannespetrat 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def build_grid(self, grid_sizes):
        grid_dict = {}
        for param_name, param in self.param_dict.items():
            if param.param_type == 'continuous':
                grid_dict[param_name] = np.linspace(param.lower, param.upper, grid_sizes[param_name])
            elif param.param_type == 'integer':
                step_size = int(round((param.upper - param.lower)/float(grid_sizes[param_name])))
                grid_dict[param_name] = np.concatenate([np.arange(param.lower, param.upper, step_size), [param.upper]])
            elif param.param_type == 'categorical':
                grid_dict[param_name] = param.possible_values
            elif param.param_type == 'boolean':
                grid_dict[param_name] = [True, False]
        # now build the grid as a list with all possible combinations i.e. the cartesian product
        grid = []
        for params in list(itertools.product(*[[(k,v) for v in vals] for k, vals in grid_dict.items()])):
            grid.append(dict(params))
        return grid
marginplot.py 文件源码 项目:pauvre 作者: conchoecia 项目源码 文件源码 阅读 35 收藏 0 点赞 0 评论 0
def generate_legend(panel, counts, color):

    # completely custom for more control
    panel.set_xlim([0, 1])
    panel.set_ylim([0, 1000])
    panel.set_yticks([int(x) for x in np.linspace(0, 1000, 6)])
    panel.set_yticklabels([int(x) for x in np.linspace(0, max(counts), 6)])
    for i in np.arange(0, 1001, 1):
        rgba = color(i / 1001)
        alpha = rgba[-1]
        facec = rgba[0:3]
        hist_rectangle = mplpatches.Rectangle((0, i), 1, 1,
                                              linewidth=0.0,
                                              facecolor=facec,
                                              edgecolor=(0, 0, 0),
                                              alpha=alpha)
        panel.add_patch(hist_rectangle)
    panel.spines['top'].set_visible(False)
    panel.spines['left'].set_visible(False)
    panel.spines['bottom'].set_visible(False)
    panel.yaxis.set_label_position("right")
    panel.set_ylabel('Number of Reads')
redwood.py 文件源码 项目:pauvre 作者: conchoecia 项目源码 文件源码 阅读 33 收藏 0 点赞 0 评论 0
def plotArc(start_angle, stop_angle, radius, width, **kwargs):
    """ write a docstring for this function"""
    numsegments = 100
    theta = np.radians(np.linspace(start_angle+90, stop_angle+90, numsegments))
    centerx = 0
    centery = 0
    x1 = -np.cos(theta) * (radius)
    y1 = np.sin(theta) * (radius)
    stack1 = np.column_stack([x1, y1])
    x2 = -np.cos(theta) * (radius + width)
    y2 = np.sin(theta) *  (radius + width)
    stack2 = np.column_stack([np.flip(x2, axis=0), np.flip(y2,axis=0)])
    #add the first values from the first set to close the polygon
    np.append(stack2, [[x1[0],y1[0]]], axis=0)
    arcArray = np.concatenate((stack1,stack2), axis=0)
    return patches.Polygon(arcArray, True, **kwargs), ((x1, y1), (x2, y2))


问题


面经


文章

微信
公众号

扫码关注公众号