【问题标题】:ValueError: could not convert string to float: 'W'ValueError:无法将字符串转换为浮点数:'W'
【发布时间】:2021-02-03 20:56:25
【问题描述】:

我一直在尝试使用 pandas 乳腺癌获得一个浅层神经网络,但我一直遇到这个错误,如果有人能告诉我真正的错误以及如何解决它,我将不胜感激。

File "D:\Users\USUARIO\Desktop\una carpeta para los oasda proyectos\Ex_Files_Python_EssT\Exercise Files\basic_hands_on.py", line 55, in predict
    np.array(WT, dtype=np.float32)
ValueError: could not convert string to float: 'W' 

我试图将字典中 W 的值转换为 float32,因为我需要它来实际处理预测函数上的方程,但我一直认为“W”的类型是一个字符串,尽管 print([W]) 给我一个矩阵。

为了上下文,这是我的代码

import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.datasets import load_breast_cancer

def initialiseNetwork(num_features):
  W = np.zeros((num_features, 1))
  b = 0
  parameters = {"W": W, "b": b}
  return parameters
def sigmoid(z):
  a = 1/(1 + np.exp(-z))
  return a
def forwardPropagation(X, parameters):
  W = parameters["W"]
  b =  parameters["b"]
  Z = np.dot(W.T,X) + b
  A = sigmoid(Z)
  return A

def cost(A, Y, num_samples):
  cost = -1/num_samples *np.sum(Y*np.log(A) + (1-Y)*(np.log(1-A)))
  return cost
def backPropagration(X, Y, A, num_samples):

  dZ = A - Y

  dW = (np.dot(X,dZ.T))/num_samples

  db = np.sum(dZ)/num_samples

  return dW, db
def updateParameters(parameters, dW, db, learning_rate):

  W = parameters["W"] - (learning_rate * dW)

  b = parameters["b"] - (learning_rate * db)

  return {"W": W, "b": b}

def model(X, Y, num_iter, learning_rate):
  num_features = X.shape[0]
  num_samples = (X.shape[1])
  print(num_samples)
  parameters = initialiseNetwork(num_features)
  for i in range(num_iter):
    A = forwardPropagation(X, parameters)
    if(i%100 == 0):
      print("cost after {} iteration: {}".format(i, cost(A, Y, num_samples)))
    dW, db = backPropagration(X, Y, A, num_samples)
    parameters = updateParameters(parameters, dW, db, learning_rate)
  return parameters
def predict(W, b, X):
  WT = np.transpose(["W"])
  np.array(WT, dtype=np.float32)
  np.array(WT,dtype=float)
  Z = np.dot(WT,X) + b
  Y = np.array([1 if y > 0.5 else 0 for y in sigmoid(Z[0])]).reshape(1,len(Z[0]))
  return Y
(X_cancer, y_cancer) = load_breast_cancer(return_X_y = True)
X_train, X_test, y_train, y_test = train_test_split(X_cancer, y_cancer,
                                                   random_state = 25)
def normalize(data):
  col_max = np.max(data, axis = 0)
  col_min = np.min(data, axis = 0)
  return np.divide(data - col_min, col_max - col_min)
X_train_n = normalize(X_train)
X_test_n = normalize(X_test)
X_trainT = X_train_n.T
X_testT = X_test_n.T
y_trainT = y_train.reshape(1, (X_trainT.shape[1]))
y_testT = y_test.reshape(1, (X_testT.shape[1]))
parameters = model(X_trainT, y_trainT, 4000, 0.75)
print(parameters)
print(X_trainT)
yPredTrain = predict(['W'], ['b'], X_trainT)   # pass weigths and bias from parameters dictionary and X_trainT as input to the function
yPredTest = predict(['W'], ['b'], X_testT)  # pass the same parameters but X_testT as input data
accuracy_train = 100 - np.mean(np.abs(yPredTrain - y_trainT)) * 100
accuracy_test = 100 - np.mean(np.abs(yPredTest - y_testT)) * 100
print("train accuracy: {} %".format(accuracy_train))
print("test accuracy: {} %".format(accuracy_test))
with open("Output.txt", "w") as text_file:
  text_file.write("train= %f\n" % accuracy_train)
  text_file.write("test= %f" % accuracy_test)```

【问题讨论】:

    标签: python pandas numpy neural-network


    【解决方案1】:

    我正要骂你没有告诉我们问题出在哪里。但是后来我碰巧将错误消息与

    匹配
    def predict(W, b, X):
       WT = np.transpose(["W"])
       np.array(WT, dtype=np.float32)
       ...
    

    当然会产生这个错误。带有字符“W”的数组肯定不能转成浮点数。

    您在很多地方使用predict(['W'],但这不是其中之一。

    【讨论】:

      【解决方案2】:

      这似乎是问题发生的地方:

      WT = np.transpose(["W"])
      np.array(WT, dtype=np.float32)
      

      这将创建一个包含"W" 的数组。不是变量W,而是文字字符"W"。我想你的意思是:

      WT = np.transpose([W])
      

      同样,当您调用predict() 时,我假设您想传入parameters["W"] 而不是"W"。请记住,"W" 只是一个字符,它与名为 W 的变量不同

      【讨论】:

      • 谢谢,我的问题是我没有正确调用字典。我忘了把像“字典名[“W”]”。
      【解决方案3】:

      您的数据集有一个值为“W”的列。 您可以通过以下代码删除或删除该列:

      dataset_name = dataset_name.drop(columns=["column_name"],axis = 1)

      【讨论】:

      • 这并不能真正解决手头的问题..
      猜你喜欢
      • 1970-01-01
      • 2019-03-23
      • 2018-06-13
      • 2013-05-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-04
      相关资源
      最近更新 更多