0
아래 코드는 CSV 파일의 데이터를 사용하여 신경망을 학습하려고합니다. CSV에서 데이터를 가져 와서 목록에 저장하고이 목록을 배열로 변환 한 다음 두 개의 배열을 x 및 y 값으로 사용하여 신경 네트워크를 학습합니다. 나는이 코드를 실행하면오류 : tensorflow를 사용하는 동안 닫힌 파일에 대한 I/O 작업
import numpy as np
import tensorflow as tf
import csv
from collections import defaultdict
columns = defaultdict(list) # each value in each column is appended to a list
# Declare list of features, we only have one real-valued feature
def model_fn(features, labels, mode):
with open('C:\\Users\\joe\\Documents\\EURUSD learn.txt') as f:
reader = csv.DictReader(f) # read rows into a dictionary format
for row in reader: # read a row as {column1: value1, column2: value2,...}
for (k,v) in row.items(): # go over each column name and value
columns[k].append(v) # append the value into the appropriate list
# based on column name k
openarray = np.asarray('<OPEN>')
closearray = np.asarray('<CLOSE>')
higharray = np.asarray('<HIGH>')
lowarray = np.asarray('<LOW>')
# Build a linear model and predict values
W = tf.get_variable("W", [1], dtype=tf.float64)
b = tf.get_variable("b", [1], dtype=tf.float64)
y = W*features['x'] + b
# Loss sub-graph
loss = tf.reduce_sum(tf.square(y - labels))
# Training sub-graph
global_step = tf.train.get_global_step()
optimizer = tf.train.GradientDescentOptimizer(0.01)
train = tf.group(optimizer.minimize(loss),
tf.assign_add(global_step, 1))
# EstimatorSpec connects subgraphs we built to the
# appropriate functionality.
return tf.estimator.EstimatorSpec(
mode=mode,
predictions=y,
loss=loss,
train_op=train)
with open('C:\\Users\\joe\\Documents\\EURUSD learn.txt') as f:
estimator = tf.estimator.Estimator(model_fn=model_fn)
# define our data sets
x_train = np.array(['openarray'])
y_train = np.array(['closearray'])
x_eval = np.array(['higharray'])
y_eval = np.array(['lowarray'])
input_fn = tf.estimator.inputs.numpy_input_fn(
{"x": x_train}, y_train, batch_size=4, num_epochs=None, shuffle=True)
train_input_fn = tf.estimator.inputs.numpy_input_fn(
{"x": x_train}, y_train, batch_size=4, num_epochs=1000, shuffle=False)
eval_input_fn = tf.estimator.inputs.numpy_input_fn(
{"x": x_eval}, y_eval, batch_size=4, num_epochs=1000, shuffle=False)
# train
estimator.train(input_fn=input_fn, steps=1000)
# Here we evaluate how well our model did.
train_metrics = estimator.evaluate(input_fn=train_input_fn)
eval_metrics = estimator.evaluate(input_fn=eval_input_fn)
print("train metrics: %r"% train_metrics)
print("eval metrics: %r"% eval_metrics)
, 나는 다음과 같은 오류 얻을 :이 오류를 보았다
WARNING:tensorflow:Using temporary folder as model directory: C:\Users\joe\AppData\Local\Temp\tmp3yj2dh4d
Traceback (most recent call last):
File "C:\Users\joe\AppData\Local\Programs\Python\Python35\stocks closing+opening.py", line 54, in <module>
estimator.train(input_fn=input_fn, steps=1000)
File "C:\Users\joe\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\estimator\estimator.py", line 302, in train
loss = self._train_model(input_fn, hooks, saving_listeners)
File "C:\Users\joe\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\estimator\estimator.py", line 711, in _train_model
features, labels, model_fn_lib.ModeKeys.TRAIN, self.config)
File "C:\Users\joe\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\estimator\estimator.py", line 694, in _call_model_fn
model_fn_results = self._model_fn(features=features, **kwargs)
File "C:\Users\joe\AppData\Local\Programs\Python\Python35\stocks closing+opening.py", line 14, in model_fn
for row in reader: # read a row as {column1: value1, column2: value2,...}
File "C:\Users\joe\AppData\Local\Programs\Python\Python35\lib\csv.py", line 109, in __next__
self.fieldnames
File "C:\Users\joe\AppData\Local\Programs\Python\Python35\lib\csv.py", line 96, in fieldnames
self._fieldnames = next(self.reader)
ValueError: I/O operation on closed file.
를, 것 같다 닫힌 파일을 실행하려고하지만 파일을 열었습니다. 이것은 임시 폴더를 모델 디렉토리로 사용하기 때문입니까? 함수 model_fn 당신이 문로를 사용하여 파일을 여는 당신이 그 파일을 가진 리더의 생성에