Skip to main content
 首页 » 编程设计

python之Tensorflow TypeError : 'Series' objects are mutable, 因此它们不能被散列

2025年02月15日25Free-Thinker

我正在尝试使用 Tensor Flow 构建简单的逻辑回归,但出现此错误:

TypeError: 'Series' objects are mutable, thus they cannot be hashed 

这是我的代码:

data = pd.read_csv(data_file,sep=";",names=header) 
... 
n = data.shape[0] 
n_training_set = int(.7*n) 
df_train = data[30:n_training_set] 
df_test = data[n_training_set:] 
 
LABEL_COLUMN = 'action' 
 
 
CONTINUOUS_COLUMNS = ['rsi','stochk','stochd'] 
CATEGORICAL_COLUMNS = [] 
 
def input_fn(df): 
  # Creates a dictionary mapping from each continuous feature column name (k) to 
  # the values of that column stored in a constant Tensor. 
  continuous_cols = {k: tf.constant(df[k].values) 
                     for k in CONTINUOUS_COLUMNS} 
  # Creates a dictionary mapping from each categorical feature column name (k) 
  # to the values of that column stored in a tf.SparseTensor. 
  categorical_cols = {k: tf.SparseTensor( 
      indices=[[i, 0] for i in range(df[k].size)], 
      values=df[k].values, 
      dense_shape=[df[k].size, 1]) 
                      for k in CATEGORICAL_COLUMNS} 
  # Merges the two dictionaries into one. 
  feature_cols = dict(continuous_cols.items() + categorical_cols.items()) 
  # Converts the label column into a constant Tensor. 
  label = tf.constant(df[LABEL_COLUMN].values) 
  # Returns the feature columns and the label. 
  return feature_cols, label 
 
 
def train_input_fn(): 
  return input_fn(df_train) 
 
def eval_input_fn(): 
  return input_fn(df_test) 
 
model_dir = tempfile.mkdtemp() 
 
CONTINUOUS_COLUMNS = ['rsi','stochk','stochd'] 
 
rsi = tf.contrib.layers.real_valued_column(df_train["rsi"]) 
stochk = tf.contrib.layers.real_valued_column(df_train["stochk"]) 
stochd = tf.contrib.layers.real_valued_column(df_train["stochd"]) 
 
### defining the model 
m = tf.contrib.learn.LinearClassifier(feature_columns=[ 
        rsi, 
        stochk, 
        stochd 
 
    ], 
  model_dir=model_dir) 
 
 
m.fit(input_fn=train_input_fn, steps=200) 

我该如何解决这个问题?

请您参考如下方法:

你的错误在于:

rsi = tf.contrib.layers.real_valued_column(df_train["rsi"]) 
stochk = tf.contrib.layers.real_valued_column(df_train["stochk"]) 
stochd = tf.contrib.layers.real_valued_column(df_train["stochd"]) 

在这里,您将 pandas 数据框中的一列作为第一个参数传递,但是第一个参数为 real_valued_column应该是列的名称。因此将上面的行替换为:

rsi = tf.contrib.layers.real_valued_column("rsi") 
stochk = tf.contrib.layers.real_valued_column("stochk") 
stochd = tf.contrib.layers.real_valued_column("stochd") 

应该成功。

另见 section教程。