2017-06-28 10 views
0

私はテンソルフローの極端な初心者です。私は2列、高さ&のState of Charge(SoC)を含むCSVデータを使用して単純な線形回帰を行うことを任されました。浮動です。 CSVファイルでは、Heightが最初のcolで、SoCは2番目のcolです。私は、私は完全に私は、コードの「すべてのトレーニングデータをフィット」の部分を追加しなければならないものにと迷ってしまいましたSoCTensorflow:CSVデータを使用した単純な線形回帰

を予測すると仮定だ高さを使用して

。など、この一人として、私は他の線形回帰モデルを見てきましたし、そのコードは心の遠くなるような、次のとおりです。

with tf.Session() as sess: 
sess.run(init) 
for epoch in range(training_epochs): 
    sess.run(training_step,feed_dict={X:train_x,Y:train_y}) 
    cost_history = np.append(cost_history,sess.run(cost,feed_dict={X: train_x,Y: train_y})) 

#calculate mean square error 
pred_y = sess.run(y_, feed_dict={X: test_x}) 
mse = tf.reduce_mean(tf.square(pred_y - test_y)) 
print("MSE: %.4f" % sess.run(mse)) 

#plot cost 
plt.plot(range(len(cost_history)),cost_history) 
plt.axis([0,training_epochs,0,np.max(cost_history)]) 
plt.show() 

fig, ax = plt.subplots() 
ax.scatter(test_y, pred_y) 
ax.plot([test_y.min(), test_y.max()], [test_y.min(), test_y.max()], 'k--', lw=3) 
ax.set_xlabel('Measured') 
ax.set_ylabel('Predicted') 
plt.show() 

私はちょうどこのガイドを使用してエラーなしで私のCSVファイルからデータを取得することができました:

TensorFlow: Reading and using data from CSV file

全コード:

import tensorflow as tf 
import pandas as pd 
import numpy as np 
import matplotlib.pyplot as plt 
%matplotlib inline 
rng = np.random 

from numpy import genfromtxt 
from sklearn.datasets import load_boston 

# Parameters 
learning_rate = 0.01 
training_epochs = 1000 
display_step = 50 
n_samples = 221 

X = tf.placeholder("float") # create symbolic variables 
Y = tf.placeholder("float") 

filename_queue = tf.train.string_input_producer(["battdata.csv"],shuffle=False) 

reader = tf.TextLineReader(skip_header_lines=1) 
key, value = reader.read(filename_queue) 

# Default values, in case of empty columns. Also specifies the type of the 
# decoded result. 
record_defaults = [[1.], [1.]] 
col1, col2= tf.decode_csv(
    value, record_defaults=record_defaults) 
features = tf.stack([col1]) 

# Set model weights 
W = tf.Variable(rng.randn(), name="weight") 
b = tf.Variable(rng.randn(), name="bias") 

# Construct a linear model 
pred = tf.add(tf.multiply(col1, W), b) # XW + b <- y = mx + b where W is gradient, b is intercept 

# Mean squared error 
cost = tf.reduce_sum(tf.pow(pred-col2, 2))/(2*n_samples) 

# Gradient descent 
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost) 

# Initializing the variables 
init = tf.global_variables_initializer() 

with tf.Session() as sess: 
    # Start populating the filename queue. 
    coord = tf.train.Coordinator() 
    threads = tf.train.start_queue_runners(coord=coord) 
    sess.run(init) 

    # Fit all training data 
    for epoch in range(training_epochs): 
     _, cost_value = sess.run([optimizer,cost]) 
     for (x, y) in zip(col2, col1): 
       sess.run(optimizer, feed_dict={X: x, Y: y}) 

      #Display logs per epoch step 
     if (epoch+1) % display_step == 0: 
      c = sess.run(cost, feed_dict={X: col2, Y:col1}) 
      print("Epoch:", '%04d' % (epoch+1), "cost=", "{:.9f}".format(c), \ 
       "W=", sess.run(W), "b=", sess.run(b)) 

     print("Optimization Finished!") 
     training_cost = sess.run(cost, feed_dict={X: col2, Y: col1}) 
     print ("Training cost=", training_cost, "W=", sess.run(W), "b=", sess.run(b), '\n') 

     #Graphic display 
     plt.plot(train_X, train_Y, 'ro', label='Original data') 
     plt.plot(train_X, sess.run(W) * col2 + sess.run(b), label='Fitted line') 
     plt.legend() 
     plt.show() 

    coord.request_stop() 
    coord.join(threads) 

エラー:

INFO:tensorflow:Error reported to Coordinator: , Attempted to use a closed Session. --------------------------------------------------------------------------- TypeError Traceback (most recent call last) in() 8 for epoch in range(training_epochs): 9 _, cost_value = sess.run([optimizer,cost]) ---> 10 for (x, y) in zip(*col1, col2): 11 sess.run(optimizer, feed_dict={X: x, Y: y}) 12

C:\Users\Shiina\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\framework\ops.py in iter(self) 514 TypeError: when invoked. 515 """ --> 516 raise TypeError("'Tensor' object is not iterable.") 517 518 def bool(self):

TypeError: 'Tensor' object is not iterable.

答えて

1

for (x, y) in zip(col2, col1)のテンソルで反復しようとしているため、エラーが発生しています。このコードの他の問題は、入力パイプラインキューの設定があり、feed_dict {}を通じてフィードインしようとしていることです。間違っています。トレーニングパートは次のようになります。

with tf.Session() as sess: 
# Start populating the filename queue. 
coord = tf.train.Coordinator() 
threads = tf.train.start_queue_runners(coord=coord) 
sess.run(init) 

# Fit all training data 
for epoch in range(training_epochs): 
    _, cost_value = sess.run([optimizer,cost]) 

     #Display logs per epoch step 
    if (epoch+1) % display_step == 0: 
     c = sess.run(cost) 
     print("Epoch:", '%04d' % (epoch+1), "cost=", "{:.9f}".format(c), \ 
      "W=", sess.run(W), "b=", sess.run(b)) 

    print("Optimization Finished!") 
    training_cost = sess.run(cost) 
    print ("Training cost=", training_cost, "W=", sess.run(W), "b=", sess.run(b), '\n') 

#Plot data after completing training 
train_X = [] 
train_Y = [] 
for i in range(input_size): #Your input data size to loop through once 
    X, Y = sess.run([col1, pred]) # Call pred, to get the prediction with the updated weights 
    train_X.append(X) 
    train_Y.append(y) 
    #Graphic display 
plt.plot(train_X, train_Y, 'ro', label='Original data') 
plt.legend() 
plt.show() 

coord.request_stop() 
coord.join(threads) 
+0

こんにちは!ご回答有難うございます。 あなたのコードを使って、グラフのx軸は値0-1.0からですが、私が使用しているcsvデータはX軸が0-100.0であるはずです:x他に何かしましたか?違う? – Tix

+0

col1の値を取得するtrain_Xの値を確認し、その値が自分のcsvデータと同じかどうかを確認します。 –

+0

train_Xの値を確認しましたが、私のCSVファイルにあるデータには対応していません。 – Tix

関連する問題