コード例 #1
0
def update_graph(dt, var, ntr, nte, mod, deg, alp):
    np.random.seed(100)
    x_train, y_train, x_test, y_test = 0, 0, 0, 0

    if dt in ['sin', 'cos', 'exp', 'log']:
        if dt == 'sin':
            x_data = random.uniform(0, 1, ntr)
            x_train = x_data.reshape(-1, 1)  # create a matrix from the list
            y_train = np.sin(2 * np.pi * x_data) + random.normal(
                0, var, x_data.shape)
            x_data_test = random.uniform(0, 1, nte)
            x_test = x_data_test.reshape(-1, 1)
            y_test = np.sin(2 * np.pi * x_data_test) + random.normal(
                0, var, x_data_test.shape)
        if dt == 'cos':
            x_data = random.uniform(0, 1, ntr)
            x_train = x_data.reshape(-1, 1)  # create a matrix from the list
            y_train = np.cos(2 * np.pi * x_data) + random.normal(
                0, var, x_data.shape)
            x_data_test = random.uniform(0, 1, nte)
            x_test = x_data_test.reshape(-1, 1)
            y_test = np.cos(2 * np.pi * x_data_test) + random.normal(
                0, var, x_data_test.shape)
        if dt == 'log':
            x_data = random.uniform(0, 1, ntr)
            x_train = x_data.reshape(-1, 1)  # create a matrix from the list
            y_train = np.log(x_data) + random.normal(0, var, x_data.shape)
            x_data_test = random.uniform(0, 1, nte)
            x_test = x_data_test.reshape(-1, 1)
            y_test = np.log(x_data_test) + random.normal(
                0, var, x_data_test.shape)
        if dt == 'exp':
            x_data = random.uniform(0, 1, ntr)
            x_train = x_data.reshape(-1, 1)  # create a matrix from the list
            y_train = np.exp(x_data) + random.normal(0, var, x_data.shape)
            x_data_test = random.uniform(0, 1, nte)
            x_test = x_data_test.reshape(-1, 1)
            y_test = np.exp(x_data_test) + random.normal(
                0, var, x_data_test.shape)

    X_train = PolynomialFeatures(degree=deg,
                                 include_bias=True).fit_transform(x_train)
    X_test = PolynomialFeatures(degree=deg,
                                include_bias=True).fit_transform(x_test)

    if mod == 'lasso':
        model = Lasso(alpha=alp, normalize=True)
    elif mod == 'ridge':
        model = Ridge(alpha=alp, normalize=True)
    else:
        model = LinearRegression(normalize=True)

    model.fit(X_train, y_train)

    Xmax = X_train
    if X_train.max() < X_test.max():
        Xmax = X_test

    Xmin = X_train
    if X_train.min() > X_test.min():
        Xmin = X_test

    x_range = np.linspace(Xmin.min(), Xmax.max(), 1000,
                          endpoint=True).reshape(-1, 1)
    X_range_poly = PolynomialFeatures(degree=deg,
                                      include_bias=True).fit_transform(x_range)

    y_range = model.predict(X_range_poly)

    test_score = model.score(X_test, y_test)
    test_error = mean_squared_error(y_test, model.predict(X_test))
    train_score = model.score(X_train, y_train)
    train_error = mean_squared_error(y_train, model.predict(X_train))

    eq = format_coefs(model.coef_.round(2))

    fig = go.Figure([
        go.Scatter(x=x_train.squeeze(),
                   y=y_train,
                   name='train',
                   mode='markers'),
        go.Scatter(x=x_test.squeeze(), y=y_test, name='test', mode='markers'),
        go.Scatter(x=x_range.squeeze(), y=y_range, name=eq),
    ])
    fig.update_layout(
        # title= str(dataset) + "  Linear Regression Plot",
        xaxis_title='X',
        yaxis_title="Dependent Variable",
        legend_title="Legend",
        title=f"test_MSE: {test_error:.3f}, train_MSE: {train_error:.3f}",
        legend=dict(orientation='h', ),
        margin=dict(l=25, r=15, t=50, b=50),
        hovermode='closest',
        font=dict(family="Courier New, monospace",
                  size=12,
                  color="RebeccaPurple"))

    return fig