Esempio n. 1
0
 def sml(self, show=True):
     '''
     估计收益率在证券市场线上的分布
     '''
     plt.style.use('seaborn-paper')
     Rm_mean = self.Rm_data['pctChg'].mean()
     k = Rm_mean - self.rfr
     all_beta = self.all_beta()
     plt.cla()
     plt.axline(xy1=(0, self.rfr), slope=k, c='m')
     plt.scatter(all_beta.beta,
                 all_beta.beta * k + self.rfr,
                 s=100,
                 marker=".",
                 c='b')
     plt.scatter(all_beta.beta, all_beta.Ri, s=100, marker=".", c='r')
     for i in all_beta.itertuples():
         plt.annotate(text=i.Index,
                      xy=(i.beta, i.Ri),
                      xytext=(i.beta, i.Ri))
         plt.annotate(text=i.Index,
                      xy=(i.beta, i.beta * k + self.rfr),
                      xytext=(i.beta, i.beta * k + self.rfr))
     if all_beta.beta.min() < 0:
         plt.axvline(0, linestyle='--')
     else:
         plt.xlim(0, all_beta.beta.max() * 1.2)
     plt.xlabel('Beta')
     plt.ylabel('E(Ri)')
     if show:
         plt.show()
     else:
         plt.savefig(f'{self.path}\\sml.svg', format='svg')
Esempio n. 2
0
def main(lr, train_path, eval_path, save_path):
    """Problem: Poisson regression with gradient ascent.

    Args:
        lr: Learning rate for gradient ascent.
        train_path: Path to CSV file containing dataset for training.
        eval_path: Path to CSV file containing dataset for evaluation.
        save_path: Path to save predictions.
    """
    # Load training set
    x_train, y_train = util.load_dataset(train_path, add_intercept=True)

    # *** START CODE HERE ***
    # Fit a Poisson Regression model
    clf = PoissonRegression()
    clf.fit(x_train, y_train)

    # Run on the validation set, and use np.savetxt to save outputs to save_path
    x_test, y_test = util.load_dataset(eval_path, add_intercept=True)
    y_test_pred = clf.predict(x_test)

    save_path_root = os.path.splitext(save_path)[0]
    # util.plot(x_test, y_test, clf.theta, save_path_root + '_fig.png')
    fig_name = save_path_root + '_fig.png'
    plt.figure()
    plt.scatter(y_test, y_test_pred, marker='x')
    plt.axline((0, 0), slope=1)
    plt.xlabel('Observed counts')
    plt.ylabel('Predicted mean counts')
    plt.title('poisson glm fit predicted mean counts')
    plt.savefig(fig_name)

    np.savetxt(save_path, y_test_pred)
    np.savetxt(save_path_root + '_theta.txt', clf.theta)
Esempio n. 3
0
def plot():
    ts, eigs_x, eigs_y, eigs_z, eigs_roll, eigs_pitch, eigs_yaw = get_data()
    f = plt.figure(figsize=(7.2, 2.8))
    plt.xlabel("t [s]")
    plt.ylabel("eigenvalues of LOAM AtA matrix")
    for eigs, label in zip((eigs_x, eigs_y, eigs_z), (f"λ₁", "λ₂", "λ₃")):
        plt.plot(ts, eigs, label=label)
    plt.axline((ts[0], degenerate_thresh), (ts[-1], degenerate_thresh),
               label="degenerate thresh",
               color="m")
    plt.xlim(0, ts[-1])
    plt.legend()
    plt.savefig("loam_eigs.pdf", bbox_inches="tight")

    plt.figure()
    plt.xlabel("t [s]")
    plt.ylabel("eigenvalues of LOAM AtA matrix")
    for eigs, label in zip((eigs_roll, eigs_pitch, eigs_yaw),
                           ("roll", "pitch", "yaw")):
        plt.plot(ts, eigs, label=label)
    plt.axline((ts[0], degenerate_thresh), (ts[-1], degenerate_thresh),
               label="degenerate thresh",
               color="m")
    plt.xlim(0, ts[-1])
    plt.legend()
    plt.savefig("loam_eigs_euler.pdf")
