I tried to implement parameter initialization and got the error message:
import numpy as np
def initialize_with_zeros(dim):
w = np.zeros(dim, 1)
b = 0
return w, b
dim = 2
initialize_with_zeros(dim)
Here is the Error:
TypeError Traceback (most recent call
last) in ()
5
6 dim = 2
----> 7 initialize_with_zeros(dim)
in initialize_with_zeros(dim)
1 def initialize_with_zeros(dim):
----> 2 w = np.zeros(dim, 1)
3 b = 0
4 return w, b
5
TypeError: data type not understood
np.zeros takes only the shape as a tuple or a single integer (in case of 1-d arrays). If you just need a 1 dimensional array, pass a single parameter. If you need a 2d-array, pass as a tuple (dim,1). Hence, depending on what you want, either use
w = np.zeros(dim)
which will give you a one dimensional array of zeros
or use
w = np.zeros((dim, 1))
which will give you a two dimensional array with dim number of rows and 1 column.
From the official docs
numpy.zeros(shape, dtype=float, order='C')
Parameters:
shape : int or tuple of ints Shape of the new array, e.g., (2, 3) or 2.
Initializing parameters with zeros:
# GRADED FUNCTION: initialize_with_zeros
import numpy as np
def initialize_with_zeros(dim):
w = np.zeros([dim, 1])
b = 0
return w, b
dim = 2
w,b=initialize_with_zeros(dim)
print ("w = " + str(w))
print ("b = " + str(b))
Related
Suppose I have the 2 arrays below:
a = tf.constant([1,2,3])
b = tf.constant([10,20,30])
How can we concatenate them using Tensorflow's methods, such that the new array is created by doing intervals of taking 1 number from each array one at a time? (Is there already a function that can do this?)
For example, the desired result for the 2 arrays is:
[1,10,2,20,3,30]
Methods with tf.concat just puts array b after array a.
a = tf.constant([1,2,3])
b = tf.constant([10,20,30])
c = tf.stack([a,b]) #combine a,b as a matrix
d = tf.transpose(c) #transpose matrix to get the right order
e = tf.reshape(d, [-1]) #reshape to 1-d tensor
You could also try using tf.tensor_scatter_nd_update:
import tensorflow as tf
a = tf.constant([1,2,3])
b = tf.constant([10,20,30])
shape = tf.shape(a)[0] + tf.shape(b)[0]
c = tf.tensor_scatter_nd_update(tf.zeros(shape, dtype=tf.int32),
tf.expand_dims(tf.concat([tf.range(start=0, limit=shape, delta=2), tf.range(start=1, limit=shape, delta=2) ], axis=0), axis=-1),
tf.concat([a, b], axis=0))
# tf.Tensor([ 1 10 2 20 3 30], shape=(6,), dtype=int32)
How can I convert a sympy expression to numpy code? For example, say I this was the code for the expression:
expression = 2 * x/y + 10 * sympy.exp(x) # Assuming that x and y are predefined from sympy.symbols
I would want to go from expression to this:
np_expression = "np.dot(2, np.dot(x, np.linalg.pinv(y))) + np.dot(10, np.exp(x))"
Note that x and y are matrices, but we can assume the shapes will match
An example with real numbers would go like this:
a = np.array([1,2],[3,4])
b = np.array([5,6],[7,8])
expression = 2 * a/b + 10 # These would be sympy symbols rather than numbers
and the result would be this:
np_expression = "np.dot(2, np.dot(5, np.linalg.pinv(9))) + 10"
In [1]: expr = 2 *x/y + 10 * exp(x)
In [3]: f = lambdify((x,y), expr)
In [4]: help(f)
_lambdifygenerated(x, y)
Created with lambdify. Signature:
func(x, y)
Expression:
2*x/y + 10*exp(x)
Source code:
def _lambdifygenerated(x, y):
return 2*x/y + 10*exp(x)
Which for specific inputs, array or otherwise:
In [5]: f(np.arange(1,5)[:,None], np.arange(1,4))
Out[5]:
array([[ 29.18281828, 28.18281828, 27.84948495],
[ 77.89056099, 75.89056099, 75.22389432],
[206.85536923, 203.85536923, 202.85536923],
[553.98150033, 549.98150033, 548.648167 ]])
In [6]: f(1,1)
Out[6]: 29.18281828459045
In [7]: f(2,3)
Out[7]: 75.22389432263984
In [8]: f(np.arange(1,4),np.arange(1,4))
Out[8]: array([ 29.18281828, 75.89056099, 202.85536923])
Normal array broadcasting rules apply. Note that x/y is element-wise. I'm not sure what lambdify will translate into dot and inv code.
trying your numpy code:
In [9]: np.dot(2, np.dot(2,np.linalg.pinv(3)))+10*np.exp(2)
---------------------------------------------------------------------------
LinAlgError Traceback (most recent call last)
<ipython-input-9-6cae91f0e0f8> in <module>
----> 1 np.dot(2, np.dot(2,np.linalg.pinv(3)))+10*np.exp(2)
....
LinAlgError: 0-dimensional array given. Array must be at least two-dimensional
We have to change the y into a 2d array, e.g. [[3]]:
In [10]: np.dot(2, np.dot(2,np.linalg.pinv([[3]])))+10*np.exp(2)
Out[10]: array([[75.22389432]])
I am trying to load columns 1 to 15 of the data.txt file into array X and column 16 into array y, and normalize all 15 columns in X in the for loop and array y in a single statement. Loading is working properly, but after trying to print results of normalization I get this error:
TypeError: 'tuple' object cannot be interpreted as an integer
Please help, the code is being done in python in the Jupyter notebook.
import numpy as np
import matplotlib.pyplot as plt
data = np.loadtxt('data.txt')
X = np.array(data[:, 1:16])
y = np.array(data[:, 16], ndmin=2).T
n = X.shape
for i in range(n):
X[:, i] = (X[:, i]-np.min(X[:, i])) / (np.max(X[:, i])-np.min(X[:, i]))
y = ( y-np.min(y) ) / ( np.max(y)-np.min(y) )
print(X)
print(y)
The problem is probably in the loop row for i in range(n):
n is X shape, its a tuple, range needs integer as parameter.
Code example of your case:
n = (2,4)
for i in range(n):
print(i)
Error:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-277-3834a67eeb55> in <module>
1 n = (2,4)
----> 2 for i in range(n):
3 print(i)
TypeError: 'tuple' object cannot be interpreted as an integer
In your case, I think you want to iterate over columns, so n = X.shape[1] will fix it.
The input X to my network has the shape (10, 1, 5, 4). I am interested in boxplotting the distribution of input features (four), for each class. So, for example:
X = np.random.randn(10, 1, 5, 4)
a = np.zeros(5, dtype=int)
b = np.ones(5, dtype=int)
y = np.hstack((a,b))
print(X.shape)
print(y.shape)
(10, 1, 5, 4)
(10,)
Then I separate the input Xinto respective classes, like:
class0, class1 =[],[]
for i in range(len(y)):
if y[i]==0:
class0.append(X[i])
else:
class1.append(X[i])
class0 = np.array(class0)
class1 = np.array(class1)
Taking class0into consideration, I can go ahead to manipulate it in a way that the four features are arranged per column (col1, col2,col3,col4) this way.
def transformer(myclass):
#reshape the class
k = myclass.transpose((0,1,3,2))
#access individual feature
s = k[0][:,0].reshape(-1,1)
a = k[0][:,1].reshape(-1,1)
j = k[0][:, 2].reshape(-1,1)
b = k[0][:, 3].reshape(-1,1)
rslt = [s,a,j,b]
return rslt
Then plot the features:
sns.boxplot(data=transformer(class0))
This is the general idea of my workflow. Note that the function transformer is hardcoded to access only the first observation (element) of the class it takes as input.
Question: How to I do modify my function to access all observations of the class, not per every single example, for generalised. Such that col1are all features in the class that are in first column for each example.
Do write the following:
def mytransformer(myclass):
#first, transpose class
k = myclass.transpose((0,1,3,2))
#speed
for i in range(k):
s = k[i][:,0].reshape(-1,1)
return s
Which gives the error:
mytransformer(class0)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-15-5451e55f03d9> in <module>()
----> 1 mytransformer(class0)
<ipython-input-14-d1a2c8098caf> in mytransformer(myclass)
3 myclass = myclass.transpose((0,1,3,2))
4 #speed
----> 5 for i in range(myclass):
6 s = k[i][:,0].reshape(-1,1)
7 return s
TypeError: only integer scalar arrays can be converted to a scalar index
Is there a way to add legend to the boxplot so that I can give name to each feature?
For your Question 1, You are using for loop range with a NumPy array which instead should have argument as an integer.
Maybe it is,
for i in range(len(k)):
I'm trying to add a numpy array to another numpy array, but I'm getting this error:
ValueError: could not broadcast input array from shape (28) into shape (28,0)
This is my code:
sample = np.fabs(sample - avg)
counter = np.arange(1,len(sample)+1)
np.append(sample, counter, axis=1)
How can I fix this?
This indicates that the array with shape (28,0) is in fact empty, which means you might need to address your upstream processing that generated sample and avg, and verify the contents of these objects. I could replicate this with the following:
import numpy as np
from numpy import random
a = random.rand(28)
b = random.random((28,0))
print(a.shape, b.shape)
(28,) (28, 0)
print(a + b)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-16-f1c1de818ef8> in <module>()
5 print(a.shape, b.shape)
6
----> 7 print(a + b)
8
9 print(b)
ValueError: operands could not be broadcast together with shapes (28,) (28,0)
print(b)
[]