В настоящее время я изучаю специализацию Deep Learning Deeplearning.ai на Coursera и выполняю первое задание, требующее внедрения нейронной сети с мышлением логистической регрессии. Проблема заключается в том, что назначением является реализация функции нейронной сети как логистической регрессии для НЕСТРУКТУРИРОВАННЫЕ ДАННЫЕ (ИЗОБРАЖЕНИЯ) . Я успешно выполнил задание, получив все ожидаемые результаты. Однако сейчас я пытаюсь использовать закодированную нейронную сеть для СТРУКТУРНЫХ ДАННЫХ , но сталкиваюсь с ошибкой вещания. Часть кода выглядит следующим образом:
Код набора данных
path_train = r'C:\Users\Ahmed Ismail Khalid\Desktop\Research Paper\Research Paper Feature Sets\Balanced Feature Sets\Balanced Train combined scores.csv'
path_test = r'C:\Users\Ahmed Ismail Khalid\Desktop\Research Paper\Research Paper Feature Sets\Balanced Feature Sets\Balanced Test combined scores.csv'
df_train = pd.read_csv(path_train)
#df_train = df_train.to_numpy()
df_test = pd.read_csv(path_test)
#df_test = df_test.to_numpy()
x_train = df_train.iloc[:,1:19]
x_train = x_train.to_numpy()
x_train = x_train.T
y_train = df_train.iloc[:,19]
y_train = y_train.to_numpy()
y_train = y_train.reshape(y_train.shape[0],1)
y_train = y_train.T
x_test = df_test.iloc[:,1:19]
x_test = x_test.to_numpy()
x_test = x_test.T
y_test = df_test.iloc[:,19]
y_test = y_test.to_numpy()
y_test = y_test.reshape(y_test.shape[0],1)
y_test = y_test.T
print ("Number of training examples: m_train = " + str(m_train))
print ("Number of testing examples: m_test = " + str(m_test))
print ("train_set_x shape: " + str(x_train.shape))
print ("train_set_y shape: " + str(y_train.shape))
print ("test_set_x shape: " + str(x_test.shape))
print ("test_set_y shape: " + str(y_test.shape))
Вывод кода набора данных
Number of training examples: df_train = 713
Number of testing examples: df_test = 237
x_train shape: (18, 713)
y_train shape: (1, 713)
x_test shape: (18, 237)
y_test shape: (1, 237)
Код функции распространения
def propagate(w,b,X,Y) :
m = X.shape[1]
A = sigmoid((w.T * X) + b)
cost = (- 1 / m) * np.sum(np.dot(Y,np.log(A)) + np.dot((1 - Y), np.log(1 - A)))
dw = (1 / m) * np.dot((X,(A - Y)).T)
db = (1 / m) * np.sum(A - Y)
assert(dw.shape == w.shape)
assert(db.dtype == float)
cost = np.squeeze(cost)
assert(cost.shape == ())
grads = {"dw": dw,
"db": db}
return grads, cost
Функции оптимизации и модели
**def optimize**(w,b,X,Y,num_iterations,learning_rate,print_cost) :
costs = []
for i in range(num_iterations) :
# Cost and gradient calculation
grads, cost = propagate(w,b,X,Y)
# Retrieve derivatives from gradients
dw = grads['dw']
db = grads['db']
# Update w and b
w = w - learning_rate * dw
b = b - learning_rate * db
if i % 100 == 0:
costs.append(cost)
# Print the cost every 100 training iterations
if print_cost and i % 100 == 0:
print ("Cost after iteration %i: %f" %(i, cost))
params = {"w": w,
"b": b}
grads = {"dw": dw,
"db": db}
return params, grads, costs
**def model**(X_train, Y_train, X_test, Y_test, num_iterations = 2000, learning_rate = 0.5, print_cost = False) :
# initialize parameters with zero
w, b = initialize_with_zeros(X_train.shape[0])
# Gradient descent (≈ 1 line of code)
parameters, grads, costs = optimize(w,b,X_train,Y_train,num_iterations,learning_rate,print_cost)
# Retrieve parameters w and b from dictionary "parameters"
w = parameters["w"]
b = parameters["b"]
# Predict train/test set examples (≈ 2 lines of code)
Y_prediction_train = predict(w,b,X_train)
Y_prediction_test = predict(w,b,X_test)
# Print train/test Errors
print("train accuracy: {} %".format(100 - np.mean(abs(Y_prediction_train - Y_train)) * 100))
print("test accuracy: {} %".format(100 - np.mean(abs(Y_prediction_test - Y_test)) * 100))
d = {"costs": costs,
"Y_prediction_test": Y_prediction_test,
"Y_prediction_train" : Y_prediction_train,
"w" : w,
"b" : b,
"learning_rate" : learning_rate,
"num_iterations": num_iterations}
return d
Модель Функция выхода
Cost after iteration 0: 0.693147
train accuracy: -0.1402524544179613 %
test accuracy: 0.4219409282700326 %
Когда я запускаю код, я получаю ValueError: operands could not be broadcast together with shapes (1,713) (713,18)
вA = sigmoid((w.T * X) + b)
. Я довольно плохо знаком с нейронными сетями и использованием numpy, поэтому не могу понять проблему. Любая помощь будет очень признательна. Весь файл .ipynb, содержащий весь код, можно загрузить отсюда
Спасибо