Esempio n. 4
0
def makeGraphs(logs):
    logs = pickle.load(open(logs, 'rb'))
    x = [x[0] for x in logs['x_y_logs']]
    y = [x[1] for x in logs['x_y_logs']]

    plt.figure(1)
    plt.xlim([-100, 100])
    plt.ylim([-100, 100])
    plt.axline((-100, 0), (100, 0), color='k', ls='--', alpha=0.5)
    plt.axline((0, -10), (0, 10), color='k', ls='--', alpha=0.5)
    plt.plot(x, y, c='r')
    plt.xlabel('X-Axis [m]')
    plt.ylabel('Y-axis [m]')
    plt.show()

    for joint_t in range(0, 3):
        for idx in range(joint_t, 18, 3):
            j = [item[idx] for item in logs['leg_logs']]
            j = np.rad2deg(j)
            plt.figure(joint_t + 2)
            plt.subplot(2, 3, idx // 3 + 1)
            length = len(j)
            if idx < 9:
                j *= -1
            plt.plot(np.linspace(0, length / 30, length),
                     j,
                     c=colors[joint_t],
                     label=f"{labels[joint_t]}{idx//3}")
            plt.legend(loc='lower left')
            plt.xlabel("Time [s]")
            plt.ylabel("Angle [deg]")

    plt.grid(ls='--', c='k', alpha=0.5)
    plt.show()
Esempio n. 5
0
def write_evaluation(model_path, y_true, y_predict, write: bool = False):
    plt.plot(y_true, y_predict, "ro", label="Prediction values", alpha=0.3)
    plt.axline([0, 0], [1, 1])
    uni_y_true = np.unique(y_true)
    plt.plot(
        uni_y_true,
        np.poly1d(np.polyfit(y_true, y_predict, 1))(uni_y_true),
        color="black",
        label="Poly1D fit",
    )
    plt.annotate(
        "r^2 = {:.2f}".format(r2_score(y_true, y_predict)),
        (0.7, 0.04),
        xycoords="axes fraction",
    )
    plt.annotate(
        "mse = {:.2f}".format(mean_squared_error(y_true, y_predict)),
        (0.7, 0.01),
        xycoords="axes fraction",
    )
    plt.annotate(
        "mae = {:.2f}".format(mean_absolute_error(y_true, y_predict)),
        (0.7, 0.07),
        xycoords="axes fraction",
    )
    plt.ylabel("Predicted Pull time (s)")
    plt.xlabel("Actual Pull time (s)")
    plt.legend(loc="upper left")
    model_name = os.path.basename(model_path).split(".")[0]
    plt.suptitle(f"Model: {model_name}")
    if not write:
        plt.show()
    else:
        plt.savefig(f"eval-{model_name}.png")
    plt.close()
    def show_plot(self, title=''):

        # styles
        plt.figure(figsize=(8, 8))
        plt.figtext(0.5, 0.9, title, ha="center", fontsize=20)
        plt.axvline(0, color='black', linewidth=.8)
        plt.axhline(0, color='black', linewidth=.8)
        plt.grid(color='grey', linestyle=':', linewidth=.5)

        # plotting data
        plt.scatter(self.x1, self.y1)
        plt.scatter(self.x2, self.y2)

        # plotting decision boundary
        if np.any(self.__weight[:-1]):
            a, b, c = self.__weight
            if b == 0:
                plt.axvline(-c / a, c='black', label='decision boundary')
            else:
                y_intercept = -c / b
                slope = -a / b
                plt.axline((0, y_intercept),
                           slope=slope,
                           c='black',
                           label='decision boundary')
            plt.legend(loc='best', fontsize=16)

        plt.figtext(0.5,
                    0.04,
                    "weight vector : " + str(self.__weight),
                    ha="center",
                    fontsize=20)
        title = title.replace(' ', '_')
        plt.savefig(f'output_images/{title}.png')
        plt.show()
Esempio n. 7
0
def plot_data(df):
    global filename
    global tmp
    global tmp_min_idx
    global tmp_max_idx
    x = np.linspace(0, df['time'].shape[0], df['time'].shape[0])
    plt.subplot(2, 1, 1)
    # peaks, _ = find_peaks(df['time'], distance=500)
    plt.plot(x, df['time'])
    # plt.scatter(tmp, df['time'][tmp_min_idx], s= 100, c='green')
    # plt.scatter(tmp, df['time'][tmp_max_idx], s= 50, c='yellow')
    plt.axline((0, 0), (0, df['time'][tmp_min_idx]), color='g', linestyle='--')
    # plt.axvline(x= tmp_min_idx, color= 'r', linestyle= '--')
    plt.scatter(tmp, df['time'][tmp], s=100, c='blue')
    # plt.scatter(int(df['time'].idxmax()*0.8), df['time'][int(df['time'].idxmax()*0.8)], s= 50, c='blue')
    plt.scatter(df['time'].idxmax(),
                df['time'][df['time'].idxmax()],
                s=50,
                c='red')

    plt.subplot(2, 1, 2)
    x = np.linspace(0, df['size'].shape[0], df['size'].shape[0])
    plt.xlabel(filename)
    plt.plot(x, df['size'])
    plt.show()
Esempio n. 8
0
def residual_vs_actual(y_true: NumArray, y_pred: NumArray, ax: Axes = None) -> Axes:
    """Plot ground truth targets on the x-axis against residuals
    (y_err = y_true - y_pred) on the y-axis.

    Args:
        y_true (array): Ground truth values
        y_pred (array): Model predictions
        ax (Axes, optional): matplotlib Axes on which to plot. Defaults to None.

    Returns:
        ax: The plot's matplotlib Axes.
    """
    if ax is None:
        ax = plt.gca()

    y_err = y_true - y_pred

    plt.plot(y_true, y_err, "o", alpha=0.5, label=None, mew=1.2, ms=5.2)
    plt.axline(
        [1, 0], [2, 0], linestyle="dashed", color="black", alpha=0.5, label="ideal"
    )

    plt.ylabel(r"Residual ($y_\mathrm{test} - y_\mathrm{pred}$)")
    plt.xlabel("Actual value")
    plt.legend(loc="lower right")

    return ax
Esempio n. 9
0
 def plot(self):
     plt.plot(self.pts[0], self.pts[1], 'ro', ms=1)
     uv = self._unit_vector[self.dim]
     for i in range(len(self._unit_vector[self.dim])):
         slope = -uv[i][0] / (uv[i][1] + 1e-9)
         plt.axline(self.range[0][i] * uv[i], slope=slope, color='black')
         plt.axline(self.range[1][i] * uv[i], slope=slope, color='black')
     plt.show()
Esempio n. 10
0
def plot_omega(data, color=None):
    #omega, mu1, eta1, k_cell, alpha_cell, epsilon = get_cell_properties(data)

    for pressure in sorted(data.pressure.unique(), reverse=True):
        d = data[data.pressure == pressure]
        w = d.omega  #omega[data.pressure == pressure]
        plt.plot(-d.vel_grad, w, "o", label=f"{pressure:.1f}", ms=1)
    plt.axline((0, 0), slope=0.5, linestyle="dashed", color="k", lw=0.8)
    plt.xlabel("shear rate (1/s)")
    plt.ylabel("tank treading\nangular frequency (rad/s)")
Esempio n. 11
0
def init():
    global max_frame
    ax.set_xlim(-2, roadWidth)
    ax.set_ylim(-10, 20)
    plt.axline((0, -2), (roadWidth, -2))
    plt.axline((0, 2), (roadWidth, 2))
    plt.axline((0, 6), (roadWidth, 6))
    plt.axline((0, 10), (roadWidth, 10))
    plt.axline((0, 14), (roadWidth, 14))
    return ln1,
		def plot_decision_boundary(weight,bias,label,color):
			if np.any(weight[:-1]):
				a,b=weight
				c=bias
				if b==0:
					plt.axvline(-c/a, c=color, label=label)
				else:
					y_intercept=-c/b
					slope=-a/b
					plt.axline((0,y_intercept), slope=slope, c=color, label=label)
Esempio n. 13
0
def plot_decision_boundary(x, y, theta=None, save_path='', intercept=True):
    plt.figure()
    start_i = 1 if intercept else 0
    plt.scatter(x[y == 0, start_i], x[y == 0, start_i + 1], color='r')
    plt.scatter(x[y == 1, start_i], x[y == 1, start_i + 1], color='b')

    if not theta is None:
        slope = -1 / (theta[2] / theta[1])
        point = quick_solve(theta)
        plt.axline(point, slope=slope)

    if save_path:
        plt.savefig(os.path.splitext(save_path)[0] + '_fig.png')

    plt.show()
Esempio n. 14
0
def _plot_scatter(inhouse, sklearn, yreal, information=""):
    #plot predicted to real values
    df = pd.DataFrame({"inhouse": inhouse, "sklearn": sklearn, "real": yreal})

    plt.scatter('real', 'inhouse', data=df, color="red", alpha=0.4)
    plt.scatter('real', 'sklearn', data=df, color="olive", alpha=0.4)

    #titles and descriptions
    plt.suptitle(f'[Fish] Visualization of inhouse vs sklearn', fontsize=16)
    plt.title(information, fontsize=12)
    plt.ylabel("Predicted Weight")
    plt.xlabel("Annual Weight")
    plt.xticks(rotation=90)
    plt.legend(["Inhouse", "Sklearn"])
    plt.axline([0, 0], [1, 1])
    return plt
Esempio n. 15
0
 def plot(self):
     for line in self.lines:
         plt.axline(line[0], line[1], color='yellow')
     handles = []
     for i, proj in enumerate(self.projs):
         for p in proj:
             plt.scatter(p[:, 0],
                         p[:, 1],
                         marker='.',
                         color=self.types[i].color)
         label = plt.scatter([], [],
                             color=self.types[i].color,
                             marker='.',
                             label=f'Type {self.types[i].type} projection')
         handles.append(label)
     plt.gca().add_artist(plt.legend(handles=handles, loc='upper left'))
Esempio n. 16
0
    def get_charts(self, figsize=(22, 6), bins=50):
        thresh = 0
        diff = self.uplift(self.beta_c, self.beta_t)
        #diff = self.beta_t / self.beta_c
        min_xy, max_xy = np.min([self.beta_c, self.beta_t
                                 ]), np.max([self.beta_c, self.beta_t])
        #ratio = (diff <= thresh).sum() / self.size

        plt.figure(figsize=figsize)
        plt.subplot(1, 3, 1)
        sns.histplot(self.beta_c,
                     label='control',
                     bins=bins,
                     stat='probability',
                     color='#19D3F3')
        sns.histplot(self.beta_t,
                     label='test',
                     bins=bins,
                     stat='probability',
                     color='C1')
        plt.title('Beta Distributions for CR')
        plt.legend()

        plt.subplot(1, 3, 2)
        sns.histplot(x=self.beta_c, y=self.beta_t, bins=bins, color='#3366CC')
        plt.xlabel('control')
        plt.ylabel('test')
        plt.axline(xy1=[min_xy, min_xy],
                   xy2=[max_xy, max_xy],
                   color='black',
                   linestyle='--')
        plt.title('Joint Distribution')

        plt.subplot(1, 3, 3)
        h = sns.histplot(x=diff,
                         bins=bins,
                         stat='probability',
                         cumulative=True,
                         color='#636EFA')
        for i in h.patches:
            if i.get_x() <= thresh:
                i.set_facecolor('#EF553B')
        plt.axvline(x=self.lift, color='black', linestyle='--')
        #plt.axhline(ratio, color='black',linestyle='--')
        plt.yticks(np.arange(0, 1.1, 0.1))
        plt.title('Uplift')
        plt.show()
Esempio n. 17
0
def plot(weights, datapoints, labels):
    """
  Plots weights/bias in a 2-D grid. The specifics of this are something y'all can kind of ignore
  """
    plt.figure(figsize=(10, 10))
    plt.grid(True)

    for input, target in zip(datapoints, labels):
        plt.plot(input[1], input[2], 'ro' if (target == 1.0) else 'go')

    #ax = plt.axes()
    #ax.arrow(0, 0, weights[1], weights[2], head_width=0.5, head_length=0.7, fc='lightblue', ec='black')
    x_min = np.amin(datapoints[:, 1])
    x_max = np.amax(datapoints[:, 1])
    get_y = lambda x: (-weights[0] - weights[1] * x) / weights[2]

    plt.axline([0, get_y(0)], [1, get_y(1)], color="black")
Esempio n. 18
0
def plot_demand_scatter(
    a: pd.DataFrame,
    b: pd.DataFrame,
    title: str = None,
    path: str = None,
) -> None:
    """
    Make a scatter plot comparing predicted and reference demand.

    Args:
        a: Predicted demand with columns `utc_datetime` and any of
          `demand_mwh` (in grey) and `scaled_demand_mwh` (in orange).
        b: Reference demand with columns `utc_datetime` and `demand_mwh`.
          Every element in `utc_datetime` must match the one in `a`.
        title: Plot title.
        path: Plot path. If provided, the figure is saved to file and closed.

    Raises:
        ValueError: Datetime columns do not match.
    """
    if not a['utc_datetime'].equals(b['utc_datetime']):
        raise ValueError('Datetime columns do not match')
    plt.figure(figsize=(8, 8))
    plt.gca().set_aspect('equal')
    plt.axline((0, 0), (1, 1), linestyle=':', color='grey')
    for field, color in [('demand_mwh', 'grey'),
                         ('scaled_demand_mwh', 'orange')]:
        if field not in a:
            continue
        plt.scatter(
            b['demand_mwh'],
            a[field],
            c=color,
            s=0.1,
            alpha=0.5,
            label=f'Prediction ({field})',
        )
    if title:
        plt.title(title)
    plt.xlabel('Reference (MWh)')
    plt.ylabel('Predicted (MWh)')
    plt.legend()
    if path:
        plt.savefig(path, bbox_inches='tight')
        plt.close()
Esempio n. 19
0
def plot_dataset(X, y, w=None, b=None):
    """
    Plot X, y data

    :param X: 2-D array of features (with 1, 2, or 3 columns)
    :param y: 1-D array of lables
    :return: Axes object
    """

    colors = ListedColormap(['r', 'b', 'g'])

    if X.shape[1] == 1:
        scatter = plt.scatter(X[:, 0], np.repeat(0, X.size), c=y, cmap=colors)

        if w is not None and b is not None:
            x1 = -b / w[-1]
            plt.scatter(x1, 0, marker='x')

    elif X.shape[1] == 2:
        scatter = plt.scatter(X[:, 0], X[:, 1], c=y, cmap=colors)

        if w is not None and b is not None:
            x1 = np.array([0, 1])
            x2 = -(w[0] * x1 + b) / w[-1]
            plt.axline(xy1=(x1[0], x2[0]), xy2=(x1[1], x2[1]))

    elif X.shape[1] == 3:
        fig = plt.figure()
        ax = fig.add_subplot(1, 1, 1, projection='3d')
        scatter = ax.scatter(X[:, 0], X[:, 1], X[:, 2], c=y, cmap=colors)

        if w is not None and b is not None:
            x1 = X[:, 0]
            x2 = X[:, 1]
            x3 = -(X[:, [0, 1]].dot(w[[0, 1]]) + b) / w[-1]
            ax.plot_trisurf(x1, x2, x3)

    else:
        raise AssertionError("Can't plot data with >3 dimensions")

    # insert legend
    plt.legend(*scatter.legend_elements())

    return plt.gca()
Esempio n. 20
0
def scatter_dataset(X, Y, title, theta=None):
    os.makedirs('outputs', exist_ok=True)
    plt.figure()
    plt.scatter(X[Y == 1, 1], X[Y == 1, 2], c='r', label='Y==1')
    plt.scatter(X[Y == 0, 1], X[Y == 0, 2], c='g', label='Y==0')
    plt.xlabel('x0')
    plt.ylabel('x1')
    plt.title(title)
    plt.legend()

    if not theta is None:
        slope = -1 / (theta[2] / theta[1])
        point = quick_solve(theta)
        plt.axline(point, slope=slope)
        theta_norm = 0.3 * theta[1:] / np.linalg.norm(theta[1:])
        plt.arrow(0.5, 0.5, theta_norm[0], theta_norm[1])

    plt.savefig(f'outputs/{title}.png')
    plt.show()
Esempio n. 21
0
 def add_modification(self):
     x_sdev = stdev(self.x)
     y_sdev = stdev(self.y)
     y_list, x_list = [], []
     ymid = (self.ax.get_ylim()[0] + self.ax.get_ylim()[1]) / 2
     xmid = (self.ax.get_xlim()[0] + self.ax.get_xlim()[1]) / 2
     ysteps = abs((self.ax.get_ylim()[1] - self.ax.get_ylim()[0]) // (y_sdev / 2))
     xsteps = abs((self.ax.get_xlim()[1] - self.ax.get_xlim()[0]) // (x_sdev))
     print(int(0 - (ysteps / 2)), int(0 + (ysteps / 2)))
     for i in range(int(0 - (ysteps / 2)), int(0 + (ysteps / 2))):
         y_list.append(ymid + (i * y_sdev))
     for i in range(int(0 - (xsteps / 2)), int(0 + (xsteps / 2))):
         x_list.append(xmid + (i * x_sdev))
     x_list.append(x_list[-1] + x_sdev)
     print(y_list)
     slope = (y_list[0] - y_list[-1]) / (min(x_list) - max(x_list))
     for pointx in x_list:
         # plt.scatter(x=pointx, y=ymid, color='blue')
         plt.axline((pointx, ymid), slope=slope, color='gray')
Esempio n. 22
0
def generate_plot(nnet: nn.Module(), device, env: Environment, states: List[State], outputs: np.array):
    nnet.eval()

    states_targ_nnet: np.ndarray = env.state_to_nnet_input(states)
    out_nnet = nnet(states_nnet_to_pytorch_input(states_targ_nnet, device).float()).cpu().data.numpy()
    out_nnet, _ = flatten(out_nnet)
    outputs, _ = flatten(outputs)

    out_nnet_array = np.array(out_nnet)
    outputs_array = np.array(outputs)

    random_indexs = list(range(len(out_nnet_array)))
    random.shuffle(random_indexs)

    random_states: np.ndarray = []
    sample_expected: np.ndarray = []
    sample_outputs: np.ndarray = []

    for i in range(100):
        random_states.append(states[random_indexs[i]])
        sample_expected.append(outputs_array[random_indexs[i]])
        sample_outputs.append(out_nnet_array[random_indexs[i]])

    h_new: np.ndarray = approx_admissible_conv(env, nnet, out_nnet_array, outputs_array, states, random_states, sample_outputs, sample_expected)

    #before, after = plt.subplots()
    plt.scatter(sample_expected, sample_outputs, c = '000000', linewidths = 0.1)
    #plt.plot([0,0],[30,30], c = 'g')
    plt.axline([0,0],[30,30], linewidth =3, c = 'g')
    plt.ylabel('NNet output')
    plt.xlabel('Expected value')
    plt.title("Output vs Expected")
    plt.show()
    #before.savefig("preconversion.pdf")

    
    plt.scatter(sample_expected, h_new, c = '000000', linewidths = 0.1)
    plt.axline([0,0],[30,30], linewidth =3, c = 'g')
    plt.ylabel('Converted output')
    plt.xlabel('Expected value')
    plt.title("Converted Output vs Expected")
    plt.show() 
Esempio n. 23
0
    def cml(self, show=True):
        '''
        资本市场线 & 有效边界
        '''
        if self.path:
            try:
                df_scatter = pd.read_csv(
                    f'{self.path}\\scatter data\\scatter_data.csv')
                df_boundary_scatter = pd.read_csv(
                    f'{self.path}\\scatter data\\boundary_scatter_data.csv')
            except:
                df_scatter = self.scatter_data()
                df_boundary_scatter = self.boundary_scatter_data()
            df_scatter['boundary'] = False
            df_boundary_scatter['boundary'] = True
            pd.concat([
                df_scatter, df_boundary_scatter
            ]).to_csv(f'{self.path}\\scatter data\\all_scatter_data.csv')
        else:
            df_scatter = self.scatter_data()
            df_boundary_scatter = self.boundary_scatter_data()

        max_sharpe = self.optimization()['sharpe']
        sprint(f'max sharpe: {max_sharpe}')
        plt.cla()
        plt.style.use('seaborn-paper')
        plt.scatter(df_scatter.risk, df_scatter.rate, s=10, marker=".", c='b')
        plt.scatter(df_boundary_scatter.risk,
                    df_boundary_scatter.rate,
                    s=10,
                    marker=".",
                    c='r')
        plt.axline(xy1=(0, self.rfr), slope=max_sharpe, c='m')
        plt.xlim(df_scatter.risk.min() * 0.8, df_scatter.risk.max() * 1.2)
        plt.ylim(df_scatter.rate.min() * 0.8, df_scatter.rate.max() * 1.2)
        plt.xlabel('Risk')
        plt.ylabel('Yield')
        if show:
            plt.show()
        else:
            plt.savefig(f'{self.path}\\cml.svg', format='svg')
        return pd.concat([df_scatter, df_boundary_scatter])
Esempio n. 24
0
    def init_cml(self, show=True):
        '''
        初始临近组合散点图
        '''
        if self.path:
            try:
                df_init_scatter = pd.read_csv(
                    f'{self.path}\\scatter data\\df_init_scatter.csv')
                df_boundary_scatter = pd.read_csv(
                    f'{self.path}\\scatter data\\boundary_scatter_data.csv')
            except:
                df_init_scatter = self.init_scatter_data()
                df_boundary_scatter = self.boundary_scatter_data()
        else:
            df_init_scatter = self.init_scatter_data()
            df_boundary_scatter = self.boundary_scatter_data()

        max_sharpe = self.optimization()['sharpe']
        plt.style.use('seaborn-paper')
        plt.cla()
        plt.scatter(df_init_scatter.risk,
                    df_init_scatter.rate,
                    s=100,
                    marker=".",
                    c='r')
        plt.scatter(df_boundary_scatter.risk,
                    df_boundary_scatter.rate,
                    s=10,
                    marker=".",
                    c='b')
        plt.axline(xy1=(0, self.rfr), slope=max_sharpe, c='m')
        plt.xlim(df_init_scatter.risk.min() * 0.8,
                 df_init_scatter.risk.max() * 1.2)
        plt.ylim(df_init_scatter.rate.min() * 0.8,
                 df_init_scatter.rate.max() * 1.2)
        plt.xlabel('Risk')
        plt.ylabel('Yield')
        if show:
            plt.show()
        else:
            plt.savefig(f'{self.path}\\init_cml.svg', format='svg')
Esempio n. 25
0
def add_decision_boundary(clf, color='gray', cav_origin=None, inv_cav_dir=False):
    """
    Adds the decision boundary to the current figure
    :param clf: The classifier
    :param color: The color of the vector
    :param cav_origin: the origin of the CAV, i.e., the base-vector where the CAV starts.
    :param inv_cav_dir: Invert direction of CAV => this is done out of simplicity reasons
    """
    bias = clf.weights[1].numpy()[0]
    w1, w2 = clf.weights[0].numpy()[:, 0]
    point_a = (0, -bias/w2)
    point_b = (-bias/w1, 0)
    m = - w1/w2
    cav = np.array([-1, 1/m])
    if inv_cav_dir:
        cav *= -1.
    dx, dy = cav / np.linalg.norm(cav)
    plt.axline(point_a, xy2=point_b, color=color)
    if cav_origin is None:
        cav_origin = point_b
    plt.arrow(*cav_origin, dx, dy, color=color, width=0.02, length_includes_head=True, head_width=0.1, zorder=3)
Esempio n. 26
0
    def __init__(self, year_start: int, year_end: int, age_start: int,
                 age_end: int):

        self.year_end = year_end
        self.age_start = age_start

        self.fig, self.ax = plt.subplots(figsize=(year_end - year_start,
                                                  age_end - age_start))
        self.ax.set(xlim=(year_start, year_end),
                    xticks=range(year_start, year_end + 1),
                    ylim=(age_start, age_end),
                    yticks=range(age_start, age_end + 1))

        plt.grid()

        for i in range(year_start - age_end, year_end):
            plt.axline((i, age_start), (i + 1, age_start + 1),
                       linewidth=0.3,
                       color='gray')

        self.titles()
Esempio n. 27
0
    def plot_AUC_convergence(self, output_dir, auc_list, event_type, jetR, jet_pt_bin, R_max):
    
        plt.axis([0, self.K_list[-1], 0, 1])
        if self.plot_title:
            plt.title(rf'{event_type} event: $R = {jetR}, p_T = {jet_pt_bin}, R_{{max}} = {R_max}$', fontsize=14)
        plt.xlabel('K', fontsize=16)
        plt.ylabel('AUC', fontsize=16)

        for label,value in auc_list.items():
        
            if 'hard' in label:
                color = sns.xkcd_rgb['dark sky blue']
                label_suffix = ' (no background)'
            if 'combined' in label:
                color = sns.xkcd_rgb['medium green']
                label_suffix = ' (thermal background)'

            if 'pfn' in label:
                AUC_PFN = value[0]
                label = f'PFN{label_suffix}'
                plt.axline((0, AUC_PFN), (1, AUC_PFN), linewidth=4, label=label,
                           linestyle='solid', alpha=0.5, color=color)
            elif 'efn' in label:
                AUC_EFN = value[0]
                label = f'EFN{label_suffix}'
                plt.axline((0, AUC_EFN), (1, AUC_EFN), linewidth=4, label=label,
                           linestyle='solid', alpha=0.5, color=color)
            elif 'neural_network' in label:
                label = f'DNN{label_suffix}'
                plt.plot(self.K_list, value, linewidth=2,
                         linestyle='solid', alpha=0.9, color=color,
                         label=label)
                    
        plt.legend(loc='lower right', fontsize=12)
        plt.tight_layout()
        plt.savefig(os.path.join(output_dir, f'AUC_convergence{self.auc_plot_index}.pdf'))
        plt.close()

        self.auc_plot_index += 1
Esempio n. 28
0
 def scl(self, name='', show=True):
     '''
     给定资产的证券特征线
     '''
     if name not in self.names:
         sprint(f'name参数值未给定,或参数值{name}不在给定风险资产范围内!已重新随机选择一种给定风险资产!',
                color='red')
         name = random.choice(self.names)
     Ri = self.data[self.data.name == name]['pctChg']
     Rm = self.Rm_data['pctChg']
     ls_dict = self.ls_beta(Ri)
     plt.cla()
     plt.axline(xy1=(0, ls_dict['alpha_ols']),
                slope=ls_dict['beta_ols'],
                c='m')
     plt.scatter(Ri, Rm, s=10, marker=".", c='b')
     plt.xlabel(f'{name}收益率(%)')
     plt.ylabel(f'{self.market_index}收益率(%)')
     if show:
         plt.show()
     else:
         makedir(self.path, 'scl')
         plt.savefig(f'{self.path}\\scl\\{name}.svg', format='svg')
def Create_Points(n, m, plot=False, base="hexagon"):

    a = 2

    #basis = np.array([[0,0],[a/2,0],[a/4,np.sqrt(3)/2],[0,np.sqrt(3)],[a/2,np.sqrt(3)]])
    #basis2 = np.array([[0,0],[a/2,0],[a/4,np.sqrt(3)/2]])
    #basis3 = np.array([[a/4,np.sqrt(3)/2],[0,np.sqrt(3)],[a/2,np.sqrt(3)]])

    hexagon_basis = np.array([[a / 4, np.sqrt(3) / 2], [a / 2,
                                                        np.sqrt(3)],
                              [a, np.sqrt(3)], [a, 0], [a / 2, 0],
                              [5 * 1 / 4 * a, np.sqrt(3) / 2]])

    star_basis = np.array([[0, 0], [a / 2, 0], [a / 4, np.sqrt(3) / 2],
                           [0, np.sqrt(3)], [a / 2, np.sqrt(3)],
                           [3 / 4 * a, 3 / 2 * np.sqrt(3)], [a, np.sqrt(3)],
                           [a, 0], [3 / 4 * a, -np.sqrt(3) / 2],
                           [3 / 2 * a, 0], [3 / 2 * a, np.sqrt(3)],
                           [5 * 1 / 4 * a, np.sqrt(3) / 2]])

    if base == "hexagon":
        basis = hexagon_basis
    if base == "star":
        basis = star_basis

    vec = np.array([[a, 0], [a / 2, a * np.sqrt(3) / 2]])

    rows = m
    cols = n
    """
    vectors = [(0,0)]
    
    vectors = []
    for i in range(0,n+1):
         vectors.append((i,0))
    for i in range(1,n+1):
         vectors.append((i,-1))     
    for i in range(0,n):
         vectors.append((i,1))
    """

    points = []

    vectors = [(j, i) for i in range(0, rows) for j in range(0, cols)]
    """
    vectors = [(0,-1),(1,-1),
              (0,0),(1,0),
              (0,1),(1,1)]
    """
    vectors = sorted(vectors, key=lambda l: l[1])

    #print(vectors)

    for v in vectors:
        point = basis + v[0] * vec[0, :] + v[1] * vec[1, :]
        points.append(point)

    points = np.array(points)

    POINTS = []
    for v in points:
        for a, b, in v:
            POINTS.append([a, b])

    lista = np.unique(np.round(POINTS, 7), axis=0)

    #############################################################################

    if plot == True:
        fig, ax = plt.subplots(figsize=(10, 10))
        x, y = np.array(lista).T

        ax.scatter(x, y)

        for i in range(-100, 100):
            plt.axline((i, 0),
                       slope=np.sqrt(3),
                       color="black",
                       alpha=0.3,
                       linestyle='--',
                       linewidth='1')  #linestyle=(0, (5, 5)))
        for i in range(-100, 100):
            plt.axline((i, 0),
                       slope=-np.sqrt(3),
                       color="black",
                       alpha=0.3,
                       linestyle='--',
                       linewidth='1')  #linestyle=(0, (5, 5)))
        for i in range(-100, 100):
            plt.axline((0, np.sqrt(3) / 2 * i),
                       slope=0,
                       color="black",
                       alpha=0.3,
                       linestyle='--',
                       linewidth='1')

        ax.set_xlim(xmin=min(x) - n, xmax=max(x) + n)
        ax.set_ylim(ymin=min(y) - n, ymax=max(y) + n)
        plt.grid(alpha=0.3)

        plt.show()

    #############################################################################

    return lista
Esempio n. 30
0
        for dim in tf.range(self.book.instrument_dim):
            for step in tf.range(self.timesteps):
                plt.figure()

                xaxis = raw_data["delta"][..., dim, step]

                for dydx in dydx_lst:
                    yaxis = dydx[..., dim, step]
                    plt.scatter(xaxis, yaxis, s=0.5)
                plt.legend([case["name"] for case in self.testcases])

                xlim = plt.xlim()
                ylim = plt.ylim()

                val = min(plt.xlim()[0], plt.ylim()[0])
                plt.axline([val, val], slope=1., color="black")

                plt.xlim(xlim)
                plt.ylim(ylim)

                plt.show()

    def make_feature_function(self, case):
        def gradient_function(raw_data):
            dydx = self.evaluate_case(case, raw_data)

            return tf.unstack(dydx * raw_data["numeraire"][:-1], axis=-1)

        return gradient_function