How parameters should be used in sitk.ReadImage()? - simpleitk

I am doing N4 bias correction in .nii file in python(Windows).For this I am using SimpleITK.While taking input of the image, I am having issues in reading the file.
Code :
print("N4 bias correction runs.")
inputImage =sitk.ReadImage("C/Users/LENOVO/Desktop/Brats18_2013_1_1_t1.nii")
maskImage = sitk.OtsuThreshold(inputImage,0,1,200)
sitk.WriteImage(maskImage,"C/Users/LENOVO/Desktop/Brats18_2013_1_1_t1_Mask.nii")
inputImage = sitk.Cast(inputImage,sitk.sitkFloat32)
corrector = sitk.N4BiasFieldCorrectionImageFilter();
output = corrector.Execute(inputImage,maskImage)
sitk.WriteImage(output,"C/Users/LENOVO/Desktop/Brats18_2013_1_1_t1_Mask.nii")
print("Finished N4 Bias Field Correction.....")
Error :
RuntimeError
Traceback (most recent call last)
<ipython-input-26-0835d7f75708> in <module>()
1
2 print("N4 bias correction runs.")
----> 3 inputImage = sitk.ReadImage("C/Users/LENOVO/Desktop/Brats18_2013_1_1_t1.nii")
4
5 maskImage = sitk.OtsuThreshold(inputImage,0,1,200)
~\Anaconda3\lib\site-packages\SimpleITK\SimpleITK.py in ReadImage(*args)
8612
8613 """
-> 8614 return _SimpleITK.ReadImage(*args)
8615 class HashImageFilter(ProcessObject):
8616 """
RuntimeError: Exception thrown in SimpleITK ReadImage: C:\Users\dashboard\Miniconda3\conda-bld\simpleitk_1521730316398\work\Code\IO\src\sitkImageReaderBase.cxx:89:
sitk::ERROR: The file "C/Users/LENOVO/Desktop/Brats18_2013_1_1_t1.nii" does not exist.

If you're going to use the Unix-style paths, then you need a leading slash, so the file path should be:
"/C/Users/LENOVO/Desktop/Brats18_2013_1_1_t1.nii/"
Or you can use Windows-style paths, then it would be:
"c:\Users\LENOVO\Desktop\Brats18_2013_1_1_t1.nii"

Related

possible fix of " enclose the batched tensor in a with pyro.plate(...): context "

In this example, the guide step is defined as follows
def guide(params):
# returns the Bernoulli probablility
alpha = pyro.param(
"alpha", torch.tensor(params[0]), constraint=constraints.positive
)
beta = pyro.param(
"beta", torch.tensor(params[1]), constraint=constraints.positive
)
return pyro.sample("beta_dist", dist.Beta(alpha, beta))
svi = pyro.infer.SVI(
model=conditioned_data_model,
guide=guide,
optim=pyro.optim.SGD({"lr": 0.001, "momentum": 0.8}),
loss=pyro.infer.Trace_ELBO(),
)
params_prior = [prior.concentration1, prior.concentration0]
# Iterate over all the data and store results
losses, alpha, beta = [], [], []
pyro.clear_param_store()
num_steps = 3000
for t in range(num_steps):
losses.append(svi.step(params_prior))
alpha.append(pyro.param("alpha").item())
beta.append(pyro.param("beta").item())
posterior_vi = dist.Beta(alpha[-1], beta[-1])
However, running the above step gives the following error, what does those hints of fix mean and how to fix it accordingly?
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Input In [9], in <cell line: 15>()
14 num_steps = 3000
15 for t in range(num_steps):
---> 16 losses.append(svi.step(params_prior))
17 alpha.append(pyro.param("alpha").item())
18 beta.append(pyro.param("beta").item())
ValueError: at site "data_dist", invalid log_prob shape
Expected [], actual [100, 1]
Try one of the following fixes:
- enclose the batched tensor in a with pyro.plate(...): context
- .to_event(...) the distribution being sampled
- .permute() data dimensions

Python Jupyter Notebook scipy

