I am trying to calculate and optimize a loss with TFQ and cirq. Using tfq.layers.State()
to work with statevector instead of its observables. But when I try to fit o get its gradient the following error appears:
with tf.GradientTape() as tape:
y_pred = qnet(x_train, training=True)
loss = tf.keras.losses.categorical_crossentropy(y_pred, y_train)
gradients = tape.gradient(loss, qnet.trainable_variables)
qnet.optimizer.apply_gradients(zip(gradients, qnet.trainable_variables))
gradients
LookupError: gradient registry has no entry for: TfqSimulateState
tfq.differentiators.ForwardDifference let us to do this but no exist for tfq.layers.State().
thanks!
Related
I am currently working on a project where I detect a face with a haar cascade classifier.
In the code, I have created Rois with a cv2 rectangle and the goal is to apply images to the ROI. On some images the code works on others it doesn´t, also applying filters doesn´t work on videos or on my webcam.
The Error Code:
ValueError:
could not broadcast input array from the shape (50,70,3) into shape
(50,2,3)
Here are some code lines that may be important:
#Reading the image
image = file dialog.askopenfilename(initialdir="/Pictures", title="select a file", filetypes=(("png files", ".jpg", ),("all file", ".*")))
img = cv2.imread(image)
gray = np.array(img)
How the Roi is created and the filter applied.
visual_eye_r = cv2.rectangle(grayef, (x,y), (x+w, y+h), (255, 255, 255, 0), )
ROI_2 = visual_eye_r[y:y+h, x:x+w]
imagefilter = cv2.imread("filter.png")
roi_h, roi_w = ROI_2.shape[:2]
image_h, image_w = imagefilter.shape[:2]
#Calculate height and width offsets
height_off = int((roi_h - image_h)/2)
width_off = int((roi_w - image_w)/2)
#Mit Numpy Slicing Bild überlegen
ROI_2[height_off:height_off+image_h, width_off:width_off+image_w] = image8
Have already looked elsewhere for the same issue but none of the fixes worked. Maybe someone can help me understand or fix the issue, because i am relative new to python.
Issue has been fixed. Realised that the height and width offset was negative, because of the size of some Region of Interests. That was what caused the error.
#I'm trying to do a taste wheel, like the Meilgaard wheel.
I'm not trying to do anything complex I only want to plot together a pie chart and a PCA plot.
I would like to have the piechart bigger than the PCA graph.
I would like to plot the pie graph with both the two PCA graphs or with the fviz_pca_biplot.
The following is the PCA:
principal4<-PCA(ExpertWine2,scale.unit = T,ind.sup = NULL,quanti.sup =29:30,quali.sup =1,graph = T,axes = c(1,2),ncp = 3)
fviz_pca_biplot(principal4)
The following is the pie chart:
slices <- c(10, 10, 10, 10)
lbls <- c("acidity", "freshness", "sweetness", "corposity")
coloris = c("gold", "cyan", "indianred1", "burlywood4")
cake=pie(slices, labels = lbls, init.angle=45, main="Pie Chart of tastes",col=coloris)
There are multiple packages aimed at solving this. It will depend on whether you as using a base r plotting implementation or something like ggplot.
I would reccomend looking at bentobox (strict positioning), patchwork (auto positioning) and cowplot (somewhere in the middle). Patchwork is primarily aimed at ggplot but the other two should work with any plotting method.
bento box:
https://github.com/PhanstielLab/BentoBox
patchwork:
https://patchwork.data-imaginist.com/
cowplot:
https://cran.r-project.org/web/packages/cowplot/vignettes/introduction.html
I get following exception when using Entity Framework to get data from bounds from a google map:
FormatException: 24201: Latitude values must be between -90 and 90 degrees.
POLYGON((81.9882716924738 140.187434563007,21.5587046599696 140.187434563007,21.5587046599696 -40.1641279369925,81.9882716924738 -40.1641279369925,81.9882716924738 140.187434563007))
I can see other have same problem, but havent found anything that solves this. I would expect that first coordinate for point is the latitude and second for longitude? And none is above 90 so why do I get this error? I tried swapping lat and lng but with same problem.
This is the failing line:
var poly = FindByBoundingBox(northEastLat, northEastLng, southWestLat, southWestLng);
DbGeography polygon = DbGeography.FromText(poly, 4326);
var parksWithinPolygon = dbCtx.SiteList.Where(p =>
p.PolygonCenter.Intersects(polygon)).Select(p=>p.SiteName).ToList();
As Damien states first problem is that Sql server expects longitude first and then lattitude. This throws another error, redirecting to another problem:
"This operation cannot be completed because the instance is not valid".
My best bet is it's the they way/order I build the polygon. Has anyone succeeded in mapping google bounds to a polygon in SQL server? In short I am trying to get any data (data has a point column) within the google map bounds.
The function to calculate polygon is listed below:
public string FindByBoundingBox(double northEastLat, double northEastLng, double southWestLat, double southWestLng)
{ //Create poylgon of bounding box
System.Globalization.CultureInfo customCulture = (System.Globalization.CultureInfo)System.Threading.Thread.CurrentThread.CurrentCulture.Clone();
customCulture.NumberFormat.NumberDecimalSeparator = ".";
System.Threading.Thread.CurrentThread.CurrentCulture = customCulture;
var bboxWKT = string.Format("POLYGON(({1} {0},{1} {2},{3} {2},{3} {0},{1} {0}))", northEastLat, northEastLng, southWestLat, southWestLng);
return bboxWKT;
}
OK i figured it out. As Damien stated the order of coordinates is oppesite of google. In SQL long needs to be first. Next thing is what is the "left hand rule". You need to create your polygon starting from lower left corner and then counter clock wise.
How I can create interactive R plots in Power BI (for example Plotly)? Below code doesn't return any error, but also doesn't show chart:
library(plotly)
library(ggplot2)
z = ggplot(data = dataset) + geom_point(mapping = aes(x = Console, y = Search))
ggplotly(z)
Data source:
source <- "https://cdn.rawgit.com/BlueGranite/Microsoft-R-Resources/master/power-bi/gameconsole.csv"
game.console <- read.csv(source, header = TRUE)
According to this question in Power BI's Community forums
Plotly lib is supported as part of HTML support for R powered Custom
Visuals only, not R Visuals in general currently.
Plotly can only be used if it produces an IMAGE\PNG for R visuals in
PBI. Not HTML.
For Custom Visuals we have an upcoming feature which will also enable R-based custom visuals to render as htmls.
Hope this helps.
The reason is that right now Power BI only supports render charts created by R visualization component as PNG.
Try the following:
p <- plot_ly(x = dataset$period, y = dataset$mean, name = "spline", line = list(shape = "spline"))
plotly_IMAGE(p, format = "png", out_file = "out.png")
But the problem with this is that, though rendered by plotly, the visualizations will not be interactive since its just a PNG image.
If you want to create interactive visualizations using plotly. The only way you can do is to create a custom Power BI visualization and import it to your report. See this post for a good introduction.
PowerBI only supports charts rendered as PNG while plotly format is in HTML. You can try to save the chart as PNG then print it in the R console inside PowerBI.
You first have to register a plotly account here.
After registration, on the top right corner arrow next to your account name and click on Settings -> API keys. You will be able to generate API key. Copy and paste your username and API key using this code.
Sys.setenv("plotly_username"="....")
Sys.setenv("plotly_api_key"=".....")
Then add this code in to turn the plot into png format and print it out.
fig <- plot_ly(x = dataset$Console, y = dataset$Search)
Png <- plotly_IMAGE(fig, out_file = "plotly-test-image.png")
print(Png)
As mentioned in another answer, this plot won't be interactive as plot in PowerBI. To create an interactive plot in PowerBI, you have to create a custom visual. Follow an R custom visual example here or radacad example here.
I use code like the example below to do basic plotting of a list of values from F# Interactive. When plotting more points, the time taken to display increases dramatically. In the examples below, 10^4 points display in 4 seconds whereas 4.10^4 points take a patience-testing 53 seconds to display. Overall it's roughly as if the time to plot N points is in N^2.
The result is that I'll probably add an interpolation layer in front of this code, but
1) I wonder if someone who knows the workings of FSharpChart and Windows.Forms could explain what is causing this behaviour? (The data is bounded so one thing that seems to rule out is the display needing to adjust scale.)
2)Is there a simple remedy other than interpolating the data myself?
let plotl (f:float list) =
let chart = FSharpChart.Line(f, Name = "")
|> FSharpChart.WithSeries.Style(Color = System.Drawing.Color.Red, BorderWidth = 2)
let form = new Form(Visible = true, TopMost = true, Width = 700, Height = 500)
let ctl = new ChartControl(chart, Dock = DockStyle.Fill)
form.Controls.Add(ctl)
let z1 = [for i in 1 .. 10000 do yield sin(float(i * i))]
let z2 = [for i in 1 .. 20000 do yield sin(float(i * i))]
plotl z1
plotl z2
First of all, FSharpChart is a name used in an older version of the library. The latest version is called F# Charting, comes with a new documentation and uses just Chart.
To answer your question, Chart.Line and Chart.Points are quite slow for large number of points. The library also has Chart.FastLine and Chart.FastPoints (which do not support as many features, but are faster). So, try getting the latest version of F# Charting and using the "Fast" version of the method.