只需输入神经网络参数parameter(权重和系数)的结构体。
function plot_fully_connected_network(parameters)
layers = fieldnames(parameters); % 获取所有层的名字
numLayers = numel(layers);
% 确定每层的神经元数目并找到最大值
neuronsPerLayer = arrayfun(@(x) numel(parameters.(layers{x}).Bias), 1:numLayers);
maxNeurons = max(neuronsPerLayer);
% 确定输入层神经元的数量
inputNeurons = size(parameters.(layers{1}).Weights, 2);
figure;
hold on;
% 设置图形属性
xlim([0, numLayers + 2]);
ylim([0, maxNeurons + 1]);
xlabel(['Layer=' num2str(numLayers+1)]);
ylabel('Neurons');
% 绘制连接,如果权重不为零
for i = 1:numLayers
currYPos = (maxNeurons - neuronsPerLayer(i)) / 2 + 1 : (maxNeurons + neuronsPerLayer(i)) / 2;
if i == 1
prevYPos = (maxNeurons - inputNeurons) / 2 + 1 : (maxNeurons + inputNeurons) / 2;
weights = parameters.(layers{i}).Weights;
else
prevYPos = (maxNeurons - neuronsPerLayer(i-1)) / 2 + 1 : (maxNeurons + neuronsPerLayer(i-1)) / 2;
weights = parameters.(layers{i}).Weights;
end
for j = 1:numel(prevYPos)
for k = 1:numel(currYPos)
if weights(k, j) ~= 0 % 检查权重是否为零
% % 连接线随权重大小而改变粗细
% lineWidth = min(abs(weights(k, j)) * 5, 5);
% lineWidth = double(gather(extractdata(max(lineWidth, 0.1))));
% line([i, i+1], [prevYPos(j), currYPos(k)], 'Color', [0 0 0], 'LineWidth', lineWidth);
% 连接线全部一样粗细
line([i, i+1], [prevYPos(j), currYPos(k)], 'Color', [0 0 0]);
end
end
end
end
% 绘制神经元,确保垂直居中
for i = 0:numLayers
if i == 0
numNeurons = inputNeurons;
else
numNeurons = neuronsPerLayer(i);
end
% 计算垂直居中的位置
yPos = (maxNeurons - numNeurons) / 2 + 1 : (maxNeurons + numNeurons) / 2;
plot(i + 1, yPos, 'bo', 'MarkerSize', 20, 'MarkerFaceColor', 'r');
end
% 设置坐标轴标签
xticklabels = {'输入层'};
for i = 1:numLayers-1
xticklabels{end+1} = ['隐藏层' num2str(i)];
end
xticklabels{end+1} = '输出层';
set(gca, 'YDir', 'reverse')
set(gca, 'XTick', 1:(numLayers + 1), 'XTickLabel', xticklabels);
set(gca, 'YTick', []);
set(gca, 'XAxisLocation', 'origin', 'YAxisLocation', 'origin');
hold off;
end
以下是Python代码及调用方式
import matplotlib.pyplot as plt
import matplotlib.patches as patches
# Updated function to draw a neural network cartoon using matplotlib.
# This function now automatically generates the labels based on the size of each layer.
def draw_neural_net(ax, left, right, bottom, top, layer_sizes):
'''
Draw a neural network cartoon using matplotlib.
'''
v_spacing = (top - bottom)/float(max(layer_sizes))
h_spacing = (right - left)/float(len(layer_sizes) - 1)
# Nodes
for n, layer_size in enumerate(layer_sizes):
layer_top = v_spacing*(layer_size - 1)/2. + (top + bottom)/2.
for m in range(layer_size):
node_color = 'white' if n == 0 else 'lightblue' if n == len(layer_sizes) - 1 else 'lightgreen'
circle = patches.Circle((n*h_spacing + left, layer_top - m*v_spacing), v_spacing/4.,
edgecolor='k', facecolor=node_color, zorder=4)
ax.add_patch(circle)
# Edges
for n, (layer_size_a, layer_size_b) in enumerate(zip(layer_sizes[:-1], layer_sizes[1:])):
layer_top_a = v_spacing*(layer_size_a - 1)/2. + (top + bottom)/2.
layer_top_b = v_spacing*(layer_size_b - 1)/2. + (top + bottom)/2.
for m in range(layer_size_a):
for o in range(layer_size_b):
line = patches.ConnectionPatch(xyA=(n*h_spacing + left, layer_top_a - m*v_spacing),
xyB=((n + 1)*h_spacing + left, layer_top_b - o*v_spacing),
coordsA='data', coordsB='data', axesA=ax, axesB=ax,
arrowstyle='->', color='darkgray', zorder=1)
ax.add_patch(line)
# Create the figure and the axes
fig, ax = plt.subplots(figsize=(9, 9))
ax.axis('off')
# Draw the neural network with specified layer sizes
draw_neural_net(ax, .1, .9, .1, .9, [3, 10, 20, 10, 10, 10, 10, 1])
# Show the neural network
plt.show()