For a long time I was able to add data and fit, then plot the curve with data. But recently I get this:
---------------------------------------------------------------------------
RuntimeError Traceback (most recent call last)
<ipython-input-6-6f645a2744bc> in <module>
1 poland = prepare_data(europe_data, 'Poland')
----> 2 plot_all(poland, max_y=400000)
3 poland
~/Pulpit/library.py in plot_all(country, max_x, max_y)
43 def plot_all(country, max_x = 1000, max_y = 500000):
44
---> 45 parameters_logistic = scipy.optimize.curve_fit(func_logistic, country['n'], country['all'])[0]
46 parameters_expo = scipy.optimize.curve_fit(func_expo, country['n'], country['all'])[0]
47
/usr/local/lib64/python3.6/site-packages/scipy/optimize/minpack.py in curve_fit(f, xdata, ydata, p0, sigma, absolute_sigma, check_finite, bounds, method, jac, **kwargs)
787 cost = np.sum(infodict['fvec'] ** 2)
788 if ier not in [1, 2, 3, 4]:
--> 789 raise RuntimeError("Optimal parameters not found: " + errmsg)
790 else:
791 # Rename maxfev (leastsq) to max_nfev (least_squares), if specified.
RuntimeError: Optimal parameters not found: Number of calls to function has reached maxfev = 800.
Here are all Python Jupyter Notebook files: https://files.fm/u/zj7cc6ne#sign_up
How to solve this?
scipy.optimize.curve_fit takes a keyword argument p0.
Initial guess for the parameters (length N). If None, then the initial
values will all be 1 (if the number of parameters for the function can
be determined using introspection, otherwise a ValueError is raised).
If the defaults 1 are too far of from the result the algorithm may not converge. Try to put some values that make sense for your problem.

Mismatch in Input Shape of tf.keras model

I am getting a mismatch in input shape of a tf.keras model. The code block is given below with the stack trace. I am using hub.keraslayer as my first layer. The model is being made for being trained using Tensor Flow Federated (TFF). The input to the model are variable length strings. Kindly suggest a way out.
#Making a Tensorflow Model
from tensorflow import keras
def create_keras_model():
encoder = hub.load("https://tfhub.dev/google/tf2-preview/gnews-swivel-20dim/1")
return tf.keras.models.Sequential([
hub.KerasLayer(encoder, input_shape=[],dtype=tf.string,trainable=True),
keras.layers.Dense(32, activation='relu'),
keras.layers.Dense(16, activation='relu'),
keras.layers.Dense(1, activation='sigmoid'),
])
def model_fn():
# We _must_ create a new model here, and _not_ capture it from an external
# scope. TFF will call this within different graph contexts.
keras_model = create_keras_model()
return tff.learning.from_keras_model(
keras_model,
input_spec=preprocessed_example_dataset.element_spec,
loss=tf.keras.losses.BinaryCrossentropy(),
metrics=[tf.keras.metrics.Accuracy()])
iterative_process = tff.learning.build_federated_averaging_process(
model_fn,
client_optimizer_fn=lambda: tf.keras.optimizers.SGD(learning_rate=0.02),
server_optimizer_fn=lambda: tf.keras.optimizers.SGD(learning_rate=1.0))
WARNING:tensorflow:From /usr/local/lib/python3.6/dist-
packages/tensorflow/python/ops/resource_variable_ops.py:1817: calling
BaseResourceVariable.__init__ (from tensorflow.python.ops.resource_variable_ops) with
constraint is deprecated and will be removed in a future version.
Instructions for updating:
If using Keras pass *_constraint arguments to layers.
WARNING:tensorflow:From /usr/local/lib/python3.6/dist-
packages/tensorflow/python/ops/resource_variable_ops.py:1817: calling
BaseResourceVariable.__init__ (from tensorflow.python.ops.resource_variable_ops) with
constraint is deprecated and will be removed in a future version.
Instructions for updating:
If using Keras pass *_constraint arguments to layers.
WARNING:tensorflow:Model was constructed with shape (None,) for input
Tensor("keras_layer_input:0", shape=(None,), dtype=string), but it was called on an input
with incompatible shape (None, None).
WARNING:tensorflow:Model was constructed with shape (None,) for input
Tensor("keras_layer_input:0", shape=(None,), dtype=string), but it was called on an input
with incompatible shape (None, None).
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-27-68fa27e65b7e> in <module>()
3 model_fn,
4 client_optimizer_fn=lambda: tf.keras.optimizers.SGD(learning_rate=0.02),
----> 5 server_optimizer_fn=lambda: tf.keras.optimizers.SGD(learning_rate=1.0))
18 frames
/usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/func_graph.py in
wrapper(*args, **kwargs)
966 except Exception as e: # pylint:disable=broad-except
967 if hasattr(e, "ag_error_metadata"):
--> 968 raise e.ag_error_metadata.to_exception(e)
969 else:
970 raise
ValueError: in user code:
/usr/local/lib/python3.6/dist-
packages/tensorflow_federated/python/learning/federated_averaging.py:91 __call__ *
num_examples_sum = dataset.reduce(
/usr/local/lib/python3.6/dist-
packages/tensorflow_federated/python/learning/model_utils.py:152 forward_pass *
self._model.forward_pass(batch_input, training), model_lib.BatchOutput)
/usr/local/lib/python3.6/dist-
packages/tensorflow_federated/python/learning/keras_utils.py:391 forward_pass *
return self._forward_pass(batch_input, training=training)
/usr/local/lib/python3.6/dist-
packages/tensorflow_federated/python/learning/keras_utils.py:359 _forward_pass *
predictions = self._keras_model(inputs, training=training)
/usr/local/lib/python3.6/dist-packages/tensorflow_hub/keras_layer.py:222 call *
result = f()
/usr/local/lib/python3.6/dist-packages/tensorflow/python/saved_model/load.py:486
_call_attribute **
return instance.__call__(*args, **kwargs)
/usr/local/lib/python3.6/dist-packages/tensorflow/python/eager/def_function.py:580 __call__
result = self._call(*args, **kwds)
/usr/local/lib/python3.6/dist-packages/tensorflow/python/eager/def_function.py:618 _call
results = self._stateful_fn(*args, **kwds)
/usr/local/lib/python3.6/dist-packages/tensorflow/python/eager/function.py:2419 __call__
graph_function, args, kwargs = self._maybe_define_function(args, kwargs)
/usr/local/lib/python3.6/dist-packages/tensorflow/python/eager/function.py:2735
_maybe_define_function
*args, **kwargs)
/usr/local/lib/python3.6/dist-packages/tensorflow/python/eager/function.py:2238
canonicalize_function_inputs
self._flat_input_signature)
/usr/local/lib/python3.6/dist-packages/tensorflow/python/eager/function.py:2305
_convert_inputs_to_signature
format_error_message(inputs, input_signature))
ValueError: Python inputs incompatible with input_signature:
inputs: (
Tensor("batch_input:0", shape=(None, None), dtype=string))
input_signature: (
TensorSpec(shape=(None,), dtype=tf.string, name=None))

