from__future__importannotationsimportmatplotlib.pyplotaspltimportnumpyasnpfromsklearn.datasetsimportmake_blobsfromsklearn.discriminant_analysisimportLinearDiscriminantAnalysisfromsklearn.metricsimportaccuracy_scoredefrun_lda_demo(n_samples:int=200,random_state:int=42,title_boundary:str="LDA の決定境界",title_projection:str="LDA による一次元射影",xlabel:str="特徴量1",ylabel:str="特徴量2",hist_xlabel:str="射影後の特徴量",class0_label:str="クラス0",class1_label:str="クラス1",)->dict[str,float]:"""Train LDA on synthetic blobs and plot boundary plus projection."""X,y=make_blobs(n_samples=n_samples,centers=2,n_features=2,cluster_std=2.0,random_state=random_state,)clf=LinearDiscriminantAnalysis(store_covariance=True)clf.fit(X,y)accuracy=float(accuracy_score(y,clf.predict(X)))w=clf.coef_[0]b=float(clf.intercept_[0])xs=np.linspace(X[:,0].min()-1,X[:,0].max()+1,300)ys_boundary=-(w[0]/w[1])*xs-b/w[1]fig,ax=plt.subplots(figsize=(7,6))ax.set_title(title_boundary)ax.scatter(X[:,0],X[:,1],c=y,cmap="coolwarm",edgecolor="k",alpha=0.8)ax.plot(xs,ys_boundary,"k--",lw=1.2,label="w^T x + b = 0")ax.set_xlabel(xlabel)ax.set_ylabel(ylabel)ax.legend(loc="best")ax.grid(alpha=0.25)fig.tight_layout()plt.show()X_proj=clf.transform(X)[:,0]fig,ax=plt.subplots(figsize=(8,4))ax.set_title(title_projection)ax.hist(X_proj[y==0],bins=20,alpha=0.7,label=class0_label)ax.hist(X_proj[y==1],bins=20,alpha=0.7,label=class1_label)ax.set_xlabel(hist_xlabel)ax.legend(loc="best")ax.grid(alpha=0.25)fig.tight_layout()plt.show()return{"accuracy":accuracy}metrics=run_lda_demo(title_boundary="LDA の決定境界",title_projection="LDA による一次元射影",xlabel="特徴量1",ylabel="特徴量2",hist_xlabel="射影後の特徴量",class0_label="クラス0",class1_label="クラス1",)print(f"訓練精度: {metrics['accuracy']:.3f}")