gpt4 book ai didi

python - 值错误 : Weights for model sequential have not yet been created

转载 作者:行者123 更新时间:2023-12-05 03:41:30 27 4
gpt4 key购买 nike

我正在测试一个基本的神经网络模型。但在继续之前,我遇到了屏幕截图中显示的错误。

这是我的代码:

import numpy as np

# Training Data
x_train = np.array([[1.0,1.0]])
y_train = np.array([2.0])


for i in range(3,10000,2):
x_train = np.append(x_train,[[i,i]],axis = 0)
y_train = np.append(y_train,[i+i],axis = 0)


# Test Data
import numpy as np

x_test = np.array([[2.0,2.0]])
y_test = np.array([4.0])

for i in range(4,8000,4):
x_test = np.append(x_test,[[i,i]],axis = 0)
y_test = np.append(y_test,[i+i])

from tensorflow import keras
from keras.layers import Flatten # to flatten the input data
from keras.layers import Dense # for the hidden layer

# We'll follow sequential method i.e. one after the other(input layer ---> hidden layer---> output layer)

model = keras.Sequential()

# For input layer
model.add(Flatten(input_shape = x_train[0].shape)) # input layer

# For Hidden layer
model.add(Dense(2,activation = 'relu')) # '2' represents a no. of neurons

# For Output layer
model.add(Dense(1)) # By default, activation = 'linear'

# before training
bf_train = model.get_weights()
bf_train

错误是:

ValueError:模型序列的权重尚未创建。权重是在首次对输入调用模型或使用 input_shape 调用 build() 时创建的。

最佳答案

您不应混合使用 tf 2.x 和独立的 keras。您应该按如下方式导入

from tensorflow import keras    
from tensorflow.keras.layers import Flatten # to flatten the input data
from tensorflow.keras.layers import Dense # for the hidden layer

现在,运行代码,你会得到一些重量。

[array([[-0.43643105, -1.0268047 ],
[ 1.0003897 , 1.1105307 ]], dtype=float32),
array([0., 0.], dtype=float32),
array([[-0.19884515],
[-0.78100944]], dtype=float32),
array([0.], dtype=float32)]

关于python - 值错误 : Weights for model sequential have not yet been created,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67706092/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com