How to convert mnist dataset in array

Hello consider following code
# load the mnist training data CSV file into a list
training_data_file = open("Training_Set/mnist_train_100.csv", 'r')
training_data_list = training_data_file.readlines()
training_data_file.close()
for record in training_data_list:
all_values = record.split(',')
x_inputs = (np.asfarray(all_values[1:]) / 255.0 * 0.99) + 0.01
print("xinput=" + str(x_inputs))
print(len(training_data_list))
MyCompleteInput = np.array(x_inputs,len(training_data_list))
I want to put x_inputs and len(training_data_list) into an array so if I print the shape of the array I get an output of (784,100).
But if I run my code I get following error:
TypeError Traceback (most recent call last)
<ipython-input-38-b0f129f57bcb> in <module>()
11 print("xinput=" + str(x_inputs))
12 print(len(training_data_list))
---> 13 MyCompleteInput = np.array(x_inputs,len(training_data_list))
14
15
TypeError: data type not understood
Can somebody help me out? tnx
The line will be
MyCompleteInput = np.array((x_inputs,len(training_data_list)))
Do this and your error will be gone. You need to add another set of parantheses for specifying the size.

Jython 2.5 isdigit

I am trying to add an isdigit() to the program so that I can verify what the user enters is valid. This is what I have so far. But when I run it an enter a character, say "f". It crashes and gives me the error which will be posted below the code. Any ideas?
def mirrorHorizontal(source):
userMirrorPoint = requestString("Enter a mirror point from 0 to halfway through the pitcure.") #asks user for an input
while (int(userMirrorPoint) < 0 or int(userMirrorPoint) > (int(getHeight(source) - 1)//2)) or not(userMirrorPoint.isdigit()):
userMirrorPoint = requestString("Enter a mirror point from 0 to halfway through the pitcure.")
height = getHeight(source)
mirrorPoint = int(userMirrorPoint)
for x in range(0, getWidth(source)):
for y in range(0, mirrorPoint):
topPixel = getPixel(source, x, y)
bottomPixel = getPixel(source, x, height-y-1)
color = getColor(topPixel)
setColor(bottomPixel, color)
The error was: f
Inappropriate argument value (of correct type).
An error occurred attempting to pass an argument to a function.
Please check line 182 of /Volumes/FLASHDRIVE2/College/Spring 16'/Programs - CPS 201/PA5Sikorski.py
isdigit() itself behaves itself in the 2.7.0 jython version I have locally
>>> '1'.isdigit()
True
>>> ''.isdigit()
False
>>> 'A'.isdigit()
False
>>> 'A2'.isdigit()
False
>>> '2'.isdigit()
True
>>> '22321'.isdigit()
True
Try breaking your big expression up, as typecasting to integers will throw errors for non-numeric strings. This is true across Python versions.
>>> int('b')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'b'
>>> int('2')
2
You probably want to be careful about the order of the parts of that long expression (this or that or ...). Breaking it up would also make it more readable.