这不是我的代码,因为这是显示问题的行:
model.fit(trainX,trainY,batch_size = 2,epochs = 200,verbose = 2)
(正如我现在想的那样,此代码很有可能使用旧版的TF,因为“ epochs”被写为“ nb_epoch”)。
代码的最新更新来自:2017年1月11日!
我已经尝试了互联网上的所有内容(还不是很多),包括在tensorflow / keras的源代码中寻找一些提示。为了清楚起见,我在代码中没有一个名为“ batch_index”的变量。
到目前为止,我已经查看了TF的不同版本(tensorflow / tensorflow / python / keras / engine / training_arrays.py)。似乎所有这些内容都来自2018年的版权,但有些以函数fit_loop开头,而其他的则以model_iteration(可能是fit_loop的更新)开头。
因此,此“ batch_index”变量只能在第一个函数中看到。
我想知道我是否朝着正确的方向前进?!
显示代码没有意义,因为,正如我所解释的那样,代码内部没有这样的变量。
但是,这是函数“ stock_prediction”的一些代码,该代码给出错误:
def stock_prediction():
# Collect data points from csv
dataset = []
with open(FILE_NAME) as f:
for n, line in enumerate(f):
if n != 0:
dataset.append(float(line.split(',')[1]))
dataset = np.array(dataset)
# Create dataset matrix (X=t and Y=t+1)
def create_dataset(dataset):
dataX = [dataset[n+1] for n in range(len(dataset)-2)]
return np.array(dataX), dataset[2:]
trainX, trainY = create_dataset(dataset)
# Create and fit Multilinear Perceptron model
model = Sequential()
model.add(Dense(8, input_dim=1, activation='relu'))
model.add(Dense(1))
model.compile(loss='mean_squared_error', optimizer='adam')
model.fit(trainX, trainY, nb_epoch=200, batch_size=2, verbose=2)
# Our prediction for tomorrow
prediction = model.predict(np.array([dataset[0]]))
result = 'The price will move from %s to %s' % (dataset[0], prediction[0][0])
return result
---------------------------------------------------------------------------
UnboundLocalError Traceback (most recent call last)
<ipython-input-19-3dde95909d6e> in <module>
14
15 # We have our file so we create the neural net and get the prediction
---> 16 print(stock_prediction())
17
18 # We are done so we delete the csv file
<ipython-input-18-8bbf4f61c738> in stock_prediction()
23 model.add(Dense(1))
24 model.compile(loss='mean_squared_error', optimizer='adam')
---> 25 model.fit(trainX, trainY, batch_size=1, epochs=200, verbose=2)
26
27 # Our prediction for tomorrow
~\Anaconda3\lib\site-packages\keras\engine\training.py in fit(self, x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, initial_epoch, steps_per_epoch, validation_steps, validation_freq, max_queue_size, workers, use_multiprocessing, **kwargs)
1176 steps_per_epoch=steps_per_epoch,
1177 validation_steps=validation_steps,
-> 1178 validation_freq=validation_freq)
1179
1180 def evaluate(self,
~\Anaconda3\lib\site-packages\keras\engine\training_arrays.py in fit_loop(model, fit_function, fit_inputs, out_labels, batch_size, epochs, verbose, callbacks, val_function, val_inputs, shuffle, callback_metrics, initial_epoch, steps_per_epoch, validation_steps, validation_freq)
211 break
212
--> 213 if batch_index == len(batches) - 1: # Last batch.
214 if do_validation and should_run_validation(validation_freq, epoch):
215 val_outs = test_loop(model, val_function, val_inputs,
UnboundLocalError: local variable 'batch_index' referenced before assignment
一些澄清:
我试图查看我的tf / keras版本,就是这样:
from tensorflow.python import keras
print(keras.__version__)
import keras
print(keras.__version__)
import tensorflow
print(tensorflow.__version__)
2.2.4-tf
2.2.5
1.14.0
为什么keras显示不同的版本?
答案 0 :(得分:3)
package com.course.kafkaproducer;
import com.course.kafkaproducer.producer.HelloKafkaProducer;
import com.course.kafkaproducer.producer.KafakKeyProducer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
//@EnableScheduling
public class KafkaProducerApplication implements CommandLineRunner {
@Autowired
private KafakKeyProducer producer;
public static void main(String[] args) {
SpringApplication.run(KafkaProducerApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
for (int i = 0; i < 30; i++) {
var key = "key-" + (i % 4);
var data = "data " + i + " with key " + key;
producer.send(key, data);
}
}
}
问题的原因是批次列表为空! UnboundLocalError: local variable 'batch_index' referenced before assignment
之所以空白,是因为用于训练数据的样本数量太小,无法除以batch_size
您应该检查数据,样本数量或 您应该将batch_size减小到一个点,以使您可以将样本数量除以批量大小并得出真实结果。
答案 1 :(得分:1)
我必须导入正确的库(Tensorflow而不是直接导入Keras):
from tensorflow.python import keras.models.Sequential
from tensorflow.python import keras.layers.Dense
from tensorflow.python.keras.layers import Input, Dense
from tensorflow.python.keras.models import Sequential
显然,这与Keras的不同版本有关。
答案 2 :(得分:0)
我检查了training_arrays.py
(here)中出现错误的函数,并且正如我所看到的,我认为问题可能出在这些语句中(来自第177-205行) :
batches = make_batches(num_train_samples, batch_size)
for batch_index, (batch_start, batch_end) in enumerate(batches): # the problem is here
# do stuff
...
if batch_index == len(batches) - 1:
# do stuff
...
如果批次是一个空列表,则可能会出现此错误。可能是您的训练集有问题吗?
答案 3 :(得分:0)
此错误是因为培训数据为空。无论您是直接从keras导入还是从tensorflow导入,如果不传递正确的数据都会出现错误,错误消息可能因导入或版本而异。还要确保您正在传递数据中的几条记录。如果您从tensorflow导入Keras并使用该错误,将是
”提高ValueError(“空训练数据”。) ValueError:空的训练数据。“
如果直接,则该消息将是有问题的错误消息。