为什么波基的阴谋没有改变?

2024-04-29 19:23:23 发布

您现在位置:Python中文网/ 问答频道 /正文

有人能帮我找出错误吗?我在mpg数据集上训练了一个回归模型,只使用了重量和马力变量。现在我想用Bokeh做一个图,用户可以通过一个滑块来选择重量,图中显示了增加马力的预测。这是我的密码:

import matplotlib.pyplot as plt

import numpy as np
from numpy import linspace

import pandas as pd

import random

import sklearn
from sklearn import linear_model, model_selection
from sklearn.metrics import mean_squared_error, r2_score

from bokeh.plotting import figure 
from bokeh.io import output_notebook, show

output_notebook() # Output im Jupyter-Notebook.

from bokeh.sampledata.autompg import autompg
auto=autompg[['hp','weight']]
mpg=autompg['mpg']

X_train, X_test, Y_train, Y_test = model_selection.train_test_split(auto, mpg, test_size=0.2)

mod = linear_model.LinearRegression()
model=mod.fit(X_train,Y_train)
#print(model.score(X_test,Y_test))

from bokeh.layouts import column
from bokeh.models import CustomJS, ColumnDataSource, Slider
from bokeh.plotting import Figure, output_file, show


# Datenerzeugung:
wtm=np.mean(auto['weight'])

hpmin=0.75*min(auto['hp'])
hpmax=1.25*max(auto['hp'])
hprange=[hpmin+(i/100)*(hpmax-hpmin) for i in range(100)]
l=len(hprange)

newinput=pd.DataFrame(data={'weight':np.repeat(wtm,l), 'hp':hprange})

preds=model.predict(newinput)
#print(list(X_train.columns.values))
#print(model.coef_)
#print(model.intercept_)

intc=model.intercept_
hpcoef=model.coef_[0]
wtcoef=model.coef_[1]


source = ColumnDataSource(data=dict(hprange=hprange, preds=preds, intc=np.repeat(intc,l), hpcoef=np.repeat(hpcoef,l), wtcoef=np.repeat(wtcoef,l)))

plot = Figure(plot_width=400, plot_height=400)

plot.circle(hprange, preds, size=7, color="firebrick", alpha=0.5)

callback = CustomJS(args=dict(source=source), code="""
    var data = source.data;
    var wt = cb_obj.value
    var intc= data['intc']
    var hprange= data['hprange']
    var hpcoef= data['hpcoef']
    var wtcoef= data['wtcoef']
    var preds = data['preds']
    for (var i = 0; i < preds.length; i++) {
        preds[i] = intc[0]+hpcoef[0]*hprange[i]+wtcoef[0]*wt
    }
    source.change.emit();
""")


slider = Slider(start=1500, end=5500, value=3000, step=100, title="Weight")
slider.js_on_change('value', callback)

layout = column(slider, plot)

show(layout)

当我运行它时,它会显示绘图,但当我移动滑块时它不会改变。 我想补充一点,我从来没有使用过javascript,如果原因真的很愚蠢,那么很抱歉。谢谢


Tags: fromtestimportautodatamodelvarnp
1条回答
网友
1楼 · 发布于 2024-04-29 19:23:23

对于将来的任何人:我通过

plot.circle(x='hprange', y='preds', size=7, color="firebrick", alpha=0.5, 
            source=source)

问题是,情节不是指光盘(我想)

不过,感谢bigreddot的评论,它帮助修复了许多其他较小的bug:)

相关问题 更多 >