首页 > 解决方案 > 如何从一个简单的感知器绘制斜率

问题描述

我想在权重变化时绘制斜率 y = mx+b 但我不知道如何获得 m 和 b 的值

这是代码:

import numpy as np
import matplotlib.pyplot as plt

def sign(x):
  return 1 if x > 0 else 0

def get_mse(predicted_data, targets):
  error = predicted_data - targets
  return np.square(error).sum()/len(targets)

fit_data = np.array([[1,0,0],
                     [1,0,1],
                     [1,1,0],
                     [1,1,1],])

targets = np.array([0,0,0,1])
weights = np.array([0,0,0])
lr = 1
epochs = 10

mse_hist = []

for _ in range(epochs):
  model_outputs = []
  for i in range(len(targets)):
    y = (fit_data[i] * weights).sum()
    y = sign(y)
    error = targets[i] - y
    weights = weights + fit_data[i] * error * lr

    model_outputs.append(y)
  mse = get_mse(model_outputs, targets)
  mse_hist.append(mse)

这里应该是斜坡的情节,至少我是这么认为的

  print("Weights:", weights)
  print("Mse:", mse_hist[-1])
  plt.plot(mse_hist)
  plt.xlabel('Iterations')
  plt.ylabel('Mean Squared Error')
  plt.pause(0.5)

plt.show()

input_data = ([1,1,1])
prediction = (input_data * weights).sum()
prediction = sign(prediction)
print("Prediction:", prediction)

谢谢您的帮助

标签: python-3.xneural-networkgoogle-colaboratoryperceptron

解决方案


推荐阅读