我想使用CNN分析jpg图片。但是,它不起作用。
我的分析目标是分析图像以区分0或1。 图像大小为400 x 400。 标签数为2。
import os
import cv2
import numpy as np
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import OneHotEncoder
from numpy import array
from PIL import Image
TRAIN_DIR = 'C:/Users/khs/Documents/image/'
train_folder_list = array(os.listdir(TRAIN_DIR))
train_input = []
train_label = [1,1,1,0,0,
0,0,0,0,0,
0,0,0,0,0,
0,0,0,0,0,
0,0,0,0,0,
0,0,0,0,0]
label_encoder = LabelEncoder()
integer_encoded = label_encoder.fit_transform(train_label)
onehot_encoder = OneHotEncoder(sparse=False)
integer_encoded = integer_encoded.reshape(len(integer_encoded), 1)
onehot_encoded = onehot_encoder.fit_transform(integer_encoded)
for img in img_list:
img_path = os.path.join(path, img)
img = Image.open(img_path)#.convert('LA')
train_input.append([np.array(img)])
train_input = np.reshape(train_input, (None,400,400,3))
X_train = train_input.astype('float32')
X_train = X_train/255.0
train_label = np.reshape(y_train,(-1,2))
X_test = test_input.astype('float32')
X_test = X_test/255.0
train_label = np.reshape(y_train,(-1,2))
test_label = np.reshape(y_test,(-1,2))
num_classes = train_label.shape[1]
我的cnn模型如下。 图片尺寸为400 * 400,Y标签数量为2 所以我定义X的形状= [None,400,400,3] 和Y_Label的形状= [None,2]
X = tf.placeholder(tf.float32,shape=[None,400,400,3]) ## 그림 사이즈
Y_Label = tf.placeholder(tf.float32,shape=[None,2]) ## 라벨 갯수
Kernel1 = tf.Variable(tf.truncated_normal(shape=[4,4,3,4],stddev=0.1))
Bias1 = tf.Variable(tf.truncated_normal(shape=[4],stddev=0.1))##
Conv1 = tf.nn.conv2d(X,Kernel1, strides=[1,1,1,1], padding = 'SAME')+Bias1
Activation1 = tf.nn.relu(Conv1)
Pool1 = tf.nn.max_pool(Activation1, ksize=[1,2,2,1], strides=[1,2,2,1],padding = 'SAME')
Kernel2 = tf.Variable(tf.truncated_normal(shape=[4,4,4,4],stddev=0.1))
Bias2 = tf.Variable(tf.truncated_normal(shape=[4],stddev=0.1))
Conv2 = tf.nn.conv2d(X,Kernel1, strides=[1,1,1,1], padding = 'SAME')+Bias2
Activation2 = tf.nn.relu(Conv2)
Pool2 = tf.nn.max_pool(Activation2, ksize=[1,2,2,1], strides=[1,2,2,1],padding = 'SAME')
W1 = tf.Variable(tf.truncated_normal(shape=[8*7*7,2]))
B1 = tf.Variable(tf.truncated_normal(shape=[2]))
Pool2_flat = tf.reshape(Pool2,[-1,8*7*7])
OutputLayer = tf.matmul(Pool2_flat,W1) + B1
Loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels = Y_Label, logits = OutputLayer))
train_step = tf.train.AdamOptimizer(0.005).minimize(Loss)
correct_prediction = tf.equal(tf.argmax(OutputLayer,1),tf.argmax(Y_Label,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
with tf.Session() as sess:
print("Start")
sess.run(tf.global_variables_initializer())
for i in range(1000):
trainingData = train_input
Y = train_label
sess.run(train_step, feed_dict={X:trainingData, Y_Label: Y})
if i%100 :
print('dd')
代码错误如下。
---------------------------------------------------------------------------
InvalidArgumentError Traceback (most recent call last)
~\Anaconda3\lib\site-packages\tensorflow\python\client\session.py in _do_call(self, fn, *args)
1333 try:
-> 1334 return fn(*args)
1335 except errors.OpError as e:
~\Anaconda3\lib\site-packages\tensorflow\python\client\session.py in _run_fn(feed_dict, fetch_list, target_list, options, run_metadata)
1318 return self._call_tf_sessionrun(
-> 1319 options, feed_dict, fetch_list, target_list, run_metadata)
1320
~\Anaconda3\lib\site-packages\tensorflow\python\client\session.py in _call_tf_sessionrun(self, options, feed_dict, fetch_list, target_list, run_metadata)
1406 self._session, options, feed_dict, fetch_list, target_list,
-> 1407 run_metadata)
1408
InvalidArgumentError: Input to reshape is a tensor with 4800000 values, but the requested shape requires a multiple of 392
[[{{node Reshape_16}}]]
During handling of the above exception, another exception occurred:
InvalidArgumentError Traceback (most recent call last)
<ipython-input-223-d3d50e0c5d17> in <module>
32 trainingData = train_input
33 Y = train_label
---> 34 sess.run(train_step, feed_dict={X:trainingData, Y_Label: Y})
35 if i%100 :
36 print('dd')
~\Anaconda3\lib\site-packages\tensorflow\python\client\session.py in run(self, fetches, feed_dict, options, run_metadata)
927 try:
928 result = self._run(None, fetches, feed_dict, options_ptr,
--> 929 run_metadata_ptr)
930 if run_metadata:
931 proto_data = tf_session.TF_GetBuffer(run_metadata_ptr)
~\Anaconda3\lib\site-packages\tensorflow\python\client\session.py in _run(self, handle, fetches, feed_dict, options, run_metadata)
1150 if final_fetches or final_targets or (handle and feed_dict_tensor):
1151 results = self._do_run(handle, final_targets, final_fetches,
-> 1152 feed_dict_tensor, options, run_metadata)
1153 else:
1154 results = []
~\Anaconda3\lib\site-packages\tensorflow\python\client\session.py in _do_run(self, handle, target_list, fetch_list, feed_dict, options, run_metadata)
1326 if handle is None:
1327 return self._do_call(_run_fn, feeds, fetches, targets, options,
-> 1328 run_metadata)
1329 else:
1330 return self._do_call(_prun_fn, handle, feeds, fetches)
~\Anaconda3\lib\site-packages\tensorflow\python\client\session.py in _do_call(self, fn, *args)
1346 pass
1347 message = error_interpolation.interpolate(message, self._graph)
-> 1348 raise type(e)(node_def, op, message)
1349
1350 def _extend_graph(self):
InvalidArgumentError: Input to reshape is a tensor with 4800000 values, but the requested shape requires a multiple of 392
[[node Reshape_16 (defined at <ipython-input-223-d3d50e0c5d17>:18) ]]
Caused by op 'Reshape_16', defined at:
File "C:\Users\khs\Anaconda3\lib\runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "C:\Users\khs\Anaconda3\lib\runpy.py", line 85, in _run_code
exec(code, run_globals)
File "C:\Users\khs\Anaconda3\lib\site-packages\ipykernel_launcher.py", line 16, in <module>
app.launch_new_instance()
File "C:\Users\khs\Anaconda3\lib\site-packages\traitlets\config\application.py", line 658, in launch_instance
app.start()
File "C:\Users\khs\Anaconda3\lib\site-packages\ipykernel\kernelapp.py", line 505, in start
self.io_loop.start()
File "C:\Users\khs\Anaconda3\lib\site-packages\tornado\platform\asyncio.py", line 148, in start
self.asyncio_loop.run_forever()
File "C:\Users\khs\Anaconda3\lib\asyncio\base_events.py", line 539, in run_forever
self._run_once()
File "C:\Users\khs\Anaconda3\lib\asyncio\base_events.py", line 1775, in _run_once
handle._run()
File "C:\Users\khs\Anaconda3\lib\asyncio\events.py", line 88, in _run
self._context.run(self._callback, *self._args)
File "C:\Users\khs\Anaconda3\lib\site-packages\tornado\ioloop.py", line 690, in <lambda>
lambda f: self._run_callback(functools.partial(callback, future))
File "C:\Users\khs\Anaconda3\lib\site-packages\tornado\ioloop.py", line 743, in _run_callback
ret = callback()
File "C:\Users\khs\Anaconda3\lib\site-packages\tornado\gen.py", line 781, in inner
self.run()
File "C:\Users\khs\Anaconda3\lib\site-packages\tornado\gen.py", line 742, in run
yielded = self.gen.send(value)
File "C:\Users\khs\Anaconda3\lib\site-packages\ipykernel\kernelbase.py", line 357, in process_one
yield gen.maybe_future(dispatch(*args))
File "C:\Users\khs\Anaconda3\lib\site-packages\tornado\gen.py", line 209, in wrapper
yielded = next(result)
File "C:\Users\khs\Anaconda3\lib\site-packages\ipykernel\kernelbase.py", line 267, in dispatch_shell
yield gen.maybe_future(handler(stream, idents, msg))
File "C:\Users\khs\Anaconda3\lib\site-packages\tornado\gen.py", line 209, in wrapper
yielded = next(result)
File "C:\Users\khs\Anaconda3\lib\site-packages\ipykernel\kernelbase.py", line 534, in execute_request
user_expressions, allow_stdin,
File "C:\Users\khs\Anaconda3\lib\site-packages\tornado\gen.py", line 209, in wrapper
yielded = next(result)
File "C:\Users\khs\Anaconda3\lib\site-packages\ipykernel\ipkernel.py", line 294, in do_execute
res = shell.run_cell(code, store_history=store_history, silent=silent)
File "C:\Users\khs\Anaconda3\lib\site-packages\ipykernel\zmqshell.py", line 536, in run_cell
return super(ZMQInteractiveShell, self).run_cell(*args, **kwargs)
File "C:\Users\khs\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 2848, in run_cell
raw_cell, store_history, silent, shell_futures)
File "C:\Users\khs\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 2874, in _run_cell
return runner(coro)
File "C:\Users\khs\Anaconda3\lib\site-packages\IPython\core\async_helpers.py", line 67, in _pseudo_sync_runner
coro.send(None)
File "C:\Users\khs\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 3049, in run_cell_async
interactivity=interactivity, compiler=compiler, result=result)
File "C:\Users\khs\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 3214, in run_ast_nodes
if (yield from self.run_code(code, result)):
File "C:\Users\khs\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 3296, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-223-d3d50e0c5d17>", line 18, in <module>
Pool2_flat = tf.reshape(Pool2,[-1,8*7*7])
File "C:\Users\khs\Anaconda3\lib\site-packages\tensorflow\python\ops\gen_array_ops.py", line 8461, in reshape
"Reshape", tensor=tensor, shape=shape, name=name)
File "C:\Users\khs\Anaconda3\lib\site-packages\tensorflow\python\framework\op_def_library.py", line 788, in _apply_op_helper
op_def=op_def)
File "C:\Users\khs\Anaconda3\lib\site-packages\tensorflow\python\util\deprecation.py", line 507, in new_func
return func(*args, **kwargs)
File "C:\Users\khs\Anaconda3\lib\site-packages\tensorflow\python\framework\ops.py", line 3300, in create_op
op_def=op_def)
File "C:\Users\khs\Anaconda3\lib\site-packages\tensorflow\python\framework\ops.py", line 1801, in __init__
self._traceback = tf_stack.extract_stack()
InvalidArgumentError (see above for traceback): Input to reshape is a tensor with 4800000 values, but the requested shape requires a multiple of 392
[[node Reshape_16 (defined at <ipython-input-223-d3d50e0c5d17>:18) ]]