神经元模拟:使用python构建的动态学习与突触演化

用于模拟学习过程中神经元的结构变化与链接以及长期维持。
我们将模拟以下概念:
神经元和突触:神经元会通过突触连接,突触具有强度(权重)。
学习过程:通过模拟神经元的激活和突触强度的改变来体现学习(例如赫布理论:同时激活的神经元连接增强)。
结构变化:包括新突触的生成(链接)和现有突触的削弱或移除(修剪)。
长期维持:通过设置一些规则来模拟长期记忆的巩固,比如反复激活的突触会变得更强且更稳定。
模拟思路:
我们将创建一组神经元,每个神经元有状态(激活/非激活)。
神经元之间的连接(突触)有权重,权重会随着神经元的共同激活而改变。
模拟将分为多个时间步。在每个时间步,一部分神经元被激活(模拟学习刺激)。
应用赫布学习规则:如果两个神经元同时激活,则它们之间的突触权重增加。
同时,我们也会引入突触修剪:权重低于某个阈值的突触会被移除。
为了模拟长期维持,我们可以设置一个巩固机制:经常被强化的突触会进入“稳定”状态,不易被削弱。
我们将使用Streamlit来展示:
神经网络的动态变化(使用图表或图形库)。
控制参数(如学习率、修剪阈值、模拟步数等)。
统计信息(如突触数量、平均权重等)。
由于Streamlit本身不提供动态图形更新,我们可以使用Altair或Plotly来创建交互式图表,或者使用静态图表并每步更新。
然而,由于神经元网络的动态可视化可能比较复杂,我们可以考虑使用网络图(如使用NetworkX和Plotly)来展示神经元之间的连接。
步骤:
定义神经元和突触的类。
定义模拟世界的更新规则。
使用Streamlit构建控制面板(参数输入、开始/暂停按钮等)。
使用Plotly绘制网络图,并实时更新。
import streamlit as st
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
from matplotlib.patches import Circle
import time
import random# 设置中文字体
def set_chinese_font():try:plt.rcParams['font.sans-serif'] = ['SimHei', 'Microsoft YaHei', 'SimSun', 'DejaVu Sans']plt.rcParams['axes.unicode_minus'] = Falseexcept:plt.rcParams['font.sans-serif'] = ['DejaVu Sans']set_chinese_font()# 设置页面
st.set_page_config(page_title="神经元学习模拟器-多类型对比",page_icon="🧠",layout="wide"
)# 应用暗色主题CSS
st.markdown("""
<style>/* 主背景色 */.stApp {background-color: #0e1117;color: #fafafa;}/* 侧边栏背景 */.css-1d391kg {background-color: #262730;}/* 统计卡片背景 */.stMetric {background-color: #1e1e1e;border: 1px solid #333;border-radius: 10px;padding: 15px;margin: 10px 0;box-shadow: 0 4px 6px rgba(0, 0, 0, 0.3);}/* 统计卡片文字颜色 */.stMetric label {color: #ffffff !important;font-weight: bold;}.stMetric div {color: #4cd964 !important;font-size: 1.5em !important;font-weight: bold;}/* 按钮样式 */.stButton>button {background-color: #4a4a4a;color: white;border: none;border-radius: 5px;padding: 10px 20px;font-weight: bold;}.stButton>button:hover {background-color: #5a5a5a;}/* 标题颜色 */h1, h2, h3, h4, h5, h6 {color: #ffffff !important;}/* 文本颜色 */.stMarkdown {color: #f0f0f0;}/* 滑块样式 */.stSlider>div>div>div {background-color: #4cd964;}/* 复选框样式 */.stCheckbox>label {color: white;}/* 扩展器样式 */.streamlit-expanderHeader {background-color: #2d2d2d;color: white;border: 1px solid #444;}
</style>
""", unsafe_allow_html=True)# 应用标题和描述
st.title("🧠 神经元学习过程模拟器 - 多类型对比")
st.markdown("""
本模拟器同时展示四种不同学习类型下,大脑神经元建立连接、加强连接以及维持长期记忆的过程,便于直观比较不同学习模式的差异。
""")# 侧边栏控制面板
st.sidebar.header("模拟控制参数")# 模拟参数
learning_intensity = st.sidebar.slider("学习强度", 0.1, 1.0, 0.7, 0.1)
repetition_count = st.sidebar.slider("重复次数", 1, 10, 3)
sleep_quality = st.sidebar.slider("睡眠质量(记忆巩固)", 0.1, 1.0, 0.8, 0.1)
simulation_speed = st.sidebar.slider("模拟速度", 1, 10, 5)# 学习类型定义
learning_types = {"新知识学习": {"description": "新的神经通路形成,连接较弱且不稳定","color": "red","intensity_factor": 0.8,  # 较高学习强度"plasticity": 0.4,  # 较高可塑性"pruning": 0.1  # 较低修剪率},"技能练习": {"description": "通过重复加强特定神经通路,提高效率","color": "blue","intensity_factor": 1.0,  # 标准学习强度"plasticity": 0.2,  # 中等可塑性"pruning": 0.05  # 中等修剪率},"记忆巩固": {"description": "睡眠期间神经网络重组,强化重要连接","color": "green","intensity_factor": 0.6,  # 较低学习强度"plasticity": 0.1,  # 较低可塑性"pruning": 0.02  # 较低修剪率},"概念关联": {"description": "不同脑区神经元建立新连接,形成知识网络","color": "purple","intensity_factor": 0.9,  # 较高学习强度"plasticity": 0.3,  # 较高可塑性"pruning": 0.08  # 中等修剪率}
}# 初始化学习类型状态
for ltype in learning_types:if f'neurons_{ltype}' not in st.session_state:st.session_state[f'neurons_{ltype}'] = []if f'connections_{ltype}' not in st.session_state:st.session_state[f'connections_{ltype}'] = []if f'learning_stage_{ltype}' not in st.session_state:st.session_state[f'learning_stage_{ltype}'] = 0if f'activated_neurons_{ltype}' not in st.session_state:st.session_state[f'activated_neurons_{ltype}'] = set()# 创建神经元网格的函数
def create_neuron_grid(rows, cols):neurons = []for i in range(rows):for j in range(cols):neurons.append({'id': len(neurons),'x': j * 2,'y': i * 2,'active': False,'activation_level': 0.0,'connections': {}})return neurons# 为每种学习类型初始化神经元
for ltype in learning_types:if not st.session_state[f'neurons_{ltype}']:st.session_state[f'neurons_{ltype}'] = create_neuron_grid(4, 5)  # 调整为4x5网格# 创建初始随机连接
def initialize_connections(neurons, num_connections=12):connections = []for _ in range(num_connections):i, j = random.sample(range(len(neurons)), 2)strength = random.uniform(0.1, 0.5)connections.append({'from': i,'to': j,'strength': strength,'active': False})neurons[i]['connections'][j] = strengthreturn connections# 为每种学习类型初始化连接
for ltype in learning_types:if not st.session_state[f'connections_{ltype}']:neurons = st.session_state[f'neurons_{ltype}']st.session_state[f'connections_{ltype}'] = initialize_connections(neurons)# 模拟学习过程的函数(针对特定学习类型)
def simulate_learning_for_type(ltype):neurons = st.session_state[f'neurons_{ltype}']connections = st.session_state[f'connections_{ltype}']activated = st.session_state[f'activated_neurons_{ltype}']# 根据学习类型调整参数type_params = learning_types[ltype]adjusted_intensity = learning_intensity * type_params['intensity_factor']plasticity = type_params['plasticity']pruning_rate = type_params['pruning']# 根据学习强度激活一些神经元num_to_activate = max(2, int(len(neurons) * adjusted_intensity * 0.3))new_activated = random.sample(range(len(neurons)), num_to_activate)# 重置激活状态for neuron in neurons:neuron['active'] = Falseneuron['activation_level'] = 0.0# 激活选中的神经元for neuron_id in new_activated:neurons[neuron_id]['active'] = Trueneurons[neuron_id]['activation_level'] = 1.0activated.add(neuron_id)# 根据赫布理论加强同时激活的神经元之间的连接for conn in connections:if (neurons[conn['from']]['active'] and neurons[conn['to']]['active']):conn['strength'] = min(1.0, conn['strength'] + 0.1 * adjusted_intensity)conn['active'] = Trueneurons[conn['from']]['connections'][conn['to']] = conn['strength']else:conn['active'] = False# 根据睡眠质量进行记忆巩固if random.random() < sleep_quality * 0.1:conn['strength'] = min(1.0, conn['strength'] + 0.01)neurons[conn['from']]['connections'][conn['to']] = conn['strength']# 根据可塑性创建新连接if random.random() < plasticity:i, j = random.sample(range(len(neurons)), 2)existing_conn = next((c for c in connections if c['from'] == i and c['to'] == j), None)if not existing_conn:new_strength = random.uniform(0.1, 0.3)connections.append({'from': i,'to': j,'strength': new_strength,'active': False})neurons[i]['connections'][j] = new_strength# 突触修剪connections_to_remove = []for i, conn in enumerate(connections):if conn['strength'] < 0.1 and random.random() < pruning_rate:connections_to_remove.append(i)for i in sorted(connections_to_remove, reverse=True):conn = connections.pop(i)if conn['to'] in neurons[conn['from']]['connections']:del neurons[conn['from']]['connections'][conn['to']]st.session_state[f'learning_stage_{ltype}'] += 1# 绘制神经元网络的函数(针对特定学习类型)
def plot_neural_network_for_type(ltype):neurons = st.session_state[f'neurons_{ltype}']connections = st.session_state[f'connections_{ltype}']type_params = learning_types[ltype]# 设置暗色主题的图表样式plt.style.use('dark_background')fig, ax = plt.subplots(figsize=(8, 6), facecolor='#0e1117')ax.set_aspect('equal')ax.set_facecolor('#1e1e1e')  # 图表背景色# 绘制连接for conn in connections:from_neuron = neurons[conn['from']]to_neuron = neurons[conn['to']]strength = conn['strength']linewidth = max(0.5, strength * 4)if conn['active']:color = '#ff6b6b'  # 活跃连接的亮红色else:# 使用学习类型的特定颜色base_color = type_params['color']if base_color == 'red':color = plt.cm.Reds(0.3 + 0.7 * strength)elif base_color == 'blue':color = plt.cm.Blues(0.3 + 0.7 * strength)elif base_color == 'green':color = plt.cm.Greens(0.3 + 0.7 * strength)else:  # purplecolor = plt.cm.Purples(0.3 + 0.7 * strength)ax.plot([from_neuron['x'], to_neuron['x']],[from_neuron['y'], to_neuron['y']],color=color, linewidth=linewidth, alpha=0.7)# 绘制神经元for neuron in neurons:x, y = neuron['x'], neuron['y']activation = neuron['activation_level']if neuron['active']:color = '#ff6b6b'  # 活跃神经元的亮红色else:base_color = type_params['color']if base_color == 'red':color = plt.cm.Oranges(0.3 + 0.7 * activation)elif base_color == 'blue':color = plt.cm.Blues(0.5 + 0.5 * activation)elif base_color == 'green':color = plt.cm.Greens(0.5 + 0.5 * activation)else:  # purplecolor = plt.cm.Purples(0.5 + 0.5 * activation)circle = Circle((x, y), 0.15, facecolor=color, edgecolor='white', linewidth=1.2)ax.add_patch(circle)ax.text(x, y, str(neuron['id']), ha='center', va='center',fontsize=6, fontweight='bold', color='white')ax.set_xlim(-1, 9)ax.set_ylim(-1, 7)ax.axis('off')stage = st.session_state[f'learning_stage_{ltype}']plt.title(f"{ltype}\n(阶段: {stage})", fontsize=12, pad=10, color='white')return fig# 绘制对比统计图
def plot_comparison_chart():# 收集各学习类型的统计数据types = list(learning_types.keys())active_counts = []total_connections = []avg_strengths = []strong_connections = []for ltype in types:neurons = st.session_state[f'neurons_{ltype}']connections = st.session_state[f'connections_{ltype}']active_counts.append(sum(1 for n in neurons if n['active']))total_connections.append(len(connections))strengths = [c['strength'] for c in connections]avg_strengths.append(np.mean(strengths) if strengths else 0)strong_connections.append(sum(1 for c in connections if c['strength'] > 0.7))# 创建对比图表 - 使用暗色主题plt.style.use('dark_background')fig, axes = plt.subplots(2, 2, figsize=(12, 8), facecolor='#0e1117')# 设置子图背景色for ax in axes.flat:ax.set_facecolor('#1e1e1e')# 活跃神经元数量对比bars1 = axes[0, 0].bar(types, active_counts, color=[learning_types[t]['color'] for t in types], alpha=0.7)axes[0, 0].set_title('活跃神经元数量对比', color='white')axes[0, 0].set_ylabel('数量', color='white')axes[0, 0].tick_params(colors='white')for bar, count in zip(bars1, active_counts):axes[0, 0].text(bar.get_x() + bar.get_width() / 2, bar.get_height(),f'{count}', ha='center', va='bottom', color='white')# 总连接数对比bars2 = axes[0, 1].bar(types, total_connections, color=[learning_types[t]['color'] for t in types], alpha=0.7)axes[0, 1].set_title('总突触连接数对比', color='white')axes[0, 1].set_ylabel('数量', color='white')axes[0, 1].tick_params(colors='white')for bar, count in zip(bars2, total_connections):axes[0, 1].text(bar.get_x() + bar.get_width() / 2, bar.get_height(),f'{count}', ha='center', va='bottom', color='white')# 平均连接强度对比bars3 = axes[1, 0].bar(types, avg_strengths, color=[learning_types[t]['color'] for t in types], alpha=0.7)axes[1, 0].set_title('平均连接强度对比', color='white')axes[1, 0].set_ylabel('强度', color='white')axes[1, 0].set_ylim(0, 1)axes[1, 0].tick_params(colors='white')for bar, strength in zip(bars3, avg_strengths):axes[1, 0].text(bar.get_x() + bar.get_width() / 2, bar.get_height(),f'{strength:.2f}', ha='center', va='bottom', color='white')# 强连接数对比bars4 = axes[1, 1].bar(types, strong_connections, color=[learning_types[t]['color'] for t in types], alpha=0.7)axes[1, 1].set_title('强连接数对比(>0.7)', color='white')axes[1, 1].set_ylabel('数量', color='white')axes[1, 1].tick_params(colors='white')for bar, count in zip(bars4, strong_connections):axes[1, 1].text(bar.get_x() + bar.get_width() / 2, bar.get_height(),f'{count}', ha='center', va='bottom', color='white')plt.tight_layout()return fig# 主界面布局
st.subheader("四种学习类型同时模拟")# 控制按钮
col1, col2, col3, col4 = st.columns(4)with col1:if st.button("单步模拟所有类型", key="step_all", use_container_width=True):for ltype in learning_types:simulate_learning_for_type(ltype)with col2:if st.button("重置所有模拟", key="reset_all", use_container_width=True):for ltype in learning_types:st.session_state[f'neurons_{ltype}'] = create_neuron_grid(4, 5)st.session_state[f'connections_{ltype}'] = initialize_connections(st.session_state[f'neurons_{ltype}'])st.session_state[f'learning_stage_{ltype}'] = 0st.session_state[f'activated_neurons_{ltype}'] = set()with col3:auto_simulate = st.checkbox("自动模拟所有类型", key="auto_all")with col4:if st.button("快速模拟10步", key="fast_10", use_container_width=True):for _ in range(10):for ltype in learning_types:simulate_learning_for_type(ltype)# 显示四种学习类型的神经元网络
st.subheader("神经元网络动态对比")
cols = st.columns(2)for i, ltype in enumerate(learning_types):with cols[i % 2]:st.markdown(f"**{ltype}**")st.caption(learning_types[ltype]['description'])fig = plot_neural_network_for_type(ltype)st.pyplot(fig)# 显示当前类型的统计信息neurons = st.session_state[f'neurons_{ltype}']connections = st.session_state[f'connections_{ltype}']active_neurons = sum(1 for n in neurons if n['active'])total_conn = len(connections)strong_conn = sum(1 for c in connections if c['strength'] > 0.7)avg_strength = np.mean([c['strength'] for c in connections]) if connections else 0# 使用自定义样式的metric显示col1, col2 = st.columns(2)with col1:st.markdown(f"""<div class="stMetric"><label>活跃神经元</label><div>{active_neurons}</div></div>""", unsafe_allow_html=True)st.markdown(f"""<div class="stMetric"><label>总连接数</label><div>{total_conn}</div></div>""", unsafe_allow_html=True)with col2:st.markdown(f"""<div class="stMetric"><label>强连接数</label><div>{strong_conn}</div></div>""", unsafe_allow_html=True)st.markdown(f"""<div class="stMetric"><label>平均强度</label><div>{avg_strength:.2f}</div></div>""", unsafe_allow_html=True)# 显示对比图表
st.subheader("学习类型对比分析")
comparison_fig = plot_comparison_chart()
st.pyplot(comparison_fig)# 自动模拟
if auto_simulate:time.sleep(1.0 / simulation_speed)for ltype in learning_types:simulate_learning_for_type(ltype)st.rerun()# 学习类型特性说明
st.subheader("学习类型特性说明")for ltype, params in learning_types.items():with st.expander(f"{ltype} - {params['description']}"):st.write(f"""- **学习强度因子**: {params['intensity_factor']} - 影响神经元激活频率和连接加强速度- **神经可塑性**: {params['plasticity']} - 影响新连接形成的概率- **突触修剪率**: {params['pruning']} - 影响弱连接被消除的概率- **颜色标识**: {params['color']}""")
