回答編集履歴

3

d

2018/11/04 10:00

投稿

tiitoi
tiitoi

スコア21956

test CHANGED
@@ -88,17 +88,17 @@
88
88
 
89
89
 
90
90
 
91
- num_samples = 30
91
+ num_samples = 30 # サンプル数
92
92
 
93
- num_classes = 3
93
+ num_classes = 3 # クラス数
94
94
 
95
- num_features = 10
95
+ num_features = 10 # 特徴量の次元
96
96
 
97
97
 
98
98
 
99
99
  data = np.random.randn(num_samples, num_features)
100
100
 
101
- labels = np.random.randint(0, 10, num_samples)
101
+ labels = np.random.randint(0, num_classes, num_samples)
102
102
 
103
103
 
104
104
 

2

d

2018/11/04 10:00

投稿

tiitoi
tiitoi

スコア21956

test CHANGED
@@ -73,3 +73,87 @@
73
73
  print(np.allclose(tf_ret, np_ret)) # True
74
74
 
75
75
  ```
76
+
77
+
78
+
79
+ ## 追記
80
+
81
+
82
+
83
+ ```python
84
+
85
+ import numpy as np
86
+
87
+ import tensorflow as tf
88
+
89
+
90
+
91
+ num_samples = 30
92
+
93
+ num_classes = 3
94
+
95
+ num_features = 10
96
+
97
+
98
+
99
+ data = np.random.randn(num_samples, num_features)
100
+
101
+ labels = np.random.randint(0, 10, num_samples)
102
+
103
+
104
+
105
+ # TensorFlow
106
+
107
+ #######################################
108
+
109
+ x = tf.placeholder(tf.float32, shape=(None, num_features))
110
+
111
+ y = tf.placeholder(tf.int64, shape=(None,))
112
+
113
+
114
+
115
+ means = []
116
+
117
+ for class_id in range(num_classes):
118
+
119
+ mean = tf.reduce_mean(tf.boolean_mask(x, tf.equal(y, class_id)), axis=0)
120
+
121
+ means.append(mean)
122
+
123
+ concat = tf.stack(means)
124
+
125
+
126
+
127
+ with tf.Session() as sess:
128
+
129
+ tf_ret = sess.run(concat, feed_dict={x: data, y: labels})
130
+
131
+ print(tf_ret.shape, tf_ret) # (3, 10)
132
+
133
+
134
+
135
+ # numpy
136
+
137
+ #######################################
138
+
139
+ means = []
140
+
141
+ for class_id in range(num_classes):
142
+
143
+ mean = np.mean(data[labels==class_id], axis=0)
144
+
145
+ means.append(mean)
146
+
147
+ np_ret = np.stack(means)
148
+
149
+
150
+
151
+ # TensorFlow と numpy の計算が一致するか
152
+
153
+ print(np.allclose(tf_ret, np_ret)) # True
154
+
155
+ ```
156
+
157
+
158
+
159
+ 各クラスごとに平均を計算するならこのような感じでしょうか?

1

d

2018/11/04 09:57

投稿

tiitoi
tiitoi

スコア21956

test CHANGED
@@ -46,7 +46,7 @@
46
46
 
47
47
  tf_ret = sess.run(concat, feed_dict={input1: a, input2: b, input3: c})
48
48
 
49
- print(tf_ret.shape, tf_ret)
49
+ print(tf_ret.shape, tf_ret) # (3, 10)
50
50
 
51
51
 
52
52
 
@@ -64,7 +64,7 @@
64
64
 
65
65
 
66
66
 
67
- print(np_ret, np_ret.shape)
67
+ print(np_ret, np_ret.shape) # (3, 10)
68
68
 
69
69
 
70
70