teratail header banner
teratail header banner
質問するログイン新規登録

質問編集履歴

1

問題解決の糸口が見えてきましたが、未だに改善されません。

2019/01/26 02:35

投稿

JunyaKoga
JunyaKoga

スコア17

title CHANGED
File without changes
body CHANGED
@@ -1,31 +1,12 @@
1
- [GitHubの記事](https://github.com/kujirahand/book-mlearn-gyomu/blob/master/src/ch5/iris/tf-iris.py)を参考にTensorFlowでアヤメの分類問題をやっているのですが、恐らくデータ型のエラーがどうしても解消できません。
2
- コスト関数の最適化のとこでエラーが出ていますが、上の事と見合わせても、データ型的にどこが間違えているのかがわかりません。
1
+ ### <1/26追
3
- 解決方法がわる方是非ご教授くださると助かります。
2
+ 最下部内容ら進展があったので記事を更新します。
4
- 試行錯誤して色々書き換えると様々なエラー生じで、もしかしたら多く個所がおかしいせん
3
+ 問題るであろうグラフ作成部分と実行部分を抜粋ます(くつ変更す)
4
+ 実行部ではfor文でエポック数を増やしたいのですが、2周目からエラーが出るようです。実行部のfor文をfor i in range(1)とした場合はエラーは生じません。
5
+ **エラー内容は「sess.runにndarrayを入れるな。テンソルを入れてくれ」ということだと思いますが、何故、forの1周目でテンソルだったものが2周目からndarrayに変化してしまうのかがわかりません。**
5
6
 
6
- ### 書いたコード
7
+
7
8
  ```python
8
- from urllib.request import urlretrieve
9
- import pandas as pd
10
- import numpy as np
11
- import tensorflow as tf
12
- from sklearn.model_selection import train_test_split
13
-
14
- # データの呼び出し
15
- url = '上記記事のコードのURL'
16
- urlretrieve(url, 'iris.csv')
17
- df = pd.read_csv('iris.csv', encoding='utf-8')
18
-
19
- # データの準備
20
- names = sorted(set(df.Name.values))
21
- name2num = {w:i for i, w in enumerate(names)}
22
- df['label'] = df['Name'].map(name2num)
23
- X = df.iloc[:,:4].values
24
- y = df.label.values
25
- X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, stratify=y, random_state=0)
26
-
27
-
28
- # グラフの作成
9
+ グラフの作成
29
10
  g = tf.Graph()
30
11
  with g.as_default():
31
12
  tf.set_random_seed(123)
@@ -34,37 +15,38 @@
34
15
  tf_y = tf.placeholder(tf.int32, shape=(None), name='tf_y')
35
16
 
36
17
  oh_y = tf.one_hot(tf_y, 3, dtype=tf.float32, name='oh_y')
37
-
18
+
38
19
  w = tf.Variable(tf.random_normal((4, 3)), name='weight')
39
20
  b = tf.Variable(tf.zeros(3), name='bias')
40
21
 
41
22
  logits = tf.add(tf.matmul(tf_x, w), b, name='logits')
42
23
 
43
24
  prediction = {'probabilities': tf.nn.softmax(logits, name='probabilities'),
44
- 'labels': tf.cast(tf.argmax(logits,1), tf.int32)}
25
+ 'labels': tf.argmax(logits,1)}
45
26
 
46
- # cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(logits=logits, labels=oh_y), name='cost')
27
+ cost = tf.losses.softmax_cross_entropy(logits=logits, onehot_labels=oh_y)
47
- cost = -tf.reduce_sum(oh_y * tf.log(prediction['probabilities']))
28
+ # cost = -tf.reduce_sum(oh_y * tf.log(prediction['probabilities']))
48
29
  optimizer = tf.train.AdamOptimizer()
49
30
  train = optimizer.minimize(cost)
50
- correct_predictions = tf.equal(prediction['labels'], tf.cast(tf.argmax(oh_y, 1), tf.int32))
31
+ correct_predictions = tf.equal(prediction['labels'], tf.argmax(oh_y, 1))
32
+ # tf.reduce_meanの中身はfloatにしてあげないと小数点の計算できない
51
- accuracy = tf.reduce_mean(tf.cast(correct_predictions, tf.float32), name='accuracy')
33
+ accuracy = tf.reduce_mean(tf.cast(correct_predictions, tf.float32), name='accuracy')
52
34
  init = tf.global_variables_initializer()
53
-
54
-
35
+
55
- # 実行
36
+ 実行
56
37
  with tf.Session(graph=g) as sess:
57
38
  sess.run(init)
58
-
39
+ # ↓のfor文のrange(1)にすると、エラーが生じません。
59
- for step in range(300):
40
+ for step in range(2):
60
- _, cost, accuracy = sess.run([train, cost, accuracy], feed_dict={tf_x: X_train, tf_y: y_train})
41
+ _, cost= sess.run([train, cost], feed_dict={tf_x: X_train, tf_y: y_train})
61
42
  if (step + 1) % 10 == 0:
62
- print('Epoch%2d Cost:%.2f Accuracy:%.2f%%' %(step+1, cost, accuracy*100))
43
+ print('Epoch%2d Cost:%.2f' %(step+1, cost))
63
44
 
64
45
  print('Prediction Accuracy: %.2f' %(sess.run(accuracy, feed_dict={tf_x: X_test, tf_y: y_test}) * 100))
46
+
65
47
  ```
66
48
  ### 生じているエラー
67
- ```ここに言語を入力
49
+ ```
68
50
  ---------------------------------------------------------------------------
69
51
  TypeError Traceback (most recent call last)
70
52
  /usr/local/lib/python3.6/dist-packages/tensorflow/python/client/session.py in __init__(self, fetches, contraction_fn)
@@ -87,12 +69,12 @@
87
69
  During handling of the above exception, another exception occurred:
88
70
 
89
71
  TypeError Traceback (most recent call last)
90
- <ipython-input-1-c6d4748fd830> in <module>()
72
+ <ipython-input-134-171c87a28859> in <module>()
91
- 52
73
+ 3 # ↓のfor文のrange(1)にすると、エラーが生じません。
92
- 53 for step in range(300):
74
+ 4 for step in range(2):
93
- ---> 54 _, cost, accuracy = sess.run([train, cost, accuracy], feed_dict={tf_x: X_train, tf_y: y_train})
75
+ ----> 5 _, cost= sess.run([train, cost], feed_dict={tf_x: X_train, tf_y: y_train})
94
- 55 if (step + 1) % 10 == 0:
76
+ 6 if (step + 1) % 10 == 0:
95
- 56 print('Epoch%2d Cost:%.2f Accuracy:%.2f%%' %(step+1, cost, accuracy*100))
77
+ 7 print('Epoch%2d Cost:%.2f' %(step+1, cost))
96
78
 
97
79
  /usr/local/lib/python3.6/dist-packages/tensorflow/python/client/session.py in run(self, fetches, feed_dict, options, run_metadata)
98
80
  927 try:
@@ -150,6 +132,80 @@
150
132
  305 except ValueError as e:
151
133
  306 raise ValueError('Fetch argument %r cannot be interpreted as a '
152
134
 
135
+ TypeError: Fetch argument 5.690171 has invalid type <class 'numpy.float32'>, must be a string or Tensor. (Can not convert a float32 into a Tensor or Operation.)
136
+ ```
137
+
138
+
139
+
140
+ <以下、更新前の原文>
141
+ [GitHubの記事](https://github.com/kujirahand/book-mlearn-gyomu/blob/master/src/ch5/iris/tf-iris.py)を参考にTensorFlowでアヤメの分類問題をやっているのですが、恐らくデータ型のエラーがどうしても解消できません。
142
+ コスト関数の最適化のとこでエラーが出ていますが、上の記事と見合わせても、データ型的にどこが間違えているのかがわかりません。
143
+ 解決の方法がわかる方、是非ご教授くださると助かります。
144
+ 試行錯誤して色々書き換えると様々なエラーが生じるので、もしかしたら多くの個所がおかしいのかもしれません。
145
+
146
+ ### 書いたコード
147
+ ```python
148
+ from urllib.request import urlretrieve
149
+ import pandas as pd
150
+ import numpy as np
151
+ import tensorflow as tf
152
+ from sklearn.model_selection import train_test_split
153
+
154
+ # データの呼び出し
155
+ url = '上記記事のコードのURL'
156
+ urlretrieve(url, 'iris.csv')
157
+ df = pd.read_csv('iris.csv', encoding='utf-8')
158
+
159
+ # データの準備
160
+ names = sorted(set(df.Name.values))
161
+ name2num = {w:i for i, w in enumerate(names)}
162
+ df['label'] = df['Name'].map(name2num)
163
+ X = df.iloc[:,:4].values
164
+ y = df.label.values
165
+ X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, stratify=y, random_state=0)
166
+
167
+
168
+ # グラフの作成
169
+ g = tf.Graph()
170
+ with g.as_default():
171
+ tf.set_random_seed(123)
172
+
173
+ tf_x = tf.placeholder(tf.float32, shape=(None, 4), name='tf_x')
174
+ tf_y = tf.placeholder(tf.int32, shape=(None), name='tf_y')
175
+
176
+ oh_y = tf.one_hot(tf_y, 3, dtype=tf.float32, name='oh_y')
177
+
178
+ w = tf.Variable(tf.random_normal((4, 3)), name='weight')
179
+ b = tf.Variable(tf.zeros(3), name='bias')
180
+
181
+ logits = tf.add(tf.matmul(tf_x, w), b, name='logits')
182
+
183
+ prediction = {'probabilities': tf.nn.softmax(logits, name='probabilities'),
184
+ 'labels': tf.cast(tf.argmax(logits,1), tf.int32)}
185
+
186
+ # cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(logits=logits, labels=oh_y), name='cost')
187
+ cost = -tf.reduce_sum(oh_y * tf.log(prediction['probabilities']))
188
+ optimizer = tf.train.AdamOptimizer()
189
+ train = optimizer.minimize(cost)
190
+ correct_predictions = tf.equal(prediction['labels'], tf.cast(tf.argmax(oh_y, 1), tf.int32))
191
+ accuracy = tf.reduce_mean(tf.cast(correct_predictions, tf.float32), name='accuracy')
192
+ init = tf.global_variables_initializer()
193
+
194
+
195
+ # 実行
196
+ with tf.Session(graph=g) as sess:
197
+ sess.run(init)
198
+
199
+ for step in range(300):
200
+ _, cost, accuracy = sess.run([train, cost, accuracy], feed_dict={tf_x: X_train, tf_y: y_train})
201
+ if (step + 1) % 10 == 0:
202
+ print('Epoch%2d Cost:%.2f Accuracy:%.2f%%' %(step+1, cost, accuracy*100))
203
+
204
+ print('Prediction Accuracy: %.2f' %(sess.run(accuracy, feed_dict={tf_x: X_test, tf_y: y_test}) * 100))
205
+ ```
206
+ ### 生じているエラー(追記時に字数が足りなくなったので削りました)
207
+ ```ここに言語を入力
208
+ ---------------------------------------------------------------------------
153
209
  TypeError: Fetch argument 682.8205 has invalid type <class 'numpy.float32'>, must be a string or Tensor. (Can not convert a float32 into a Tensor or Operation.)
154
210
  ```
155
211