运行自定义神经网络代码遇TypeError:NoneType与float无法执行乘法运算
首先,先解释你遇到的错误含义:
TypeError: unsupported operand type(s) for *: 'NoneType' and 'float'
这个错误的核心意思是:你的代码中有一个变量的值是None(空值),但你尝试将它和一个浮点数执行乘法运算——Python不支持这种操作,所以抛出了这个类型错误。
为什么修改代码后出现这个问题?
你之前使用单参数的propup方法时没有报错,是因为那个版本的代码完全没用到input_history这个变量;但修改后的代码新增了v_history参数,并且在propup里执行了numpy.dot(v_history, self.B),而v_history对应的是类实例的self.input_history。
看你的类初始化代码:
def __init__( self, input=None, input_history=None, n_visible=7, n_hidden=500, delay=6, A=None, B=None, W=None, hbias=None, vbias=None, numpy_rng=None): # ... 其他初始化代码 self.input = input self.input_history = input_history # ...
input_history的默认值是None,如果你在创建这个类的实例时,没有传入有效的input_history数据,那么self.input_history就会保持None状态。当后续代码调用propup(比如sample_h_given_v方法内部,你没贴出这个方法,但从调用逻辑能推断)时,会把None传入v_history参数,执行numpy.dot(None, self.B)时,底层会尝试对None和数组元素做乘法,自然触发了这个错误。
另外,你的get_cost_updates方法里还有一个明显的参数错误:
self.vbias += lr * numpy.mean(self.input - nv_samples, self.input_history, axis=0)
numpy.mean的第二个参数应该是计算均值的轴(axis)或者其他可选参数,你这里错误地传入了self.input_history,如果它是None,也会引发额外的参数错误,需要修正。
解决方案
确保
input_history被正确初始化- 如果你创建类实例时,
input_history是必填数据,那么去掉它的默认None值,强制传入符合维度要求的数据:input_history的形状需要匹配(样本数量, n_visible * delay),这样才能和self.B(形状(n_visible*delay, n_hidden))执行矩阵乘法。 - 如果需要默认值,不要用
None,而是生成一个符合维度的初始数组,比如:if input_history is None: # 假设input有样本维度,生成对应形状的全零数组 input_history = np.zeros((input.shape[0], n_visible * delay))
- 如果你创建类实例时,
修复
numpy.mean的参数错误
把get_cost_updates里的那行代码改成:self.vbias += lr * numpy.mean(self.input - nv_samples, axis=0)检查
sample_h_given_v方法
确认这个方法内部调用propup时,传入的v_history一定是有效的数值数组,而不是None。如果有必要,可以在方法开头加一个判断:def sample_h_given_v(self, vis, v_history): if v_history is None: raise ValueError("v_history cannot be None!") # 后续逻辑 return self.propup(vis, v_history)
内容的提问来源于stack exchange,提问作者V.O Vian

