有人可以帮我找到错误吗?我仅使用重量和马力变量在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,很抱歉,如果原因是一个非常愚蠢的原因。谢谢!
答案 0 :(得分:1)
对于未来的任何人:我通过
修复它plot.circle(x='hprange', y='preds', size=7, color="firebrick", alpha=0.5,
source=source)
问题在于情节并没有提到CDS(我认为)。
感谢bigreddot的评论,但这有助于修复许多其他较小的错误:)