Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
train = 'C:\ProgramData\Anaconda3\animal train'
test = 'C:\ProgramData\Anaconda3\animal test'
lr = 0.001
def label_image(img):
word_label = img.split('.')[-3]
if word_label == "cat": return [1,0]
elif word_label == "dog": return [0,1]
def create_train_data():
training_data = []
for img in tqdm(os.listdir(train)):
label = label_img(img)
path = os.path.join(train,img)
img = cv2.resize(cv2.imread(path,cv2.IMREAD_GRAYSCALE),(50,50))
training_data.append([np.array(img), np.array(label)])
shuffle(training_data)
return(training_data)
I am new to tensorflow and this is my first project ( Cat vs Dog Image Classification)
Can you please explain each line in detail what is create_train_data() function actually doing?
Image reading in OpenCV goes as follows
img = cv2.imread("path/to/image", flags)
Now "path/to/image" is either your working directory or absolute path.
path = os.path.join(train,img) in your code is creating absolute path. I think since you are in working directory, just directly reading image also should work in this case.
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
I have made a GUI using using Qt Designer running in python here
How do I add code to my project to add a checkbox that locks (have their values changed together whatever they may be. 0 - 100 range) both my Qsliders together. See picture below.
Please feel free to ask if more info is needed.
You would connect each slider's valueChanged signal to the other's setValue slot when the checkbox is checked, and disconnect when unchecked.
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
class Template(QWidget):
def __init__(self):
super().__init__()
vbox = QVBoxLayout(self)
vbox.addWidget(QSlider(Qt.Horizontal))
vbox.addWidget(QCheckBox('Lock', toggled=self.toggleLocked))
vbox.addWidget(QSlider(Qt.Horizontal))
def toggleLocked(self, state):
s1, s2 = self.findChildren(QSlider)
if state:
s2.setValue(s1.value())
s1.valueChanged[int].connect(s2.setValue)
s2.valueChanged[int].connect(s1.setValue)
else:
s1.valueChanged[int].disconnect()
s2.valueChanged[int].disconnect()
if __name__ == '__main__':
app = QApplication(sys.argv)
window = Template()
window.show()
sys.exit(app.exec_())
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I need a replacement for the tf.browser.toPixels() tensorflowJS function. Trying to port some code to python and I'm wondering if there is a quick way around this.
In the browser this gets really simple and we just callback new frames and draw into a canvas. But in python development, say in matplotlib or tkinter, I guess I'm gonna need some tricks.
Is there a (not super big) solution for this?
Thanks
Let say you are having a 2D tensor img which run it in your browser like tf.browser.toPixels(img). You can draw similar images using OpenCV and matplotlib like:
Using Pytorch
import matplotlib.pyplot as plt
# If your data is in GPU:
img_np = img.cpu().numpy()
# Using OpenCV
cv2.imwrite(img_np.astype(np.uint8), "image.png")
# Using matplotlib
plt.imshow(img_np)
Tensorflow
```python
import matplotlib.pyplot as plt
img_np = img.numpy()
# Using OpenCV
cv2.imwrite(img_np.astype(np.uint8), "image.png")
# Using matplotlib
plt.imshow(img_np)
Also, if you have a 3D tensor ( i.e. n x m x 3) you can still average the bands and make a 2D tensor out of it and plot them the same way.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I am figuring out how to use the np.polyfit function and the documentation confuses me. In particular, I am trying to perform linear regression and print related statistics like the sum of squared errors (SSE). Can someone provide clear and concise explanations, possibly with a minimal working example?
np.polyfit returns a tuple containing the coefficients parametrizing the best-fitting polynomial of degree deg. To fit a line, use deg = 1. You can return the residual (sum of squared errors) by passing full = True as an argument to polyfit. Note that with this argument, polyfit will also return some other information about the fit, which we can just discard.
Altogether, then, we have might have something like
import matplotlib.pyplot as plt
import numpy as np
# Generate some toy data.
x = np.random.rand(25)
y = 2 * x + 0.5 + np.random.normal(scale=0.05, size=x.size)
# Fit the trend line.
(m, b), (SSE,), *_ = np.polyfit(x, y, deg=1, full=True)
# Plot the original data.
plt.scatter(x, y, color='k')
# Plot the trend line.
line_x = np.linspace(0, 1, 200)
plt.plot(line_x, m * line_x + b, color='r')
plt.title(f'slope = {round(m, 3)}, int = {round(b, 3)}, SSE = {round(SSE, 3)}')
plt.show()
The *_ notation in the call to polyfit just tells Python to discard however many additional values are returned by the function. The documentation can tell you about these extra values if you're interested. We have to parse the SSE as a tuple (SSE,) because polyfit returns it as a singleton array. This code produces something like this plot.
You might also like to know about np.polyval, which will take tuples of polynomial coefficients and evaluate the corresponding function at input points.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
X axis contains 80 different variables. The green dots represent performance. The red/blue lines denote the increase/decrease in performance respectively. I was thinking of a box plot/scatter plot, but what I need I think is a combination of the two. Any help is appreciated.
I would make a scatter plot where the dot represents performance and the red/blue lines are represented as yerr.
import numpy as np
import matplotlib.pyplot as plt
y = [20, 30, 40]
x = np.arange(0,len(y), 1)
xlabel = ['airplane', 'apple', 'banana']
change = [-10,0,+3]
y_err,err_color = [],[]
for i in change:
if i < 0 :
y_err.append([[abs(i)],[0]])
err_color.append(['blue'])
else:
y_err.append([[0],[i]])
err_color.append(['red'])
for i in range(len(x)):
print(y_err[i])
plt.errorbar(x[i], y[i], yerr = y_err[i], color = 'green',fmt='.',ecolor =
err_color[i])
plt.xticks(x, xlabel,rotation = 'vertical')
plt.show()
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking us to recommend or find a tool, library or favorite off-site resource are off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead, describe the problem and what has been done so far to solve it.
Closed 8 years ago.
Improve this question
I have a theoretical distribution and I want to randomly sample in 2D space for the following distribution :
def p(z,m):
E = { 'ft':0.55, 'alpha': 2.99, 'z0':0.191, 'km':0.089, 'kt':0.25 }
S = { 'ft':0.39, 'alpha': 2.15, 'z0':0.121, 'km':0.093, 'kt':-0.175 }
I={ 'ft':0.06, 'alpha': 1.77, 'z0':0.045, 'km':0.096, 'kt':0.0 }
Evalue=E['ft']*np.exp(-1*E['kt']*(m-20))*z**E['alpha']*np.exp(-1*(z/(E['z0']+E['km']*(m-20)))**E['alpha'])
Svalue=S['ft']*np.exp(-1*S['kt']*(m-20))*z**S['alpha']*np.exp(-1*(z/(S['z0']+S['km']*(m-20)))**S['alpha'])
Ivalue=I['ft']*np.exp(-1*I['kt']*(m-20))*z**I['alpha']*np.exp(-1*(z/(I['z0']+I['km']*(m-20)))**I['alpha'])
value=Evalue+Svalue+Ivalue
return value
Update:
I figured out that inverse transform sampling is the appropriate approach to sample data from a probability distribution.
How could I program this method in python for 2D data or is there any library that I can use?
Take a look at Markov chain Monte Carlo (MCMC) methods. Basically you jump around the space of (z, m) points. From wherever you are, you always accept a jump that increases p(z, m). You accept a jump which decreases p(z, m) with some probability. There is a Python library PyMC to carry out that process.
If you want to randomly sample a value from p(z,m), then a simple way to implement this would be to use the 'random' module in python. I show the idea using numpy's version of random:
import numpy as np
import matplotlib.pyplot as plt
def p(z,m):
E = { 'ft':0.55, 'alpha': 2.99, 'z0':0.191, 'km':0.089, 'kt':0.25 }
S = { 'ft':0.39, 'alpha': 2.15, 'z0':0.121, 'km':0.093, 'kt':-0.175 }
I={ 'ft':0.06, 'alpha': 1.77, 'z0':0.045, 'km':0.096, 'kt':0.0 }
Evalue=E['ft']*np.exp(-1*E['kt']*(m-20))*z**E['alpha']*np.exp(-1*(z/(E['z0']+E['km']*(m-20)))**E['alpha'])
Svalue=S['ft']*np.exp(-1*S['kt']*(m-20))*z**S['alpha']*np.exp(-1*(z/(S['z0']+S['km']*(m-20)))**S['alpha'])
Ivalue=I['ft']*np.exp(-1*I['kt']*(m-20))*z**I['alpha']*np.exp(-1*(z/(I['z0']+I['km']*(m-20)))**I['alpha'])
value=Evalue+Svalue+Ivalue
return value
# Define the number of iterations you want for each variable
num_iter_m = 50
num_iter_z = 50
# I then set rand_m to go from 20 to 30, as your function fails for <20
rand_m = (np.random.random(num_iter_m)*10)+20
# z goes from the range 0 - 1
rand_z = (np.random.random(num_iter_z))
# Note, I am sampling from a uniform distribution for m and z. You can use more complicated functions, i.e., Gaussian/Normal shapes or even user defined.
rand_p = np.zeros((len(rand_z), len(rand_m)))
# Fill a grid with the random p(z,m) values
for i in range(len(rand_z)):
for j in range(len(rand_m)):
rand_p[i][j] = p(rand_z[i], rand_m[j])
# Plot
fig = plt.figure(0)
ax1 = fig.add_subplot(211)
ax1.scatter(rand_z, rand_m)
ax1.set_xlabel("z")
ax1.set_ylabel("m")
ax2 = fig.add_subplot(212)
cf = ax2.contourf(rand_z, rand_m, rand_p)
ax2.set_xlabel("z")
ax2.set_ylabel("m")
colbar = plt.colorbar(cf)
colbar.set_label("p(z,m)")
plt.show()
A specific module to use to it in a more sophisticated way would be, e.g., PyMC (
https://github.com/pymc-devs/pymc) or emcee (http://dan.iel.fm/emcee/current/).
If you wanted to sample z and m weighted by the 2D function p(z,m) this is a little more complicated.