I have a TensorBoard embedding that is created and saved like this from a gensim Doc2Vec model:
embedding = model.docvecs.vectors_docs
tf.reset_default_graph()
sess = tf.InteractiveSession()
X = tf.Variable([0.0], name='embedding')
place = tf.placeholder(tf.float32, shape=embedding.shape)
set_x = tf.assign(X, place, validate_shape=False)
sess.run(tf.global_variables_initializer())
sess.run(set_x, feed_dict={place: embedding})
summary_writer = tf.summary.FileWriter('log', sess.graph)
config = projector.ProjectorConfig()
embedding_conf = config.embeddings.add()
embedding_conf.tensor_name = 'embedding:0'
embedding_conf.metadata_path = os.path.join('log','metadata.tsv')
projector.visualize_embeddings(summary_writer, config)
saver = tf.train.Saver([X])
saver.save(sess, os.path.join('log', 'model.ckpt'), 1)
Results in this error:
TensorBoard 1.5.1 at http://COMPUTER_NAME:6006 (Press CTRL+C to quit)
E0222 17:15:20.231085 Thread-1 _internal.py:88] Error on request:
Traceback (most recent call last):
File "c:\users\user\_installed\anaconda\envs\docsim\lib\site-packages\werkzeug
\serving.py", line 270, in run_wsgi
execute(self.server.app)
File "c:\users\user\_installed\anaconda\envs\docsim\lib\site-packages\werkzeug
\serving.py", line 258, in execute
application_iter = app(environ, start_response)
File "c:\users\user\_installed\anaconda\envs\docsim\lib\site-packages\tensorbo
ard\backend\application.py", line 271, in __call__
return self.data_applications[clean_path](environ, start_response)
File "c:\users\user\_installed\anaconda\envs\docsim\lib\site-packages\werkzeug
\wrappers.py", line 308, in application
resp = f(*args[:-2] + (request,))
File "c:\users\user\_installed\anaconda\envs\docsim\lib\site-packages\tensorbo
ard\plugins\projector\projector_plugin.py", line 514, in _serve_metadata
for line in f:
File "c:\users\user\_installed\anaconda\envs\docsim\lib\site-packages\tensorfl
ow\python\lib\io\file_io.py", line 214, in __next__
return self.next()
File "c:\users\user\_installed\anaconda\envs\docsim\lib\site-packages\tensorfl
ow\python\lib\io\file_io.py", line 208, in next
retval = self.readline()
File "c:\users\user\_installed\anaconda\envs\docsim\lib\site-packages\tensorfl
ow\python\lib\io\file_io.py", line 178, in readline
return self._prepare_value(self._read_buf.ReadLineAsString())
File "c:\users\user\_installed\anaconda\envs\docsim\lib\site-packages\tensorfl
ow\python\lib\io\file_io.py", line 94, in _prepare_value
return compat.as_str_any(val)
File "c:\users\user\_installed\anaconda\envs\docsim\lib\site-packages\tensorfl
ow\python\util\compat.py", line 106, in as_str_any
return as_str(value)
File "c:\users\user\_installed\anaconda\envs\docsim\lib\site-packages\tensorfl
ow\python\util\compat.py", line 84, in as_text
return bytes_or_text.decode(encoding)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x92 in position 84: invalid
start byte
When I remove the embedding_conf.metadata_path = os.path.join('log','metadata.tsv') line, no error occurs. In addition, I can then select the very same metadata file that TensorFlow was attempting to bind to the embedding when the error occurred.
Why is this error occurring?
Is it possible that the data inside your metadata.tsv file isn't UTF-8 encoded?
Related
(base) C:\Windows\System32>anaconda-navigator
2022-10-25 21:01:52,124 - ERROR init.global_exception_logger:19
'utf-8' codec can't decode byte 0xbb in position 0: invalid start byte
Traceback (most recent call last):
File "D:\anaconda3\lib\site-packages\anaconda_navigator\widgets\main_window_init_.py", line 497, in setup
self.post_setup(conda_data=output)
File "D:\anaconda3\lib\site-packages\anaconda_navigator\widgets\main_window_init_.py", line 525, in post_setup
self.tab_home.setup(conda_data)
File "D:\anaconda3\lib\site-packages\anaconda_navigator\widgets\tabs\home.py", line 253, in setup
self.update_applications()
File "D:\anaconda3\lib\site-packages\anaconda_navigator\widgets\tabs\home.py", line 292, in update_applications
self.api.process_apps(self._applications, prefix=self.current_prefix).values(),
File "D:\anaconda3\lib\site-packages\anaconda_navigator\api\anaconda_api.py", line 561, in process_apps
collected_applications: external_apps.ApplicationCollection = external_apps.get_applications(
File "D:\anaconda3\lib\site-packages\anaconda_navigator\api\external_apps_init.py", line 49, in get_applications
apps: typing.Sequence[typing.Union[BaseApp, AppPatch]] = config_utils.load_configuration(context=context)
File "D:\anaconda3\lib\site-packages\anaconda_navigator\api\external_apps\config_utils.py", line 217, in load_configuration
return apply_configuration(
File "D:\anaconda3\lib\site-packages\anaconda_navigator\api\external_apps\config_utils.py", line 198, in apply_configuration
addition: typing.Union[None, base.BaseApp, base.AppPatch] = base.BaseApp.parse_configuration(
File "D:\anaconda3\lib\site-packages\anaconda_navigator\api\external_apps\base.py", line 233, in parse_configuration
return target_cls._parse_configuration( # pylint: disable=protected-access
File "D:\anaconda3\lib\site-packages\anaconda_navigator\api\external_apps\base.py", line 458, in _parse_configuration
result: BaseInstallableApp = BaseInstallableApp(
File "", line 17, in init
self.attrs_post_init()
File "D:\anaconda3\lib\site-packages\anaconda_navigator\api\external_apps\base.py", line 378, in attrs_post_init
for location in self._detector(context=context):
File "D:\anaconda3\lib\site-packages\anaconda_navigator\api\external_apps\bundle\vscode_utils.py", line 58, in call
stdout, _, _ = conda_launch_utils.run_process([application.executable, '--version'])
File "D:\anaconda3\lib\site-packages\anaconda_navigator\utils\conda\launch.py", line 45, in run_process
stdout = ansi_utlils.escape_ansi(raw_stdout.decode())
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xbb in position 0: invalid start byte
can anyone help me to solve this issue?
I am working with gpt2, python 3.9 and tensorflow 2.5 and when connecting to flask (flask run in terminal) I get a following message:
TypeError: Cannot cast array data from dtype('O') to dtype('int64') according to the rule 'safe'
Here is the code in generator.py
#!/usr/bin/env python3
import fire
import json
import os
import numpy as np
import tensorflow.compat.v1 as tf
# import model, sample, encoder
from text_generator import model
from text_generator import sample
from text_generator import encoder
class AI:
def generate_text(self, input_text):
model_name = '117M_Trained'
seed = None,
nsamples = 1
batch_size = 1
length = 150
temperature = 1
top_k = 40
top_p = 1
models_dir = 'models'
self.response = ''
models_dir = os.path.expanduser(os.path.expandvars(models_dir))
if batch_size is None:
batch_size = 1
assert nsamples % batch_size == 0
enc = encoder.get_encoder(model_name, models_dir)
hparams = model.default_hparams()
cur_path = os.path.dirname(__file__) + '/models' + '/' + model_name
with open(cur_path + '/hparams.json') as f:
hparams.override_from_dict(json.load(f))
if length is None:
length = hparams.n_ctx // 2
elif length > hparams.n_ctx:
raise ValueError("Can't get samples longer than window size: %s" % hparams.n_ctx)
with tf.Session(graph=tf.Graph()) as sess:
context = tf.placeholder(tf.int32, [batch_size, None])
np.random.seed(seed)
tf.set_random_seed(seed)
output = sample.sample_sequence(
hparams=hparams, length=length,
context=context,
batch_size=batch_size,
temperature=temperature, top_k=top_k, top_p=top_p
)
saver = tf.train.Saver()
ckpt = tf.train.latest_checkpoint(cur_path)
saver.restore(sess, ckpt)
context_tokens = enc.encode(input_text)
generated = 0
for _ in range(nsamples // batch_size):
out = sess.run(output, feed_dict={
context: [context_tokens for _ in range(batch_size)]
})[:, len(context_tokens):]
for i in range(batch_size):
generated += 1
text = enc.decode(out[i])
self.response = text
return self.response
ai = AI()
text = ai.generate_text('How are you?')
print(text)
Any help is appreciated 🙏 ps I have also added below the entire traceback
* Serving Flask app 'text_generator' (lazy loading)
* Environment: development
* Debug mode: on
2021-09-14 19:58:08.687907: I tensorflow/core/platform/cpu_feature_guard.cc:142] This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN) to use the following CPU instructions in performance-critical operations: AVX2 FMA
To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags.
Traceback (most recent call last):
File "_mt19937.pyx", line 178, in numpy.random._mt19937.MT19937._legacy_seeding
TypeError: 'tuple' object cannot be interpreted as an integer
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/dusandev/miniconda3/bin/flask", line 8, in <module>
sys.exit(main())
File "/Users/dusandev/miniconda3/lib/python3.9/site-packages/flask/cli.py", line 990, in main
cli.main(args=sys.argv[1:])
File "/Users/dusandev/miniconda3/lib/python3.9/site-packages/flask/cli.py", line 596, in main
return super().main(*args, **kwargs)
File "/Users/dusandev/miniconda3/lib/python3.9/site-packages/click/core.py", line 1062, in main
rv = self.invoke(ctx)
File "/Users/dusandev/miniconda3/lib/python3.9/site-packages/click/core.py", line 1668, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "/Users/dusandev/miniconda3/lib/python3.9/site-packages/click/core.py", line 1404, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "/Users/dusandev/miniconda3/lib/python3.9/site-packages/click/core.py", line 763, in invoke
return __callback(*args, **kwargs)
File "/Users/dusandev/miniconda3/lib/python3.9/site-packages/click/decorators.py", line 84, in new_func
return ctx.invoke(f, obj, *args, **kwargs)
File "/Users/dusandev/miniconda3/lib/python3.9/site-packages/click/core.py", line 763, in invoke
return __callback(*args, **kwargs)
File "/Users/dusandev/miniconda3/lib/python3.9/site-packages/flask/cli.py", line 845, in run_command
app = DispatchingApp(info.load_app, use_eager_loading=eager_loading)
File "/Users/dusandev/miniconda3/lib/python3.9/site-packages/flask/cli.py", line 321, in __init__
self._load_unlocked()
File "/Users/dusandev/miniconda3/lib/python3.9/site-packages/flask/cli.py", line 346, in _load_unlocked
self._app = rv = self.loader()
File "/Users/dusandev/miniconda3/lib/python3.9/site-packages/flask/cli.py", line 402, in load_app
app = locate_app(self, import_name, name)
File "/Users/dusandev/miniconda3/lib/python3.9/site-packages/flask/cli.py", line 256, in locate_app
__import__(module_name)
File "/Users/dusandev/Desktop/AI/text_generator/__init__.py", line 2, in <module>
from .routes import generator
File "/Users/dusandev/Desktop/AI/text_generator/routes.py", line 2, in <module>
from .generator import ai
File "/Users/dusandev/Desktop/AI/text_generator/generator.py", line 74, in <module>
text = ai.generate_text('How are you?')
File "/Users/dusandev/Desktop/AI/text_generator/generator.py", line 46, in generate_text
np.random.seed(seed)
File "mtrand.pyx", line 244, in numpy.random.mtrand.RandomState.seed
File "_mt19937.pyx", line 166, in numpy.random._mt19937.MT19937._legacy_seeding
File "_mt19937.pyx", line 186, in numpy.random._mt19937.MT19937._legacy_seeding
TypeError: Cannot cast array data from dtype('O') to dtype('int64') according to the rule 'safe'
The problem is the line None, in your code. This is causing the tuple (None,) as the input to the np.random.seed(seed). It accepts integer, but you are sending the tuple.
I am learning ML from AI Adventures but I have a problem with that code
WARNING:tensorflow:From Ai1.py:12: load_csv_with_header (from tensorflow.contrib.learn.python.learn.datasets.base) is deprecated and will be removed in a future version.
Instructions for updating:
Use tf.data instead.
Traceback (most recent call last):
File "Ai1.py", line 12, in <module>
target_dtype=np.int)
File "C:\Users\Ardit\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\util\deprecation.py", line 324, in new_func
return func(*args, **kwargs)
File "C:\Users\Ardit\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\contrib\learn\python\learn\datasets\base.py", line 53, in load_csv_with_header
header = next(data_file)
File "C:\Users\Ardit\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\lib\io\file_io.py", line 220, in __next__
return self.next()
File "C:\Users\Ardit\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\lib\io\file_io.py", line 214, in next
retval = self.readline()
File "C:\Users\Ardit\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\lib\io\file_io.py", line 184, in readline
return self._prepare_value(self._read_buf.ReadLineAsString())
File "C:\Users\Ardit\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\lib\io\file_io.py", line 100, in _prepare_value
return compat.as_str_any(val)
File "C:\Users\Ardit\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\util\compat.py", line 107, in as_str_any
return as_str(value)
File "C:\Users\Ardit\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\util\compat.py", line 80, in as_text
return bytes_or_text.decode(encoding)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 8: invalid start byte
I am using python 3.6
Can anyone help me
Sorry, here is the code
import tensorflow as tf
import numpy as np
from tensorflow.contrib.learn.python.learn.datasets import base
# Data files
IRIS_TRAINING = "iris_training.csv"
IRIS_TEST = "iris_test.csv"
# Load datasets.
training_set = base.load_csv_with_header(filename=IRIS_TRAINING,
features_dtype=np.float32,
target_dtype=np.int)
test_set = base.load_csv_with_header(filename=IRIS_TEST,
features_dtype=np.float32,
target_dtype=np.int)
print(training_set.data)
print(training_set.target)
I am trying to train Autoencoder by Chainer in python and wrote below code. But it does not work. Why??
class Autoencoder(Chain):
def __init__(self):
super().__init__()
with self.init_scope():
self.l1 = L.Linear(3,2)
self.l2 = L.Linear(2,3)
def __call__(self,x):
h1 = self.l1(x)
h2 = self.l2(h1)
return h2
class Dataset(dataset.DatasetMixin):
def __init__(self,number_of_data, show_initial = False):
noise_level = 1
self.data = np.zeros((number_of_data,3),dtype = np.float32)
OA_vector = np.array([3,2,1])
OB_vector = np.array([2,-1,1])
t = np.random.uniform(-0.5,0.5,number_of_data)
s = np.random.uniform(-0.5,0.5,number_of_data)
for i in range(0,number_of_data):
noise = np.random.uniform(-noise_level, noise_level,3)
self.data[i] = t[i]*OA_vector + s[i]*OB_vector + noise
def __len__(self):
return self.data.shape[0]
def get_example(self,idx):
return self.data[idx]
if __name__ == "__main__":
n_epoch = 5
batch_size = 100
number_of_data = 1000 #データ数
train_data = Dataset(number_of_data,False)
model = Autoencoder()
optimizer = optimizers.SGD(lr=0.05).setup(model)
train_iter = iterators.SerialIterator(train_data,batch_size)
updater = training.StandardUpdater(train_iter,optimizer,device=0)
trainer = training.Trainer(updater,(n_epoch,"epoch"),out="result")
trainer.run()
I am using Chainer. And the Dataset makes 3 dimensitonal vectors. The number of the vectors is "number_of_data".
Should I do that without using trainer?
I don't understand where problem is.
EDIT
When we run above code with device=0, we have error like below.
Exception in main training loop: Unsupported type <class 'NoneType'>
Traceback (most recent call last):
File "/home/****/.local/lib/python3.5/site-packages/chainer/training/trainer.py", line 308, in run
update()
File "/home/****/.local/lib/python3.5/site-packages/chainer/training/updaters/standard_updater.py", line 149, in update
self.update_core()
File "/home/****/.local/lib/python3.5/site-packages/chainer/training/updaters/standard_updater.py", line 164, in update_core
optimizer.update(loss_func, in_arrays)
File "/home/****/.local/lib/python3.5/site-packages/chainer/optimizer.py", line 655, in update
loss.backward(loss_scale=self._loss_scale)
File "/home/****/.local/lib/python3.5/site-packages/chainer/variable.py", line 966, in backward
self._backward_main(retain_grad, loss_scale)
File "/home/****/.local/lib/python3.5/site-packages/chainer/variable.py", line 1095, in _backward_main
target_input_indexes, out_grad, in_grad)
File "/home/****/.local/lib/python3.5/site-packages/chainer/function_node.py", line 548, in backward_accumulate
gxs = self.backward(target_input_indexes, grad_outputs)
File "/home/****/.local/lib/python3.5/site-packages/chainer/functions/activation/relu.py", line 73, in backward
return ReLUGrad2(y).apply((gy,))
File "/home/****/.local/lib/python3.5/site-packages/chainer/function_node.py", line 258, in apply
outputs = self.forward(in_data)
File "/home/****/.local/lib/python3.5/site-packages/chainer/function_node.py", line 368, in forward
return self.forward_cpu(inputs)
File "/home/****/.local/lib/python3.5/site-packages/chainer/functions/activation/relu.py", line 97, in forward_cpu
y = (self.b > 0) * inputs[0]
File "cupy/core/core.pyx", line 1310, in cupy.core.core.ndarray.__mul__
File "cupy/core/elementwise.pxi", line 753, in cupy.core.core.ufunc.__call__
File "cupy/core/elementwise.pxi", line 68, in cupy.core.core._preprocess_args
Will finalize trainer extensions and updater before reraising the exception.
Traceback (most recent call last):
File "AC.py", line 70, in <module>
trainer.run()
File "/home/****/.local/lib/python3.5/site-packages/chainer/training/trainer.py", line 322, in run
six.reraise(*sys.exc_info())
File "/home/****/.local/lib/python3.5/site-packages/six.py", line 693, in reraise
raise value
File "/home/****/.local/lib/python3.5/site-packages/chainer/training/trainer.py", line 308, in run
update()
File "/home/****/.local/lib/python3.5/site-packages/chainer/training/updaters/standard_updater.py", line 149, in update
self.update_core()
File "/home/****/.local/lib/python3.5/site-packages/chainer/training/updaters/standard_updater.py", line 164, in update_core
optimizer.update(loss_func, in_arrays)
File "/home/****/.local/lib/python3.5/site-packages/chainer/optimizer.py", line 655, in update
loss.backward(loss_scale=self._loss_scale)
File "/home/****/.local/lib/python3.5/site-packages/chainer/variable.py", line 966, in backward
self._backward_main(retain_grad, loss_scale)
File "/home/****/.local/lib/python3.5/site-packages/chainer/variable.py", line 1095, in _backward_main
target_input_indexes, out_grad, in_grad)
File "/home/****/.local/lib/python3.5/site-packages/chainer/function_node.py", line 548, in backward_accumulate
gxs = self.backward(target_input_indexes, grad_outputs)
File "/home/****/.local/lib/python3.5/site-packages/chainer/functions/activation/relu.py", line 73, in backward
return ReLUGrad2(y).apply((gy,))
File "/home/****/.local/lib/python3.5/site-packages/chainer/function_node.py", line 258, in apply
outputs = self.forward(in_data)
File "/home/****/.local/lib/python3.5/site-packages/chainer/function_node.py", line 368, in forward
return self.forward_cpu(inputs)
File "/home/****/.local/lib/python3.5/site-packages/chainer/functions/activation/relu.py", line 97, in forward_cpu
y = (self.b > 0) * inputs[0]
File "cupy/core/core.pyx", line 1310, in cupy.core.core.ndarray.__mul__
File "cupy/core/elementwise.pxi", line 753, in cupy.core.core.ufunc.__call__
File "cupy/core/elementwise.pxi", line 68, in cupy.core.core._preprocess_args
TypeError: Unsupported type <class 'NoneType'>
When we run above code with device=-1, we have error like below.
Exception in main training loop: unsupported operand type(s) for *: 'bool' and 'NoneType'
Traceback (most recent call last):
File "/home/****/.local/lib/python3.5/site-packages/chainer/training/trainer.py", line 308, in run
update()
File "/home/****/.local/lib/python3.5/site-packages/chainer/training/updaters/standard_updater.py", line 149, in update
self.update_core()
File "/home/****/.local/lib/python3.5/site-packages/chainer/training/updaters/standard_updater.py", line 164, in update_core
optimizer.update(loss_func, in_arrays)
File "/home/****/.local/lib/python3.5/site-packages/chainer/optimizer.py", line 655, in update
loss.backward(loss_scale=self._loss_scale)
File "/home/****/.local/lib/python3.5/site-packages/chainer/variable.py", line 966, in backward
self._backward_main(retain_grad, loss_scale)
File "/home/****/.local/lib/python3.5/site-packages/chainer/variable.py", line 1095, in _backward_main
target_input_indexes, out_grad, in_grad)
File "/home/****/.local/lib/python3.5/site-packages/chainer/function_node.py", line 548, in backward_accumulate
gxs = self.backward(target_input_indexes, grad_outputs)
File "/home/****/.local/lib/python3.5/site-packages/chainer/functions/activation/relu.py", line 73, in backward
return ReLUGrad2(y).apply((gy,))
File "/home/****/.local/lib/python3.5/site-packages/chainer/function_node.py", line 258, in apply
outputs = self.forward(in_data)
File "/home/****/.local/lib/python3.5/site-packages/chainer/function_node.py", line 368, in forward
return self.forward_cpu(inputs)
File "/home/****/.local/lib/python3.5/site-packages/chainer/functions/activation/relu.py", line 97, in forward_cpu
y = (self.b > 0) * inputs[0]
Will finalize trainer extensions and updater before reraising the exception.
Traceback (most recent call last):
File "AC.py", line 70, in <module>
trainer.run()
File "/home/****/.local/lib/python3.5/site-packages/chainer/training/trainer.py", line 322, in run
six.reraise(*sys.exc_info())
File "/home/****/.local/lib/python3.5/site-packages/six.py", line 693, in reraise
raise value
File "/home/****/.local/lib/python3.5/site-packages/chainer/training/trainer.py", line 308, in run
update()
File "/home/****/.local/lib/python3.5/site-packages/chainer/training/updaters/standard_updater.py", line 149, in update
self.update_core()
File "/home/****/.local/lib/python3.5/site-packages/chainer/training/updaters/standard_updater.py", line 164, in update_core
optimizer.update(loss_func, in_arrays)
File "/home/****/.local/lib/python3.5/site-packages/chainer/optimizer.py", line 655, in update
loss.backward(loss_scale=self._loss_scale)
File "/home/****/.local/lib/python3.5/site-packages/chainer/variable.py", line 966, in backward
self._backward_main(retain_grad, loss_scale)
File "/home/****/.local/lib/python3.5/site-packages/chainer/variable.py", line 1095, in _backward_main
target_input_indexes, out_grad, in_grad)
File "/home/****/.local/lib/python3.5/site-packages/chainer/function_node.py", line 548, in backward_accumulate
gxs = self.backward(target_input_indexes, grad_outputs)
File "/home/****/.local/lib/python3.5/site-packages/chainer/functions/activation/relu.py", line 73, in backward
return ReLUGrad2(y).apply((gy,))
File "/home/****/.local/lib/python3.5/site-packages/chainer/function_node.py", line 258, in apply
outputs = self.forward(in_data)
File "/home/****/.local/lib/python3.5/site-packages/chainer/function_node.py", line 368, in forward
return self.forward_cpu(inputs)
File "/home/****/.local/lib/python3.5/site-packages/chainer/functions/activation/relu.py", line 97, in forward_cpu
y = (self.b > 0) * inputs[0]
TypeError: unsupported operand type(s) for *: 'bool' and 'NoneType'
I think the model need to return loss in __call__ method.
Sample modification is as follows:
class Autoencoder(Chain):
def __init__(self):
super().__init__()
with self.init_scope():
self.l1 = L.Linear(3,2)
self.l2 = L.Linear(2,3)
def forward(self,x):
h1 = self.l1(x)
h2 = self.l2(h1)
return h2
def __call__(self,x):
h = self.forward(x)
# Instead of h, __call__ should return loss.
loss = F.mean_squared_error(h, x)
return loss
when i use the lstm to comlete the multi-class label,i use the y_train as my label input.
the code below:
y_train = yuantrain['LOCF']
labels = to_categorical(np.array(y_train),286)
the error code hint:
Traceback (most recent call last):
File "<ipython-input-55-4ae3f21f520f>", line 1, in <module>
labels = to_categorical(np.array(y_train))
File "C:\ProgramData\Anaconda2\lib\site-packages\keras\utils\np_utils.py",
line 24, in to_categorical
categorical = np.zeros((n, num_classes))
MemoryError
below is the y_train(5) :
In [65]:
y_train[0:5]
Out[65]:
0 620245
1 282
2 500004
3 620193
4 60119
Name: LOCF, dtype: int64
THAT I HAVE A TRY:
# biao qian chu li
# 处理标签为二进制,以及思考二进制的解码
labels = yuantrain["LOCF"].drop_duplicates()
#labels is the y_train's unique label
num_labels = len(labels) # (all of the unique labels)
one_hot = np.zeros((num_labels, num_labels), int)
np.fill_diagonal(one_hot, 1)
label_dict = dict(zip(labels, one_hot))
y_train = yuantrain['LOCF']
y_train = y_train.apply(lambda y: label_dict[y])
BUT I feel it is not easy for me, that i have to decode in only my way.
when i use my one-hot way,the keras also have error like below:
Train...
ERROR (theano.gof.opt): SeqOptimizer apply <theano.tensor.opt.FusionOptimizer object at 0x000000000D87B0F0>
ERROR (theano.gof.opt): Traceback:
ERROR (theano.gof.opt): Traceback (most recent call last):
File "C:\ProgramData\Anaconda2\lib\site-packages\theano\gof\opt.py", line 235, in apply
sub_prof = optimizer.optimize(fgraph)
File "C:\ProgramData\Anaconda2\lib\site-packages\theano\gof\opt.py", line 87, in optimize
ret = self.apply(fgraph, *args, **kwargs)
File "C:\ProgramData\Anaconda2\lib\site-packages\theano\tensor\opt.py", line 7289, in apply
new_outputs = self.optimizer(node)
File "C:\ProgramData\Anaconda2\lib\site-packages\theano\tensor\opt.py", line 7122, in local_fuse
tv = gof.op.get_test_value(ii)
File "C:\ProgramData\Anaconda2\lib\site-packages\theano\gof\op.py", line 987, in get_test_value
return PureOp._get_test_value(v_var)
File "C:\ProgramData\Anaconda2\lib\site-packages\theano\gof\op.py", line 580, in _get_test_value
detailed_err_msg = utils.get_variable_trace_string(v)
File "C:\ProgramData\Anaconda2\lib\site-packages\theano\gof\utils.py", line 134, in get_variable_trace_string
return sio.getvalue()
File "C:\ProgramData\Anaconda2\lib\StringIO.py", line 271, in getvalue
self.buf += ''.join(self.buflist)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe8 in position 27: ordinal not in range(128)
ERROR (theano.gof.opt): SeqOptimizer apply <theano.tensor.opt.FusionOptimizer object at 0x000000000D87B0F0>
ERROR (theano.gof.opt): Traceback:
ERROR (theano.gof.opt): Traceback (most recent call last):
File "C:\ProgramData\Anaconda2\lib\site-packages\theano\gof\opt.py", line 235, in apply
sub_prof = optimizer.optimize(fgraph)
File "C:\ProgramData\Anaconda2\lib\site-packages\theano\gof\opt.py", line 87, in optimize
ret = self.apply(fgraph, *args, **kwargs)
File "C:\ProgramData\Anaconda2\lib\site-packages\theano\tensor\opt.py", line 7289, in apply
new_outputs = self.optimizer(node)
File "C:\ProgramData\Anaconda2\lib\site-packages\theano\tensor\opt.py", line 7122, in local_fuse
tv = gof.op.get_test_value(ii)
File "C:\ProgramData\Anaconda2\lib\site-packages\theano\gof\op.py", line 987, in get_test_value
return PureOp._get_test_value(v_var)
File "C:\ProgramData\Anaconda2\lib\site-packages\theano\gof\op.py", line 580, in _get_test_value
detailed_err_msg = utils.get_variable_trace_string(v)
File "C:\ProgramData\Anaconda2\lib\site-packages\theano\gof\utils.py", line 134, in get_variable_trace_string
return sio.getvalue()
File "C:\ProgramData\Anaconda2\lib\StringIO.py", line 271, in getvalue
self.buf += ''.join(self.buflist)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe8 in position 27: ordinal not in range(128)
Train on 100000 samples, validate on 77963 samples
Epoch 1/5
Traceback (most recent call last):
File "<ipython-input-67-5ce4b6739b03>", line 1, in <module>
runfile('E:/XIAMENproject/Prediction_Guo/count.py', wdir='E:/XIAMENproject/Prediction_Guo')
File "C:\ProgramData\Anaconda2\lib\site-packages\spyder\utils\site\sitecustomize.py", line 866, in runfile
execfile(filename, namespace)
File "C:\ProgramData\Anaconda2\lib\site-packages\spyder\utils\site\sitecustomize.py", line 87, in execfile
exec(compile(scripttext, filename, 'exec'), glob, loc)
File "E:/XIAMENproject/Prediction_Guo/count.py", line 150, in <module>
validation_data=(x_val, y_val))
File "C:\ProgramData\Anaconda2\lib\site-packages\keras\models.py", line 870, in fit
initial_epoch=initial_epoch)
File "C:\ProgramData\Anaconda2\lib\site-packages\keras\engine\training.py", line 1507, in fit
initial_epoch=initial_epoch)
File "C:\ProgramData\Anaconda2\lib\site-packages\keras\engine\training.py", line 1156, in _fit_loop
outs = f(ins_batch)
File "C:\ProgramData\Anaconda2\lib\site-packages\keras\backend\theano_backend.py", line 1196, in __call__
return self.function(*inputs)
File "C:\ProgramData\Anaconda2\lib\site-packages\theano\compile\function_module.py", line 805, in __call__
self.maker.inputs[i].variable)
File "C:\ProgramData\Anaconda2\lib\site-packages\theano\gof\utils.py", line 134, in get_variable_trace_string
return sio.getvalue()
File "C:\ProgramData\Anaconda2\lib\StringIO.py", line 271, in getvalue
self.buf += ''.join(self.buflist)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe8 in position 27: ordinal not in range(128)
I reset the tag ID to the continuous ID,and then use the to_categorical.