I am tryng to get data from a API. But when I use Insomnia ou direct on browser, it is ok.
When I use axios in my code, I have this error : Blocking of a multi-origin request (Cross-Origin Request): the "Same Origin" policy does not allow to consult the remote resource....
My code
const axiosInstance = axios.create({
baseURL : 'https://trefle.io/api/v1/plants?token=********',
mode: 'no-cors',
withCredentials: false,
credentials: 'same-origin',
headers : {
'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/json',
}
})
async getPlantsList(context)
{
try{
const response = await axiosInstance.get();
console.log('2', response.data);
} catch(error){
console.log('error', error);
}
}
I need help, I search on web, but I do not find a solution.
Thank for your help
Add headers in axios instance
Several issues:
The Access-Control-Allow-Origin header has no place in your request, since it's a response header.
You cannot use the no-cors mode if you want your client to have access to the response. You'll have to use the cors mode (which is the default for cross-origin requests).
Because the resource in question doesn't seems to allow any request headers other than CORS-safelisted request headers, you won't be able to include a Content-Type header in your request. But note that the request in question is a GET, for which it makes no sense to include a Content-Type header, since GET requests are not meant to have a body. Just drop that header from your request.
If you solve all three issues, it should work.
You don't necessary to set cors option
I will shows two options by axios call.
Both makes same result
Option 1 : using create()
const axios = require("axios")
const token ='<your token>'
const api = axios.create({baseURL: `https://trefle.io/api/v1/plants/?token=${token}`});
try {
api.get().then((results) => {
for (plant of results.data.data) {
console.log(JSON.stringify(plant))
}
})
} catch (error) {
console.log(error)
}
Option 2 : no create()
const axios = require("axios")
const getPlants = async () => {
try {
const token ='<your token>'
const response = await axios.get(`https://trefle.io/api/v1/plants?token=${token}`);
return Promise.resolve(response.data);
} catch (error) {
return Promise.reject(error);
}
}
getPlants()
.then(plants => {
for (plant of plants.data) {
console.log(JSON.stringify(plant))
}
}).catch(error => console.log(error));
Result 1
$ node get-option1.js
{"id":77116,"common_name":"Evergreen oak","slug":"quercus-rotundifolia","scientific_name":"Quercus rotundifolia","year":1785,"bibliography":"Encycl. 1: 723 (1785)","author":"Lam.","status":"accepted","rank":"species","family_common_name":null,"genus_id":3519,"image_url":"https://d2seqvvyy3b8p2.cloudfront.net/40ab8e7cdddbe3e78a581b84efa4e893.jpg","synonyms":["Quercus ilex var. oleoides","Quercus ilex subvar. rotundifolia","Quercus ilex f. macrophylla","Quercus ilex f. oleoides","Quercus ilex var. calicina","Quercus ilex subsp. rotundifolia","Quercus lyauteyi","Quercus ballota var. rotundifolia","Quercus ilex f. brevicupulata","Quercus ilex subvar. major","Quercus ilex var. pendula","Quercus rotundifolia f. dolichocalyx","Quercus calicina","Quercus rotundifolia f. pilosella","Quercus rotundifolia f. macrocarpa","Quercus ilex var. rotundifolia","Quercus sugaro","Quercus ilex subvar. pendula","Quercus ilex f. pendula","Quercus ilex f. ballota","Quercus ilex f. rotundifolia","Quercus ilex subvar. minor","Quercus ballota","Quercus ilex var. ballota","Quercus ilex f. calicina","Quercus ilex var. microcarpa","Quercus rotundifolia f. calicina","Quercus ilex f. macrocarpa","Quercus rotundifolia f. brevicupulata","Quercus rotundifolia var. macrocarpa","Quercus ilex var. brevicupulata","Quercus ilex subsp. ballota","Quercus ilex var. dolichocalyx","Quercus rotundifolia var. pilosella","Quercus rotundifolia var. brevicupulata","Quercus rotundifolia subsp. maghrebiana"],"genus":"Quercus","family":"Fagaceae","links":{"self":"/api/v1/species/quercus-rotundifolia","plant":"/api/v1/plants/quercus-rotundifolia","genus":"/api/v1/genus/quercus"}}
... cut off
Result 2
$ node get-option2.js
{"id":77116,"common_name":"Evergreen oak","slug":"quercus-rotundifolia","scientific_name":"Quercus rotundifolia","year":1785,"bibliography":"Encycl. 1: 723 (1785)","author":"Lam.","status":"accepted","rank":"species","family_common_name":null,"genus_id":3519,"image_url":"https://d2seqvvyy3b8p2.cloudfront.net/40ab8e7cdddbe3e78a581b84efa4e893.jpg","synonyms":["Quercus ilex var. oleoides","Quercus ilex subvar. rotundifolia","Quercus ilex f. macrophylla","Quercus ilex f. oleoides","Quercus ilex var. calicina","Quercus ilex subsp. rotundifolia","Quercus lyauteyi","Quercus ballota var. rotundifolia","Quercus ilex f. brevicupulata","Quercus ilex subvar. major","Quercus ilex var. pendula","Quercus rotundifolia f. dolichocalyx","Quercus calicina","Quercus rotundifolia f. pilosella","Quercus rotundifolia f. macrocarpa","Quercus ilex var. rotundifolia","Quercus sugaro","Quercus ilex subvar. pendula","Quercus ilex f. pendula","Quercus ilex f. ballota","Quercus ilex f. rotundifolia","Quercus ilex subvar. minor","Quercus ballota","Quercus ilex var. ballota","Quercus ilex f. calicina","Quercus ilex var. microcarpa","Quercus rotundifolia f. calicina","Quercus ilex f. macrocarpa","Quercus rotundifolia f. brevicupulata","Quercus rotundifolia var. macrocarpa","Quercus ilex var. brevicupulata","Quercus ilex subsp. ballota","Quercus ilex var. dolichocalyx","Quercus rotundifolia var. pilosella","Quercus rotundifolia var. brevicupulata","Quercus rotundifolia subsp. maghrebiana"],"genus":"Quercus","family":"Fagaceae","links":{"self":"/api/v1/species/quercus-rotundifolia","plant":"/api/v1/plants/quercus-rotundifolia","genus":"/api/v1/genus/quercus"}}
... cut off
Is someone could take a time to explain me why my code does not work ?
const axiosInstance = axios.create({
baseURL : `https://trefle.io/api/v1/plants?token=${token}`,
})
actions:{
async getPlantsList(context)
{
try{
console.log(axiosInstance);
const response = await axiosInstance.get();
console.log('2', response.data);
context.commit();
} catch(error){
console.log('error', error);
}
}
Answer
With Vuejs 3
On vite.config.js file in root.
You have to add this code
server:{
proxy:{
'/api':{
target: 'https://trefle.io',
changeOrigin: true
}
}
https://vitejs.dev/config/server-options.html
Thanks for helping me
Related
I have a model.json generated from tensorflow via tensorflow.js coverter
In the original implementation of model in tensorflow in python, it is built like this:
model = models.Sequential([
base_model,
layers.Dropout(0.2),
layers.Flatten(),
layers.Dense(128, activation='relu'),
layers.Dense(num_classes)
])
In tensorflow, the probability can be generated by score = tf.nn.softmax(predictions[0]), according to the tutorial on official website.
How do I get this probability in tensorflow.js?
I have copied the codes template as below:
$("#predict-button").click(async function () {
if (!modelLoaded) { alert("The model must be loaded first"); return; }
if (!imageLoaded) { alert("Please select an image first"); return; }
let image = $('#selected-image').get(0);
// Pre-process the image
console.log( "Loading image..." );
let tensor = tf.browser.fromPixels(image, 3)
.resizeNearestNeighbor([224, 224]) // change the image size
.expandDims()
.toFloat()
// RGB -> BGR
let predictions = await model.predict(tensor).data();
console.log(predictions);
let top5 = Array.from(predictions)
.map(function (p, i) { // this is Array.map
return {
probability: p,
className: TARGET_CLASSES[i] // we are selecting the value from the obj
};
}).sort(function (a, b) {
return b.probability - a.probability;
}).slice(0, 2);
console.log(top5);
$("#prediction-list").empty();
top5.forEach(function (p) {
$("#prediction-list").append(`<li>${p.className}: ${p.probability.toFixed(6)}</li>`);
});
How should I modify the above code?
The output is just the same as the value of variable 'predictions':
Float32Array(5)
0: -2.5525975227355957
1: 7.398464679718018
2: -3.252196788787842
3: 4.710395812988281
4: -4.636396408081055
buffer: (...)
byteLength: (...)
byteOffset: (...)
length: (...)
Symbol(Symbol.toStringTag): (...)
__proto__: TypedArray
0: {probability: 7.398464679718018, className: "Sunflower"}
1: {probability: 4.710395812988281, className: "Rose"}
length: 2
__proto__: Array(0)
Please help!!!
Thanks!
In order to extract the probabilities from the logits of the model using a softmax function you can do the following:
This is the array of logits that are also the predictions you get from the model
const logits = [-2.5525975227355957, 7.398464679718018, -3.252196788787842, 4.710395812988281, -4.636396408081055]
You can call tf.softmax() on the array of values
const probabilities = tf.softmax(logits)
Result:
[0.0000446, 0.9362511, 0.0000222, 0.0636765, 0.0000056]
Then if you wanted to get the index with the highest probability you can make use of tf.argMax():
const results = tf.argMax(probabilities).dataSync()[0]
Result:
1
Edit
I am not too familiar with jQuery so this might not be correct. But here is how I would get the probabilities of the outputs in descending order:
let probabilities = tf.softmax(predictions).dataSync();
$("#prediction-list").empty();
probabilities.forEach(function(p, i) {
$("#prediction-list").append(
`<li>${TARGET_CLASSES[i]}: ${p.toFixed(6)}</li>`
);
});
my environment:
ubuntu 18.04
rtx 2080ti
cuda 10.1
node v12.16.3
tfjs 1.7.4
the saved_model is efficientdet-d0,
and the step of inference is in inference step
for parsing image data with js,i convert img.png to img.jpg,and the result of saved_model is same with saved_model result
the command convert saved_model to tfjs_graph_model is
tensorflowjs_converter --input_format=tf_saved_model /tmp/saved_model ~/DATA/http_models/specDetection/
and my test code is
var tfc = require("#tensorflow/tfjs-converter");
var tf = require("#tensorflow/tfjs-core");
var jpeg_js = require("jpeg-js");
var fs = require("fs");
async function loadModel() {
var modelUrl = "http://localhost:8000/model.json"
var model = await tfc.loadGraphModel(modelUrl);
return model;
}
async function detect() {
var model = await loadModel();
var img = fs.readFileSync("~/SRC/automl_test/efficientdet/img.jpg");
const input = jpeg_js.decode(img,{useTArray:true,formatAsRGBA:false});
const batched = tf.tidy(() => {
const img = tf.browser.fromPixels(input);
// Reshape to a single-element batch so we can pass it to executeAsync.
return img.expandDims(0);
});
const result = await model.executeAsync({'image_arrays:0':batched},['detections:0']);
console.log(result);
}
detect();
when detect object in img.jpg with my test code,nothing detected --- the size of result is 0
what do i do to sovle this problem?
thanks for any cue
edit:
code 1:
var img = fs.readFileSync("~/DATA/http_models/specDetection/test.jpg");
var dataJpegJs = jpeg_js.decode(img,{useTArray:true,formatAsRGBA:false})
var batched = tf.browser.fromPixels({data:dataJpegJs.data, width: dataJpegJs.width, height:dataJpegJs.height},3);
batched = batched.slice([0,0,0],[-1,-1,3]);
var result = await model.executeAsync({'image_arrays:0':batched.expandDims(0)},['detections:0']);
result = tf.slice(result,[0,0,1],[1,-1,4]);
code 2:
var img = fs.readFileSync("~/DATA/http_models/specDetection/test.jpg");
var dataJpegJs = jpeg_js.decode(img,{useTArray:true,formatAsRGBA:true})
var batched = tf.browser.fromPixels({data:dataJpegJs.data, width: dataJpegJs.width, height:dataJpegJs.height},4);
batched = batched.slice([0,0,0],[-1,-1,3]);
var result = await model.executeAsync({'image_arrays:0':batched.expandDims(0)},['detections:0']);
result = tf.slice(result,[0,0,1],[1,-1,4]);
code 1 got a bad result and code 2 got a correct result.
code 2 decode jpg with formatAsRGBA:true,and set numChannels=4 in tf.browser.fromPixels. jpeg-js must decode jpg to RGBA to work correctly.
i think it is a bug of jpeg-js.or i am not familiar with jpg encoding?
The tensor is not well generated. fromPixels is mostly used to get a tensor from an htmlImageElement. Printing a summary of the tensor and compare it with the one generated for python can suffice to tell that.
Is there an issue with jpeg-js ?
First we need to know how the imageData works. An image Data pixel is a 4 numerical values R, G, B, A. When using the data decoded by jpeg_js.decode as argument of tf.browser.fromPixel with 3 channels (formatAsRGBA:false), it is considered as an image data. Let's consider the data [a, b, c, d, e, f] = jpeg_js.decode("path", {formatAsRGBA:false}) and the tensor t created from it
t = tf.browser.fromPixels({data, width: 2, height: 1}). How it is interpreted ? tf.browser.fromPixels, will create an ImageDate of height: 1 and of width: 2. Consequently, the imageData will be of size 1 * 2 * 4 (instead of 1 * 2 * 3) and has all its values set to 0. Then it will copy the data decoded to the imageData. So imageData = [a, b, c, d, e, f, 0, 0].
As a result, the slice (t.slice([0, 0, 0], [-1, -1, 3]) will be [a, b, c, e, f, 0].
Neither is jpeg_js the issue, nor tf.browser.fromPixels. This is how imageData works
What can be done ?
keep the alpha channel of the decoded image formatAsRGBA:true
Instead of using tf.browser.fromPixels, use directly tf.tensor to create the tensor
const img = tf.tensor(input.data, [input.height, input.width, 3])
Another option is to usetensorflow-node. And tf.node.decodeImage can decode an image from a tensor.
const img = fs.readFileSync("path/of/image");
const tensor = tf.node.decodeImage(img)
// use the tensor for prediction
Unlike jpeg-js that works only for image in jpeg encoding format, it can decode a wider range of images
I was trying to get a variable I created in a simple function but I keep getting errors. I am doing:
x = tf.get_variable('quadratic/x')
but the python complains as follow:
python qm_tb_scopes.py
quadratic/x:0
Traceback (most recent call last):
File "qm_tb_scopes.py", line 24, in <module>
x = tf.get_variable('quadratic/x')
File "/Users/my_username/path/tensor_flow_experiments/venv/lib/python2.7/site-packages/tensorflow/python/ops/variable_scope.py", line 732, in get_variable
partitioner=partitioner, validate_shape=validate_shape)
File "/Users/my_username/path/tensor_flow_experiments/venv/lib/python2.7/site-packages/tensorflow/python/ops/variable_scope.py", line 596, in get_variable
partitioner=partitioner, validate_shape=validate_shape)
File "/Users/my_username/path/tensor_flow_experiments/venv/lib/python2.7/site-packages/tensorflow/python/ops/variable_scope.py", line 161, in get_variable
caching_device=caching_device, validate_shape=validate_shape)
File "/Users/my_username/path/tensor_flow_experiments/venv/lib/python2.7/site-packages/tensorflow/python/ops/variable_scope.py", line 457, in _get_single_variable
"but instead was %s." % (name, shape))
ValueError: Shape of a new variable (quadratic/x) must be fully defined, but instead was <unknown>.
it seems its trying to create a new variable, but I am simply trying to get a defined one. Why is it doing this?
The whole code is:
import tensorflow as tf
def get_quaratic():
# x variable
with tf.variable_scope('quadratic'):
x = tf.Variable(10.0,name='x')
# b placeholder (simualtes the "data" part of the training)
b = tf.placeholder(tf.float32,name='b')
# make model (1/2)(x-b)^2
xx_b = 0.5*tf.pow(x-b,2)
y=xx_b
return y,x
y,x = get_quaratic()
learning_rate = 1.0
# get optimizer
opt = tf.train.GradientDescentOptimizer(learning_rate)
# gradient variable list = [ (gradient,variable) ]
print x.name
x = tf.get_variable('quadratic/x')
x = tf.get_variable(x.name)
You need to pass the option reuse=True to tf.variable_scope() if you want to get the same variable twice.
See the documentation (https://www.tensorflow.org/versions/r0.9/how_tos/variable_scope/index.html)
for more details.
Alternatively, you could get the variable once, outside your Python function, and pass it in as a argument in Python. I find that a bit cleaner since it makes it explicit what variables the code uses.
I hope that helps!
This is not the best solution, but try creating the variable through tf.get_variable() with reuse=False to ensure a new variable is created. Then, when obtaining the variable, use tf.get_variable() with reuse=True to get the current variable. Setting reuse to tf.AUTO_REUSE risks the creation of a new variable if the exact var is not present. Also make sure to specify the shape of the variable in tf.get_variable().
import tensorflow as tf
def get_quaratic():
# x variable
with tf.variable_scope('quadratic', reuse=False):
x = tf.get_variable('x', ())
tf.assign(x, 10)
# b placeholder (simualtes the "data" part of the training)
b = tf.placeholder(tf.float32,name='b')
# make model (1/2)(x-b)^2
xx_b = 0.5*tf.pow(x-b,2)
y=xx_b
return y,x
y,x = get_quaratic()
learning_rate = 1.0
# get optimizer
opt = tf.train.GradientDescentOptimizer(learning_rate)
# gradient variable list = [ (gradient,variable) ]
print (x.name)
with tf.variable_scope('', reuse=True):
x = tf.get_variable('quadratic/x', shape=())
print(tf.global_variables()) # there is only 1 variable
with tf.name_scope('hidden4'):
weights = tf.Variable(tf.convert_to_tensor(weights4))
biases = tf.Variable(tf.convert_to_tensor(biases4))
hidden4 = tf.sigmoid(tf.matmul(hidden3, weights) + biases)
I want to ues tf.get_variable to get the variable hidden4/weights defined as above, but failed as below:
hidden4weights = tf.get_variable("hidden4/weights:0")
*** ValueError: Variable hidden4/weights:0 already exists, disallowed. Did you mean to set reuse=True in VarScope? Originally defined at:
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/pdb.py", line 234, in default
exec code in globals, locals
File "/usr/local/lib/python2.7/cmd.py", line 220, in onecmd
return self.default(line)
Then I try hidden4/weights.eval (sess), but it also failed.
(Pdb) hidden4/weights.eval(sess)
*** NameError: name 'hidden4' is not defined
tf.name_scope() is used to visualize variables.
tf.name_scope(name)
Wrapper for Graph.name_scope() using the default graph.
What I think you are looking for is tf.variable_scope():
Variable Scope mechanism in TensorFlow consists of 2 main functions:
tf.get_variable(, , ): Creates or returns a variable with a given name.
tf.variable_scope(): Manages namespaces for names passed to tf.get_variable().
with tf.variable_scope('hidden4'):
# No variable in this scope with name exists, so it creates the variable
weights = tf.get_variable("weights", <shape>, tf.convert_to_tensor(weights4)) # Shape of a new variable (hidden4/weights) must be fully defined
biases = tf.get_variable("biases", <shape>, tf.convert_to_tensor(biases4)) # Shape of a new variable (hidden4/biases) must be fully defined
hidden4 = tf.sigmoid(tf.matmul(hidden3, weights) + biases)
with tf.variable_scope('hidden4', reuse=True):
hidden4weights = tf.get_variable("weights")
assert weights == hidden4weights
That should do it.
I have solved the problem above:
classifyerlayer_W=[v for v in tf.all_variables() if v.name == "softmax_linear/weights:0"][0] #find the variable by name "softmax_linear/weights:0"
init= numpy.random.randn(2048, 4382) # create a array you use to re-initial the variable
assign_op = classifyerlayer_W.assign(init) # create a assign operation
sess.run(assign_op) # run op to finish the assign
I am having a problem in initializing the following model in OpenBUGS
model
{
#likelihood
for (t in 1:n) { yisigma2[t] <- 1/exp(theta[t]);
y[t] ~ dnorm(0,yisigma2[t]);
}
#Priors
mu ~ dnorm(0,0.1);
phistar ~ dbeta(20,1.5);
itau2 ~ dgamma(2.5,0.025);
beta <- exp(mu/2);
phi <- 2*phistar-1;
tau <- sqrt(1/itau2);
theta0~dnorm(mu, itau2)
thmean[1] <- mu + phi*(theta0-mu);
theta[1] ~ dnorm(thmean[1],itau2);
for (t in 2:n) { thmean[t] <- mu + phi*(theta[t-1]-mu);
theta[t] ~ dnorm(thmean[t],itau2);
}
}
This is my data
list(y=c(-0.0383 , 0.0019 ,......-0.0094),n=945)
And this is the list of my initials
list(phistar= 0.98, mu=0, itau2=50)
The checking of model, loading of data and compilation steps are ok. When loading initials, OpenBUGS says initial values are loaded but chain contains uninitialized variables. I then tried to initialize theta0 also but the problem persists. Could someone please help me regarding this?
Thanks
Khalid
I am newbie at OpenBugs but shouldn't you be specifying a distribution for inits rather than a single point value? something like?
inits <- function(){ list(alpha=rnorm(1), beta=rnorm(1), sigma = rlnorm(1))}