我们从Python开源项目中,提取了以下12个代码示例,用于说明如何使用scipy.interpolate.spline()。
def smoothCurve(X, Fac): NPoints = X.shape[0] dim = X.shape[1] idx = range(NPoints) idxx = np.linspace(0, NPoints, NPoints*Fac) Y = np.zeros((NPoints*Fac, dim)) NPointsOut = 0 for ii in range(dim): Y[:, ii] = interp.spline(idx, X[:, ii], idxx) #Smooth with box filter y = (0.5/Fac)*np.convolve(Y[:, ii], np.ones(Fac*2), mode='same') Y[0:len(y), ii] = y NPointsOut = len(y) Y = Y[0:NPointsOut-1, :] Y = Y[2*Fac:-2*Fac, :] return Y
def smooth_log(self): """ This function ... :return: """ centers = np.array(self.centers) counts = np.array(self.counts) not_zero = counts != 0 centers = centers[not_zero] counts = counts[not_zero] order = 2 s = InterpolatedUnivariateSpline(centers, np.log10(counts), k=order) # Return the spline curve return s # -----------------------------------------------------------------
def getSlidingWindow(x, dim, Tau, dT): """ A function that computes the sliding window embedding of a discrete signal. If the requested windows and samples do not coincide with sampels in the original signal, spline interpolation is used to fill in intermediate values :param x: The discrete signal :param dim: The dimension of the sliding window embedding :param Tau: The increment between samples in the sliding window :param dT: The hop size between windows :returns: An Nxdim Euclidean vector of sliding windows """ N = len(x) NWindows = int(np.floor((N-dim*Tau)/dT)) X = np.zeros((NWindows, dim)) idx = np.arange(N) for i in range(NWindows): idxx = dT*i + Tau*np.arange(dim) start = int(np.floor(idxx[0])) end = int(np.ceil(idxx[-1]))+2 if end >= len(x): X = X[0:i, :] break X[i, :] = interp.spline(idx[start:end+1], x[start:end+1], idxx) return X
def random_investing(): profit = 0 stocks_invested = 0 stocks_iterated = 0 y = [] state = env.reset() while stocks_iterated < stocks_to_iterate: action = np.random.choice(np.array(VALID_ACTIONS)) next_state, reward, done, _ = env.step(action) if done: profit += reward stocks_invested += reward != 0 y.append(profit / (stocks_invested or 1)) state = env.reset() stocks_iterated += 1 print( "Stock {}/{} , Profit: {}".format(stocks_iterated, stocks_to_iterate, profit / (stocks_invested or 1))) else: state = next_state x_new = np.linspace(x.min(),x.max(),smoothing) y = np.array(y) y_smooth = spline(x, y, x_new) return [plt.plot(x_new, y_smooth, linewidth=2, label='Random'),profit / (stocks_invested or 1)]
def plot_density(self, ax, num=300, **kwargs): """Returns a density plot on an Pyplot Axes object. Args: ax (:obj:`Axes`): An matplotlib Axes object on which the histogram will be plot num (:obj:`int`): The number of x values the line is plotted on. Default: 300 **kwargs: Keyword arguments that are passed on to the pyplot.plot function. """ colors = [] self.build() bin_centers = np.asarray(self._get_bin_centers()) x_new = np.linspace(bin_centers.min(), bin_centers.max(), num) if 'color' in kwargs: colors = kwargs['color'] del kwargs['color'] power_smooth = [] for (colname, bin_values) in self.hist_dict.items(): normed_values, ble = np.histogram(self._get_bin_centers(), bins=self.bin_list, weights=bin_values, normed=True ) power_smooth.append(x_new) power_smooth.append(spline(bin_centers, normed_values, x_new)) lines = ax.plot(*power_smooth, **kwargs) for i, line in enumerate(lines): if len(colors) > 0: plt.setp(line, color=colors[i], label=list(self.hist_dict.keys())[i]) else: plt.setp(line, label=list(self.hist_dict.keys())[i]) return lines
def smooth(self): """ This function ... :return: """ order = 2 s = InterpolatedUnivariateSpline(self.centers, self.counts, k=order) # Return the spline curve return s # -----------------------------------------------------------------
def plot_accuracy_curve(title, style, y, vp_size, smooth, interval, maxlen, **kwargs): mv_avg = kwargs.pop('mv_avg', False) x = range(vp_size, 1 + len(y) * vp_size, vp_size) min_len = min(len(x), len(y), maxlen) x, y = x[:min_len], y[:min_len] if mv_avg is not False: y = move_avg(y, mv_avg) if smooth > 0: try: x_new = np.linspace(min(x), max(x), smooth) except ValueError as e: print('Plot error:', title, e) return power_smooth = spline(x, y, x_new) else: x_new = x power_smooth = y x_new = pick_interval(x_new, interval) power_smooth = pick_interval(power_smooth, interval) plt.plot(x_new, power_smooth, style, label=title, **kwargs)
def plot_acc_line(k, style, xs, ys, interval=1, smooth=300): dx, dy = xs[k], ys[k] if interval > 1: dx = [e for i, e in enumerate(dx) if (i + 1) % interval == 0] dy = [e for i, e in enumerate(dy) if (i + 1) % interval == 0] min_len = min(len(dx), len(dy)) dx, dy = dx[:min_len], dy[:min_len] x_new = np.linspace(min(dx), max(dx), smooth) power_smooth = spline(dx, dy, x_new) plt.plot(x_new, power_smooth, linewidth=2.0, label=k, linestyle=style)
def deep_q_investing(): profit = 0 stocks_invested = 0 stocks_iterated = 0 y = [] with tf.Session() as sess: sess.run(tf.initialize_all_variables()) state = env.reset() while stocks_iterated < stocks_to_iterate: state = np.squeeze(np.reshape(state, [80, 80])) state = np.stack([state] * 4, axis=2) state = np.array([state]) q_values = estimator.predict(sess, state)[0] best_action = np.argmax(q_values) action = VALID_ACTIONS[best_action] next_state, reward, done, _ = env.step(action) if done: profit += reward stocks_invested += reward != 0 y.append(profit/(stocks_invested or 1)) state = env.reset() stocks_iterated += 1 print ("Stock {}/{} , Profit: {}".format(stocks_iterated, stocks_to_iterate, profit/(stocks_invested or 1))) else: state = next_state x_new = np.linspace(x.min(),x.max(),smoothing) y = np.array(y) y_smooth = spline(x, y, x_new) return [plt.plot(x_new, y_smooth, linewidth=2, label='Deep Q'),profit / (stocks_invested or 1)]
def plot_density(self, ax, num=300, **kwargs): """Returns a density plot on an Pyplot Axes object. Args: :ax: (`Axes`) An matplotlib Axes object on which the histogram will be plot :num: (`int`) The number of x values the line is plotted on. Default: 300 :**kwargs: Keyword arguments that are passed on to the pyplot.plot function. """ colors = [] self.build() bin_centers = np.asarray(self._get_bin_centers()) x_new = np.linspace(bin_centers.min(), bin_centers.max(), num) if 'color' in kwargs: colors = kwargs['color'] del kwargs['color'] power_smooth = [] for (colname, bin_values) in self.hist_dict.items(): normed_values, ble = np.histogram(self._get_bin_centers(), bins=self.bin_list, weights=bin_values, normed=True ) power_smooth.append(x_new) power_smooth.append(spline(bin_centers, normed_values, x_new)) lines = ax.plot(*power_smooth, **kwargs) for i, line in enumerate(lines): if len(colors) > 0: plt.setp(line, color=colors[i], label=list(self.hist_dict.keys())[i]) else: plt.setp(line, label=list(self.hist_dict.keys())[i]) return lines