質問編集履歴

1

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

2019/01/26 02:35

投稿

JunyaKoga
JunyaKoga

スコア17

test CHANGED
File without changes
test CHANGED
@@ -1,3 +1,283 @@
1
+ ### <1/26追記>
2
+
3
+ 最下部の内容から進展があったので、記事を更新します。
4
+
5
+ 問題があるであろう、グラフ作成の部分と実行部分を抜粋します(いくつか変更してます)。
6
+
7
+ 実行部ではfor文でエポック数を増やしたいのですが、2周目からエラーが出るようです。実行部のfor文をfor i in range(1)とした場合はエラーは生じません。
8
+
9
+ **エラー内容は「sess.runにndarrayを入れるな。テンソルを入れてくれ」ということだと思いますが、何故、forの1周目でテンソルだったものが2周目からndarrayに変化してしまうのかがわかりません。**
10
+
11
+
12
+
13
+
14
+
15
+ ```python
16
+
17
+ グラフの作成
18
+
19
+ g = tf.Graph()
20
+
21
+ with g.as_default():
22
+
23
+ tf.set_random_seed(123)
24
+
25
+
26
+
27
+ tf_x = tf.placeholder(tf.float32, shape=(None, 4), name='tf_x')
28
+
29
+ tf_y = tf.placeholder(tf.int32, shape=(None), name='tf_y')
30
+
31
+
32
+
33
+ oh_y = tf.one_hot(tf_y, 3, dtype=tf.float32, name='oh_y')
34
+
35
+
36
+
37
+ w = tf.Variable(tf.random_normal((4, 3)), name='weight')
38
+
39
+ b = tf.Variable(tf.zeros(3), name='bias')
40
+
41
+
42
+
43
+ logits = tf.add(tf.matmul(tf_x, w), b, name='logits')
44
+
45
+
46
+
47
+ prediction = {'probabilities': tf.nn.softmax(logits, name='probabilities'),
48
+
49
+ 'labels': tf.argmax(logits,1)}
50
+
51
+
52
+
53
+ cost = tf.losses.softmax_cross_entropy(logits=logits, onehot_labels=oh_y)
54
+
55
+ # cost = -tf.reduce_sum(oh_y * tf.log(prediction['probabilities']))
56
+
57
+ optimizer = tf.train.AdamOptimizer()
58
+
59
+ train = optimizer.minimize(cost)
60
+
61
+ correct_predictions = tf.equal(prediction['labels'], tf.argmax(oh_y, 1))
62
+
63
+ # tf.reduce_meanの中身はfloatにしてあげないと小数点の計算できない
64
+
65
+ accuracy = tf.reduce_mean(tf.cast(correct_predictions, tf.float32), name='accuracy')
66
+
67
+ init = tf.global_variables_initializer()
68
+
69
+
70
+
71
+ 実行
72
+
73
+ with tf.Session(graph=g) as sess:
74
+
75
+ sess.run(init)
76
+
77
+ # ↓のfor文のrange(1)にすると、エラーが生じません。
78
+
79
+ for step in range(2):
80
+
81
+ _, cost= sess.run([train, cost], feed_dict={tf_x: X_train, tf_y: y_train})
82
+
83
+ if (step + 1) % 10 == 0:
84
+
85
+ print('Epoch%2d Cost:%.2f' %(step+1, cost))
86
+
87
+
88
+
89
+ print('Prediction Accuracy: %.2f' %(sess.run(accuracy, feed_dict={tf_x: X_test, tf_y: y_test}) * 100))
90
+
91
+
92
+
93
+ ```
94
+
95
+ ### 生じているエラー
96
+
97
+ ```
98
+
99
+ ---------------------------------------------------------------------------
100
+
101
+ TypeError Traceback (most recent call last)
102
+
103
+ /usr/local/lib/python3.6/dist-packages/tensorflow/python/client/session.py in __init__(self, fetches, contraction_fn)
104
+
105
+ 299 self._unique_fetches.append(ops.get_default_graph().as_graph_element(
106
+
107
+ --> 300 fetch, allow_tensor=True, allow_operation=True))
108
+
109
+ 301 except TypeError as e:
110
+
111
+
112
+
113
+ /usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/ops.py in as_graph_element(self, obj, allow_tensor, allow_operation)
114
+
115
+ 3489 with self._lock:
116
+
117
+ -> 3490 return self._as_graph_element_locked(obj, allow_tensor, allow_operation)
118
+
119
+ 3491
120
+
121
+
122
+
123
+ /usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/ops.py in _as_graph_element_locked(self, obj, allow_tensor, allow_operation)
124
+
125
+ 3578 raise TypeError("Can not convert a %s into a %s." % (type(obj).__name__,
126
+
127
+ -> 3579 types_str))
128
+
129
+ 3580
130
+
131
+
132
+
133
+ TypeError: Can not convert a float32 into a Tensor or Operation.
134
+
135
+
136
+
137
+ During handling of the above exception, another exception occurred:
138
+
139
+
140
+
141
+ TypeError Traceback (most recent call last)
142
+
143
+ <ipython-input-134-171c87a28859> in <module>()
144
+
145
+ 3 # ↓のfor文のrange(1)にすると、エラーが生じません。
146
+
147
+ 4 for step in range(2):
148
+
149
+ ----> 5 _, cost= sess.run([train, cost], feed_dict={tf_x: X_train, tf_y: y_train})
150
+
151
+ 6 if (step + 1) % 10 == 0:
152
+
153
+ 7 print('Epoch%2d Cost:%.2f' %(step+1, cost))
154
+
155
+
156
+
157
+ /usr/local/lib/python3.6/dist-packages/tensorflow/python/client/session.py in run(self, fetches, feed_dict, options, run_metadata)
158
+
159
+ 927 try:
160
+
161
+ 928 result = self._run(None, fetches, feed_dict, options_ptr,
162
+
163
+ --> 929 run_metadata_ptr)
164
+
165
+ 930 if run_metadata:
166
+
167
+ 931 proto_data = tf_session.TF_GetBuffer(run_metadata_ptr)
168
+
169
+
170
+
171
+ /usr/local/lib/python3.6/dist-packages/tensorflow/python/client/session.py in _run(self, handle, fetches, feed_dict, options, run_metadata)
172
+
173
+ 1135 # Create a fetch handler to take care of the structure of fetches.
174
+
175
+ 1136 fetch_handler = _FetchHandler(
176
+
177
+ -> 1137 self._graph, fetches, feed_dict_tensor, feed_handles=feed_handles)
178
+
179
+ 1138
180
+
181
+ 1139 # Run request and get response.
182
+
183
+
184
+
185
+ /usr/local/lib/python3.6/dist-packages/tensorflow/python/client/session.py in __init__(self, graph, fetches, feeds, feed_handles)
186
+
187
+ 469 """
188
+
189
+ 470 with graph.as_default():
190
+
191
+ --> 471 self._fetch_mapper = _FetchMapper.for_fetch(fetches)
192
+
193
+ 472 self._fetches = []
194
+
195
+ 473 self._targets = []
196
+
197
+
198
+
199
+ /usr/local/lib/python3.6/dist-packages/tensorflow/python/client/session.py in for_fetch(fetch)
200
+
201
+ 259 elif isinstance(fetch, (list, tuple)):
202
+
203
+ 260 # NOTE(touts): This is also the code path for namedtuples.
204
+
205
+ --> 261 return _ListFetchMapper(fetch)
206
+
207
+ 262 elif isinstance(fetch, collections.Mapping):
208
+
209
+ 263 return _DictFetchMapper(fetch)
210
+
211
+
212
+
213
+ /usr/local/lib/python3.6/dist-packages/tensorflow/python/client/session.py in __init__(self, fetches)
214
+
215
+ 368 """
216
+
217
+ 369 self._fetch_type = type(fetches)
218
+
219
+ --> 370 self._mappers = [_FetchMapper.for_fetch(fetch) for fetch in fetches]
220
+
221
+ 371 self._unique_fetches, self._value_indices = _uniquify_fetches(self._mappers)
222
+
223
+ 372
224
+
225
+
226
+
227
+ /usr/local/lib/python3.6/dist-packages/tensorflow/python/client/session.py in <listcomp>(.0)
228
+
229
+ 368 """
230
+
231
+ 369 self._fetch_type = type(fetches)
232
+
233
+ --> 370 self._mappers = [_FetchMapper.for_fetch(fetch) for fetch in fetches]
234
+
235
+ 371 self._unique_fetches, self._value_indices = _uniquify_fetches(self._mappers)
236
+
237
+ 372
238
+
239
+
240
+
241
+ /usr/local/lib/python3.6/dist-packages/tensorflow/python/client/session.py in for_fetch(fetch)
242
+
243
+ 269 if isinstance(fetch, tensor_type):
244
+
245
+ 270 fetches, contraction_fn = fetch_fn(fetch)
246
+
247
+ --> 271 return _ElementFetchMapper(fetches, contraction_fn)
248
+
249
+ 272 # Did not find anything.
250
+
251
+ 273 raise TypeError('Fetch argument %r has invalid type %r' % (fetch,
252
+
253
+
254
+
255
+ /usr/local/lib/python3.6/dist-packages/tensorflow/python/client/session.py in __init__(self, fetches, contraction_fn)
256
+
257
+ 302 raise TypeError('Fetch argument %r has invalid type %r, '
258
+
259
+ 303 'must be a string or Tensor. (%s)' %
260
+
261
+ --> 304 (fetch, type(fetch), str(e)))
262
+
263
+ 305 except ValueError as e:
264
+
265
+ 306 raise ValueError('Fetch argument %r cannot be interpreted as a '
266
+
267
+
268
+
269
+ 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.)
270
+
271
+ ```
272
+
273
+
274
+
275
+
276
+
277
+
278
+
279
+ <以下、更新前の原文>
280
+
1
281
  [GitHubの記事](https://github.com/kujirahand/book-mlearn-gyomu/blob/master/src/ch5/iris/tf-iris.py)を参考にTensorFlowでアヤメの分類問題をやっているのですが、恐らくデータ型のエラーがどうしても解消できません。
2
282
 
3
283
  コスト関数の最適化のとこでエラーが出ていますが、上の記事と見合わせても、データ型的にどこが間違えているのかがわかりません。
@@ -128,180 +408,12 @@
128
408
 
129
409
  ```
130
410
 
131
- ### 生じているエラー
411
+ ### 生じているエラー(追記時に字数が足りなくなったので削りました)
132
412
 
133
413
  ```ここに言語を入力
134
414
 
135
415
  ---------------------------------------------------------------------------
136
416
 
137
- TypeError Traceback (most recent call last)
138
-
139
- /usr/local/lib/python3.6/dist-packages/tensorflow/python/client/session.py in __init__(self, fetches, contraction_fn)
140
-
141
- 299 self._unique_fetches.append(ops.get_default_graph().as_graph_element(
142
-
143
- --> 300 fetch, allow_tensor=True, allow_operation=True))
144
-
145
- 301 except TypeError as e:
146
-
147
-
148
-
149
- /usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/ops.py in as_graph_element(self, obj, allow_tensor, allow_operation)
150
-
151
- 3489 with self._lock:
152
-
153
- -> 3490 return self._as_graph_element_locked(obj, allow_tensor, allow_operation)
154
-
155
- 3491
156
-
157
-
158
-
159
- /usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/ops.py in _as_graph_element_locked(self, obj, allow_tensor, allow_operation)
160
-
161
- 3578 raise TypeError("Can not convert a %s into a %s." % (type(obj).__name__,
162
-
163
- -> 3579 types_str))
164
-
165
- 3580
166
-
167
-
168
-
169
- TypeError: Can not convert a float32 into a Tensor or Operation.
170
-
171
-
172
-
173
- During handling of the above exception, another exception occurred:
174
-
175
-
176
-
177
- TypeError Traceback (most recent call last)
178
-
179
- <ipython-input-1-c6d4748fd830> in <module>()
180
-
181
- 52
182
-
183
- 53 for step in range(300):
184
-
185
- ---> 54 _, cost, accuracy = sess.run([train, cost, accuracy], feed_dict={tf_x: X_train, tf_y: y_train})
186
-
187
- 55 if (step + 1) % 10 == 0:
188
-
189
- 56 print('Epoch%2d Cost:%.2f Accuracy:%.2f%%' %(step+1, cost, accuracy*100))
190
-
191
-
192
-
193
- /usr/local/lib/python3.6/dist-packages/tensorflow/python/client/session.py in run(self, fetches, feed_dict, options, run_metadata)
194
-
195
- 927 try:
196
-
197
- 928 result = self._run(None, fetches, feed_dict, options_ptr,
198
-
199
- --> 929 run_metadata_ptr)
200
-
201
- 930 if run_metadata:
202
-
203
- 931 proto_data = tf_session.TF_GetBuffer(run_metadata_ptr)
204
-
205
-
206
-
207
- /usr/local/lib/python3.6/dist-packages/tensorflow/python/client/session.py in _run(self, handle, fetches, feed_dict, options, run_metadata)
208
-
209
- 1135 # Create a fetch handler to take care of the structure of fetches.
210
-
211
- 1136 fetch_handler = _FetchHandler(
212
-
213
- -> 1137 self._graph, fetches, feed_dict_tensor, feed_handles=feed_handles)
214
-
215
- 1138
216
-
217
- 1139 # Run request and get response.
218
-
219
-
220
-
221
- /usr/local/lib/python3.6/dist-packages/tensorflow/python/client/session.py in __init__(self, graph, fetches, feeds, feed_handles)
222
-
223
- 469 """
224
-
225
- 470 with graph.as_default():
226
-
227
- --> 471 self._fetch_mapper = _FetchMapper.for_fetch(fetches)
228
-
229
- 472 self._fetches = []
230
-
231
- 473 self._targets = []
232
-
233
-
234
-
235
- /usr/local/lib/python3.6/dist-packages/tensorflow/python/client/session.py in for_fetch(fetch)
236
-
237
- 259 elif isinstance(fetch, (list, tuple)):
238
-
239
- 260 # NOTE(touts): This is also the code path for namedtuples.
240
-
241
- --> 261 return _ListFetchMapper(fetch)
242
-
243
- 262 elif isinstance(fetch, collections.Mapping):
244
-
245
- 263 return _DictFetchMapper(fetch)
246
-
247
-
248
-
249
- /usr/local/lib/python3.6/dist-packages/tensorflow/python/client/session.py in __init__(self, fetches)
250
-
251
- 368 """
252
-
253
- 369 self._fetch_type = type(fetches)
254
-
255
- --> 370 self._mappers = [_FetchMapper.for_fetch(fetch) for fetch in fetches]
256
-
257
- 371 self._unique_fetches, self._value_indices = _uniquify_fetches(self._mappers)
258
-
259
- 372
260
-
261
-
262
-
263
- /usr/local/lib/python3.6/dist-packages/tensorflow/python/client/session.py in <listcomp>(.0)
264
-
265
- 368 """
266
-
267
- 369 self._fetch_type = type(fetches)
268
-
269
- --> 370 self._mappers = [_FetchMapper.for_fetch(fetch) for fetch in fetches]
270
-
271
- 371 self._unique_fetches, self._value_indices = _uniquify_fetches(self._mappers)
272
-
273
- 372
274
-
275
-
276
-
277
- /usr/local/lib/python3.6/dist-packages/tensorflow/python/client/session.py in for_fetch(fetch)
278
-
279
- 269 if isinstance(fetch, tensor_type):
280
-
281
- 270 fetches, contraction_fn = fetch_fn(fetch)
282
-
283
- --> 271 return _ElementFetchMapper(fetches, contraction_fn)
284
-
285
- 272 # Did not find anything.
286
-
287
- 273 raise TypeError('Fetch argument %r has invalid type %r' % (fetch,
288
-
289
-
290
-
291
- /usr/local/lib/python3.6/dist-packages/tensorflow/python/client/session.py in __init__(self, fetches, contraction_fn)
292
-
293
- 302 raise TypeError('Fetch argument %r has invalid type %r, '
294
-
295
- 303 'must be a string or Tensor. (%s)' %
296
-
297
- --> 304 (fetch, type(fetch), str(e)))
298
-
299
- 305 except ValueError as e:
300
-
301
- 306 raise ValueError('Fetch argument %r cannot be interpreted as a '
302
-
303
-
304
-
305
417
  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.)
306
418
 
307
419
  ```