Почему мои веса после тренировки в этом странном формате? - PullRequest
0 голосов
/ 26 марта 2020

В настоящее время я пытаюсь выучить регрессию логистики c, и я застрял при построении линии от весов после тренировки. Я ожидаю массив из 3 значений, но когда я печатаю веса, чтобы проверить их, я получаю (с разными значениями каждый раз, но в одном и том же формате):

[array([[ 0.42433906], [-0.67847246]], dtype=float32) array([-0.06681705], dtype=float32)]

My вопрос, почему вес в этом формате 2 массива, а не 1 массив длины 3? И как мне интерпретировать эти веса, чтобы я мог построить разделительную линию?

Вот мой код:

from tensorflow import keras
from keras.models import Sequential
from keras.layers import Dense
from keras.regularizers import L1L2
import random
import numpy as np

# return the array data of shape (m, 2) and the array labels of shape (m, 1)
def get_random_data(w, b, mu, sigma, m): # slope, y-intercept, mean of the data, standard deviation, size of arrays
  data = np.empty((m, 2))
  labels = np.empty((m, 1))

  # fill the arrays with random data
  for i in range(m):
    c = (random.random() > 0.5) # 0 with probability 1/2 and 1 with probability 1/2
    n = random.normalvariate(mu, sigma) # noise using normal distribution
    x_1 = random.random() # uniform distribution on [0, 1)
    x_2 = w * x_1 + b + (-1)**c * n

    labels[i] = c
    data[i][0] = x_1
    data[i][1] = x_2


  # the train set is the first 80% of our data, and the test set is the following 20%
  train_length = int(round(m * 0.8, 1)) 

  train_data = np.empty((train_length, 2))
  train_labels = np.empty((train_length, 1))
  test_data = np.empty((m - train_length, 2))
  test_labels = np.empty((m - train_length, 1))

  for i in range(train_length):
    train_data[i] = data[i]
    train_labels[i] = labels[i]

  for i in range(train_length, m):
    test_data[i - train_length] = data[i]
    test_labels[i - train_length] = labels[i]

  return (train_data, train_labels), (test_data, test_labels)

(train_data, train_labels), (test_data, test_labels) = get_random_data(2,3,100,100,200)

model = Sequential()
model.add(Dense(train_labels.shape[1],
                activation='sigmoid',
                kernel_regularizer=L1L2(l1=0.0, l2=0.1),
                input_dim=(train_data.shape[1]))) 
model.compile(optimizer='sgd',
              loss='binary_crossentropy',
              metrics=['accuracy'])

model.fit(train_data, train_labels, epochs=100, validation_data=(test_data,test_labels))

weights = np.asarray(model.get_weights())
print("the weights are " , weights)

1 Ответ

1 голос
/ 28 марта 2020

Первый индекс массива показывает веса коэффициентов, а второй массив показывает смещение.

Итак, у вас есть уравнение, подобное приведенному ниже.

h(x) = 0.42433906x1 + -0.67847246x2 + -0.06681705

Logisti c регрессия принимает это уравнение и применяет сигмовидную функцию, чтобы сжать результаты между 0-1.

Итак, если вы хотите нарисовать уравнение линии, вы можете использовать сделать это с возвращенными весами, как я объяснил выше.

...