陈骋
发布于 2025-03-31 / 44 阅读
0
0

动态演示:回归模型 | SoftMax函数

回归模型演示:

用户:

代码模式你是一名程序员,你的任务是编写python代码,动态展示线性回归。要求:

  • 可以通过小滑块,调节截距和斜率
  • 随时计算残差平方和

AI:

为了实现这个功能,我们可以使用Python中的matplotlib库来绘制图形,并使用ipywidgets库来创建滑块。以下是一个完整的代码示例,展示了如何动态展示线性回归并通过滑块调节截距和斜率,同时计算残差平方和。

首先,确保你已经安装了所需的库:

pip install matplotlib ipywidgets numpy

然后,以下是完整的Python代码:

import numpy as np
import matplotlib.pyplot as plt
from IPython.display import display
import ipywidgets as widgets

# 生成一些样本数据
np.random.seed(0)
X = 2 * np.random.rand(100, 1)
y = 4 + 3 * X + np.random.randn(100, 1)

def plot_linear_regression(intercept, slope):
    # 计算预测值
    y_pred = intercept + slope * X
    
    # 计算残差平方和
    residuals = y - y_pred
    rss = np.sum(residuals ** 2)
    
    # 绘制散点图和拟合直线
    plt.figure(figsize=(8, 6))
    plt.scatter(X, y, color='blue', label='Data points')
    plt.plot(X, y_pred, color='red', linewidth=2, label=f'Fit line: y = {intercept:.2f} + {slope:.2f}x\nRSS: {rss:.2f}')
    plt.xlabel('X')
    plt.ylabel('y')
    plt.title('Linear Regression with Dynamic Intercept and Slope')
    plt.legend()
    plt.grid(True)
    plt.show()

# 创建滑块
intercept_slider = widgets.FloatSlider(value=4.0, min=-10.0, max=10.0, step=0.1, description='Intercept:')
slope_slider = widgets.FloatSlider(value=3.0, min=-10.0, max=10.0, step=0.1, description='Slope:')

# 将滑块与绘图函数绑定
interactive_plot = widgets.interactive(plot_linear_regression, intercept=intercept_slider, slope=slope_slider)

# 显示交互式绘图
display(interactive_plot)

这段代码首先生成了一些随机的样本数据,然后定义了一个函数plot_linear_regression,用于根据给定的截距和斜率绘制线性回归图,并计算和显示残差平方和(RSS)。接着,使用ipywidgets库创建了两个滑块,分别用于调整截距和斜率,并将这些滑块与绘图函数绑定在一起。最后,通过display函数显示交互式的绘图界面。

请注意,这段代码需要在支持Jupyter Notebook或类似的环境中运行才能正常工作。


SoftMax演示:

用户:

代码模式你是一名程序员,你的任务是编写python代码,动态展示SoftMax函数。要求:

  • 可以通过小滑块,调节“温度”
  • 实时展示计算概率的变化

AI:

为了实现这个功能,我们可以使用Python中的matplotlib库来绘制图形,并使用ipywidgets库来创建滑块。以下是一个完整的代码示例,展示了如何动态展示SoftMax函数并通过滑块调节“温度”,同时实时展示计算概率的变化。

首先,确保你已经安装了所需的库:

pip install matplotlib ipywidgets numpy

然后,以下是完整的Python代码:

import numpy as np
import matplotlib.pyplot as plt
from IPython.display import display
import ipywidgets as widgets

# 生成一些样本数据
np.random.seed(0)
scores = np.array([1.0, 2.0, 3.0])

def softmax(scores, temperature):
    # 计算SoftMax概率分布
    exp_scores = np.exp((scores - np.max(scores)) / temperature)
    probabilities = exp_scores / np.sum(exp_scores)
    return probabilities

def plot_softmax(temperature):
    # 计算SoftMax概率
    probs = softmax(scores, temperature)
    
    # 绘制柱状图
    plt.figure(figsize=(8, 6))
    bars = plt.bar(range(len(scores)), probs, tick_label=[f'Score {i+1}' for i in range(len(scores))], color='skyblue')
    plt.xlabel('Scores')
    plt.ylabel('Probability')
    plt.title(f'SoftMax Probabilities with Temperature: {temperature:.2f}')
    plt.ylim(0, 1)
    plt.grid(axis='y', linestyle='--', alpha=0.7)
    
    # 显示每个条形的概率值
    for bar, prob in zip(bars, probs):
        yval = bar.get_height()
        plt.text(bar.get_x() + bar.get_width()/2, yval, f'{prob:.2f}', ha='center', va='bottom')  # va: vertical alignment
    
    plt.show()

# 创建滑块
temperature_slider = widgets.FloatSlider(value=1.0, min=0.1, max=5.0, step=0.1, description='Temperature:')

# 将滑块与绘图函数绑定
interactive_plot = widgets.interactive(plot_softmax, temperature=temperature_slider)

# 显示交互式绘图
display(interactive_plot)

这段代码首先生成了一些样本得分数据,然后定义了一个函数softmax,用于根据给定的温度计算SoftMax概率分布。接着,定义了另一个函数plot_softmax,用于绘制这些概率分布的柱状图,并在每个条形上显示概率值。使用ipywidgets库创建了一个滑块,用于调整温度,并将这个滑块与绘图函数绑定在一起。最后,通过display函数显示交互式的绘图界面。

请注意,这段代码需要在支持Jupyter Notebook或类似的环境中运行才能正常工作。

用户:

请展示5个scores,同时温度的调节范围扩大到10.

AI:

好的,我会更新代码以展示5个得分,并将温度的调节范围扩大到10。以下是完整的Python代码:

import numpy as np
import matplotlib.pyplot as plt
from IPython.display import display
import ipywidgets as widgets

# 生成一些样本数据
np.random.seed(0)
scores = np.array([1.0, 2.0, 3.0, 4.0, 5.0])

def softmax(scores, temperature):
    # 计算SoftMax概率分布
    exp_scores = np.exp((scores - np.max(scores)) / temperature)
    probabilities = exp_scores / np.sum(exp_scores)
    return probabilities

def plot_softmax(temperature):
    # 计算SoftMax概率
    probs = softmax(scores, temperature)
    
    # 绘制柱状图
    plt.figure(figsize=(8, 6))
    bars = plt.bar(range(len(scores)), probs, tick_label=[f'Score {i+1}' for i in range(len(scores))], color='skyblue')
    plt.xlabel('Scores')
    plt.ylabel('Probability')
    plt.title(f'SoftMax Probabilities with Temperature: {temperature:.2f}')
    plt.ylim(0, 1)
    plt.grid(axis='y', linestyle='--', alpha=0.7)
    
    # 显示每个条形的概率值
    for bar, prob in zip(bars, probs):
        yval = bar.get_height()
        plt.text(bar.get_x() + bar.get_width()/2, yval, f'{prob:.2f}', ha='center', va='bottom')  # va: vertical alignment
    
    plt.show()

# 创建滑块
temperature_slider = widgets.FloatSlider(value=1.0, min=0.1, max=10.0, step=0.1, description='Temperature:')

# 将滑块与绘图函数绑定
interactive_plot = widgets.interactive(plot_softmax, temperature=temperature_slider)

# 显示交互式绘图
display(interactive_plot)

这段代码现在生成了五个样本得分数据,并且温度的调节范围已经扩大到10。通过滑块可以调整温度,并实时查看SoftMax概率分布的变化。

请注意,这段代码需要在支持Jupyter Notebook或类似的环境中运行才能正常工作。


评论