Related
we all know the common approach to define a pipeline with a dimensionality reduction technique and then a model for training and testing. Then we can apply the GridSearchCv for hyperparameter tuning.
grid = GridSearchCV(
Pipeline([
('reduce_dim', PCA()),
('classify', RandomForestClassifier(n_jobs = -1))
]),
param_grid=[
{
'reduce_dim__n_components': range(0.7,0.9,0.1),
'classify__n_estimators': range(10,50,5),
'classify__max_features': ['auto', 0.2],
'classify__min_samples_leaf': [40,50,60],
'classify__criterion': ['gini', 'entropy']
}
],
cv=5, scoring='f1')
grid.fit(X,y)
I can understand the above code.
Now i was going through the documentation today and there i found one part code which is little bit strange.
pipe = Pipeline([
# the reduce_dim stage is populated by the param_grid
('reduce_dim', 'passthrough'), # How does this work??
('classify', LinearSVC(dual=False, max_iter=10000))
])
N_FEATURES_OPTIONS = [2, 4, 8]
C_OPTIONS = [1, 10, 100, 1000]
param_grid = [
{
'reduce_dim': [PCA(iterated_power=7), NMF()],
'reduce_dim__n_components': N_FEATURES_OPTIONS, ### No PCA is used..??
'classify__C': C_OPTIONS
},
{
'reduce_dim': [SelectKBest(chi2)],
'reduce_dim__k': N_FEATURES_OPTIONS,
'classify__C': C_OPTIONS
},
]
reducer_labels = ['PCA', 'NMF', 'KBest(chi2)']
grid = GridSearchCV(pipe, n_jobs=1, param_grid=param_grid)
X, y = load_digits(return_X_y=True)
grid.fit(X, y)
First of all while defining a pipeline, it used a string 'passthrough' instead of a object.
('reduce_dim', 'passthrough'), ```
Then while defining different dimensionality reduction technique for the grid search, it used a different strategy. How does [PCA(iterated_power=7), NMF()] this work ?
'reduce_dim': [PCA(iterated_power=7), NMF()],
'reduce_dim__n_components': N_FEATURES_OPTIONS, # here
Please Someone explain the code to me .
Solved - in one line, the order is ['PCA', 'NMF', 'KBest(chi2)']
Courtesy of - seralouk (see answer below)
For Reference If someone looks for more details
1 2 3
It is equivalent as far as I know.
In the documentation you have this:
pipe = Pipeline([
# the reduce_dim stage is populated by the param_grid
('reduce_dim', 'passthrough'),
('classify', LinearSVC(dual=False, max_iter=10000))
])
N_FEATURES_OPTIONS = [2, 4, 8]
C_OPTIONS = [1, 10, 100, 1000]
param_grid = [
{
'reduce_dim': [PCA(iterated_power=7), NMF()],
'reduce_dim__n_components': N_FEATURES_OPTIONS,
'classify__C': C_OPTIONS
},
{
'reduce_dim': [SelectKBest(chi2)],
'reduce_dim__k': N_FEATURES_OPTIONS,
'classify__C': C_OPTIONS
},
]
Initially we have ('reduce_dim', 'passthrough'), and then 'reduce_dim': [PCA(iterated_power=7), NMF()]
The definition of the PCA is done in the second line.
You could define alternatively:
pipe = Pipeline([
# the reduce_dim stage is populated by the param_grid
('reduce_dim', PCA(iterated_power=7)),
('classify', LinearSVC(dual=False, max_iter=10000))
])
N_FEATURES_OPTIONS = [2, 4, 8]
C_OPTIONS = [1, 10, 100, 1000]
param_grid = [
{
'reduce_dim__n_components': N_FEATURES_OPTIONS,
'classify__C': C_OPTIONS
},
{
'reduce_dim': [SelectKBest(chi2)],
'reduce_dim__k': N_FEATURES_OPTIONS,
'classify__C': C_OPTIONS
},
]
I am having problems loading my model on google colab. here is the code:
I have attached the code below
I have tried changing the name of the statedict and it does not help
basically, I am trying to save my model for later use, but, this is becoming extremely difficult since I am not being able to properly save and load it. Please help me with the problem. After the section of the code, you will also find the error that I have attached below.
here is the code
from zipfile import ZipFile
file_name = 'data.zip'
with ZipFile(file_name, 'r') as zip:
zip.extractall()
from zipfile import ZipFile
file_name = 'results.zip'
with ZipFile(file_name, 'r') as zip:
zip.extractall()
!pip install tensorflow-gpu
from __future__ import print_function
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.optim as optim
import torch.utils.data
import torchvision.datasets as dset
import torchvision.transforms as transforms
import torchvision.utils as vutils
from torch.autograd import Variable
batchSize = 64
imageSize = 64
transform = transforms.Compose([transforms.Resize(imageSize), transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),])
dataset = dset.CIFAR10(root = './data', download = True, transform = transform)
dataloader = torch.utils.data.DataLoader(dataset, batch_size = batchSize, shuffle = True, num_workers = 2)
def weights_init(m):
classname = m.__class__.__name__
if classname.find('Conv') != -1:
m.weight.data.normal_(0.0, 0.02)
elif classname.find('BatchNorm') != -1:
m.weight.data.normal_(1.0, 0.02)
m.bias.data.fill_(0)
class G(nn.Module):
def __init__(self):
super(G, self).__init__()
self.main = nn.Sequential(
nn.ConvTranspose2d(100, 512, 4, 1, 0, bias = False),
nn.BatchNorm2d(512),
nn.ReLU(True),
nn.ConvTranspose2d(512, 256, 4, 2, 1, bias = False),
nn.BatchNorm2d(256),
nn.ReLU(True),
nn.ConvTranspose2d(256, 128, 4, 2, 1, bias = False),
nn.BatchNorm2d(128),
nn.ReLU(True),
nn.ConvTranspose2d(128, 64, 4, 2, 1, bias = False),
nn.BatchNorm2d(64),
nn.ReLU(True),
nn.ConvTranspose2d(64, 3, 4, 2, 1, bias = False),
nn.Tanh()
)
def forward(self, input):
output = self.main(input)
return output
netG = G()
netG.load_state_dict(torch.load('generator.pth'))
netG.eval()
#netG.apply(weights_init)
class D(nn.Module):
def __init__(self):
super(D, self).__init__()
self.main = nn.Sequential(
nn.Conv2d(3, 64, 4, 2, 1, bias = False),
nn.LeakyReLU(0.2, inplace = True),
nn.Conv2d(64, 128, 4, 2, 1, bias = False),
nn.BatchNorm2d(128),
nn.LeakyReLU(0.2, inplace = True),
nn.Conv2d(128, 256, 4, 2, 1, bias = False),
nn.BatchNorm2d(256),
nn.LeakyReLU(0.2, inplace = True),
nn.Conv2d(256, 512, 4, 2, 1, bias = False),
nn.BatchNorm2d(512),
nn.LeakyReLU(0.2, inplace = True),
nn.Conv2d(512, 1, 4, 1, 0, bias = False),
nn.Sigmoid()
)
def forward(self, input):
output = self.main(input)
return output.view(-1)
netD = D()
netD.load_state_dict(torch.load('discriminator.pth'))
netD.eval()
#netD.apply(weights_init)
criterion = nn.BCELoss()
checkpoint = torch.load('discriminator.pth')
optimizerD = optim.Adam(netD.parameters(), lr = 0.0002, betas = (0.5, 0.999))
optimizerD.load_state_dict(checkpoint['optimizer_state_dict'])
epoch = checkpoint['epoch']
errD = checkpoint['loss']
checkpoint1 = torch.load('genrator.pth')
optimizerG = optim.Adam(netG.parameters(), lr = 0.0002, betas = (0.5, 0.999))
optimizerG.load_state_dict(checkpoint1['optimizer_state_dict'])
errG = checkpoint1['loss']
k = epoch
for j in range(k, 10):
for i, data in enumerate(dataloader, 0):
netD.zero_grad()
real, _ = data
input = Variable(real)
target = Variable(torch.ones(input.size()[0]))
output = netD(input)
errD_real = criterion(output, target)
noise = Variable(torch.randn(input.size()[0], 100, 1, 1))
fake = netG(noise)
target = Variable(torch.zeros(input.size()[0]))
output = netD(fake.detach())
errD_fake = criterion(output, target)
errD = errD_real + errD_fake
errD.backward()
optimizerD.step()
netG.zero_grad()
target = Variable(torch.ones(input.size()[0]))
output = netD(fake)
errG = criterion(output, target)
errG.backward()
optimizerG.step()
print('[%d/%d][%d/%d] Loss_D: %.4f Loss_G: %.4f' % (epoch+1, 10, i+1, len(dataloader), errD.data, errG.data))
if i % 100 == 0:
vutils.save_image(real, '%s/real_samples.png' % "./results", normalize = True)
fake = netG(noise)
vutils.save_image(fake.data, '%s/fake_samples_epoch_%03d.png' % ("./results", epoch+1), normalize = True)
torch.save({
'epoch': epoch,
'model_state_dict': netD.state_dict(),
'optimizer_state_dict': optimizerD.state_dict(),
'loss': errD
}, 'discriminator.pth')
torch.save({
'epoch': epoch,
'model_state_dict': netG.state_dict(),
'optimizer_state_dict': optimizerG.state_dict(),
'loss': errG
}, 'generator.pth')
here is the error
RuntimeError Traceback (most recent call last)
<ipython-input-23-3e55546152c7> in <module>()
26 # Creating the generator
27 netG = G()
---> 28 netG.load_state_dict(torch.load('generator.pth'))
29 netG.eval()
30 #netG.apply(weights_init)
/usr/local/lib/python3.6/dist-packages/torch/nn/modules/module.py in load_state_dict(self, state_dict, strict)
767 if len(error_msgs) > 0:
768 raise RuntimeError('Error(s) in loading state_dict for {}:\n\t{}'.format(
--> 769 self.__class__.__name__, "\n\t".join(error_msgs)))
770
771 def _named_members(self, get_members_fn, prefix='', recurse=True):
RuntimeError: Error(s) in loading state_dict for G:
Missing key(s) in state_dict: "main.0.weight", "main.1.weight", "main.1.bias", "main.1.running_mean", "main.1.running_var", "main.3.weight", "main.4.weight", "main.4.bias", "main.4.running_mean", "main.4.running_var", "main.6.weight", "main.7.weight", "main.7.bias", "main.7.running_mean", "main.7.running_var", "main.9.weight", "main.10.weight", "main.10.bias", "main.10.running_mean", "main.10.running_var", "main.12.weight".
Unexpected key(s) in state_dict: "epoch", "model_state_dict", "optimizer_state_dict", "loss".
You need to access the 'model_state_dict' key inside the loaded checkpoint.
Try:
netG.load_state_dict(torch.load('generator.pth')['model_state_dict'])
You'll probably need to apply the same fix to the discriminator as well.
I'am new to TF: I took perceptron's code from this tutorial on MNIST(actually, its not necessary to follow this link) :https://github.com/aymericdamien/TensorFlow-Examples/blob/master/examples/3_NeuralNetworks/multilayer_perceptron.py
I wanted to remake those perceptron to a perceptron with 1 layer and linear activation function, to make it the most simpliest form of : output =w2(w1*x+b1)+b2. But this is what i get:
Data:
X_train: array([[ 10.],
[ 10.],
[ 11.],
[ 6.],
[ 8.],
[ 9.],
[ 22.],
[ 14.],
[ 6.],
[ 8.],
[ 11.],
[ 9.],
[ 13.],
[ 7.],
[ 13.],
[ 7.],
[ 13.],
[ 11.]])
y_train: array([[ 44.5825],
[ 53.99 ],
[ 52.4475],
[ 37.6 ],
[ 38.6125],
[ 39.5875],
[ 43.07 ],
[ 74.8575],
[ 34.185 ],
[ 38.61 ],
[ 34.8175],
[ 36.61 ],
[ 34.0675],
[ 37.67 ],
[ 49.725 ],
[ 79.4775],
[ 50.41 ],
[ 51.26 ]])
X_test: array([[ 6.],
[ 14.],
[ 14.],
[ 12.],
[ 13.],
[ 13.]])
y_test: array([[ 55.75 ],
[ 33.035 ],
[ 38.3275],
[ 39.2825],
[ 50.7325],
[ 45.2575]])
Parameters:
learning_rate = 1
training_epochs = 1
display_step = 1 #maintaining variable
x = tf.placeholder("float", [None, 1])
y = tf.placeholder("float", [None, 1])
Perceptron model:
def multilayer_perceptron(x, weights, biases, output_0):
layer_1 = tf.add(tf.matmul(x, weights['h1']), biases['b1'])
out_layer = tf.add(tf.matmul(layer_1, weights['out']), biases['out'])
output_o = out_layer #This variable is just needed to print result in session
return out_layer
output_0 = tf.Variable(tf.random_normal([1, n_classes]))
weights = {
'h1': tf.Variable(tf.random_normal([n_input, n_hidden_1])),
'out': tf.Variable(tf.random_normal([n_hidden_2, n_classes]))}
biases = {
'b1': tf.Variable(tf.random_normal([n_hidden_1])),
'out': tf.Variable(tf.random_normal([n_classes]))}
Let's build the graph:
prediction = multilayer_perceptron(x, weights, biases, output)
cost = tf.reduce_mean(tf.square(prediction-y)) #MSE
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost) #Gives the smallest cost
init = tf.initialize_all_variables()
Finally, let's run the session:
with tf.Session() as Sess:
Sess.run(init)
for epoch in range(training_epochs):
avg_cost = 0.
number_of_bathces = len(X_train)/batch_size
_, c = Sess.run([optimizer, cost], feed_dict = {x: X_train, y: y_train})
avg_cost += c/len(X_train)
print(Sess.run(output_0))
if epoch % display_step ==0:
print("Epoch:", '%02d' % (epoch+1), "cost =", "{:.9f}".format(avg_cost))
print("Optimization finished")
correct_prediction = tf.equal(tf.arg_max(prediction,1), tf.arg_max(y,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
print("Accuracy:", accuracy.eval({x:X_test, y:y_test}))
And now, we get the output:
[[ 0.77995574]]
Epoch: 01 cost = 262.544189453
Optimization finished
Accuracy: 1.0
The most confusing thing is the output(first number)! It should be somewhere in range of [30; 50]! Please, explain me, where did i do wrong.
Your code is notably messy, so I've removed a lot of redundant pieces:
from __future__ import print_function
import numpy as np
import tensorflow as tf
X_train = np.array([[ 10.], [ 10.], [ 11.], [ 6.], [ 8.], [ 9.], [ 22.], [ 14.], [ 6.], [ 8.], [ 11.], [ 9.], [ 13.], [ 7.], [ 13.], [ 7.], [ 13.], [ 11.]])
y_train = np.array([[ 44.5825], [ 53.99 ], [ 52.4475], [ 37.6 ], [ 38.6125], [ 39.5875], [ 43.07 ], [ 74.8575], [ 34.185 ], [ 38.61 ], [ 34.8175], [ 36.61 ], [ 34.0675], [ 37.67 ], [ 49.725 ], [ 79.4775], [ 50.41 ], [ 51.26 ]])
X_test = np.array([[ 6.], [ 14.], [ 14.], [ 12.], [ 13.], [ 13.]])
y_test = np.array([[ 55.75 ], [ 33.035 ], [ 38.3275], [ 39.2825], [ 50.7325], [ 45.2575]])
learning_rate = 0.05
training_epochs = 10
n_classes = 1
n_hidden_1 = 5
n_hidden_2 = 5
n_input = 1
x = tf.placeholder(tf.float32, [None, 1])
y = tf.placeholder(tf.float32, [None, 1])
def multilayer_perceptron(x, weights, biases):
layer_1 = tf.add(tf.matmul(x, weights['h1']), biases['b1'])
out_layer = tf.add(tf.matmul(layer_1, weights['out']), biases['out'])
return out_layer
weights = {
'h1': tf.Variable(tf.random_normal([n_input, n_hidden_1])),
'out': tf.Variable(tf.random_normal([n_hidden_2, n_classes]))}
biases = {
'b1': tf.Variable(tf.random_normal([n_hidden_1])),
'out': tf.Variable(tf.random_normal([n_classes]))}
prediction = multilayer_perceptron(x, weights, biases)
cost = tf.reduce_mean(tf.square(prediction - y)) #MSE
optimizer = tf.train.AdamOptimizer(learning_rate = learning_rate).minimize(cost) #Gives the smallest cost
init = tf.initialize_all_variables()
with tf.Session() as sess:
sess.run(init)
for epoch in range(training_epochs):
_, c = sess.run([optimizer, cost], feed_dict = {x: X_train, y: y_train})
print("Epoch:", '%02d' % (epoch+1), "cost =", "{:.9f}".format(c))
print("Optimization finished")
print(sess.run(prediction, feed_dict = {x: X_test, y: y_test} ))
It seems to work now. I've got the following results:
Epoch: 01 cost = 1323.519653320
Epoch: 02 cost = 926.386840820
Epoch: 03 cost = 628.072326660
Epoch: 04 cost = 431.689270020
Epoch: 05 cost = 343.259063721
Epoch: 06 cost = 355.978668213
Epoch: 07 cost = 430.280548096
Epoch: 08 cost = 501.149414062
Epoch: 09 cost = 527.575683594
Epoch: 10 cost = 507.708007812
Optimization finished
[[ 30.79703712]
[ 69.70319366]
[ 69.70319366]
[ 59.97665405]
[ 64.83992004]
[ 64.83992004]]
Results may vary due to random initialization of weights.
Couple of tips:
Use smaller learning rate
Train over several epochs to see the dynamics
Why is my convolutional autoencoder not converging properly? I have a very simple layer stack.
Encoder: Conv/ReLU(Kernel size: 7x7, stride = 1, padding = 0) => maxPool(kernel size=2x2, stride = 2) => Conv/ReLU(Kernel size: 5x5, stride = 1, padding = 0) => MaxPool(kernel size=2x2, stride = 2)
Decoder: Nearest Neighbour Upsampling => Deconv/ReLU => Nearest Neighbour Upsampling => Deconv/ReLU
Training Images are of size 30x30x1.
I tried to train it with 1000 images over 1000 epoch, but the error (MSE) is still 120.
BATCH_SIZE = 100
IMAGE_SIZE = 30
NUM_CHANNELS = 1
num_images = 1000
def init_weights(shape):
return tf.Variable(tf.random_normal(shape, stddev=0.01))
def encoder(X, w, w2, wd, wd2):
l1a = tf.nn.relu(tf.nn.conv2d(X, w,strides=[1, 1, 1, 1], padding='VALID'))
l1 = tf.nn.max_pool(l1a, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')
l2a = tf.nn.relu(tf.nn.conv2d(l1, w2,strides=[1, 1, 1, 1], padding='VALID'))
l2 = tf.nn.max_pool(l2a, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')
l1da = tf.image.resize_images(l2, 8, 8, 1, align_corners=False)
output_shapel1d = tf.convert_to_tensor([BATCH_SIZE, 12, 12, 32], dtype=tf.int32);
l1d = tf.nn.relu(tf.nn.conv2d_transpose(l1da, wd, output_shapel1d, strides=[1, 1, 1, 1], padding='VALID'))
l2da = tf.image.resize_images(l1d, 24, 24, 1, align_corners=False)
output_shapel2d = tf.convert_to_tensor([BATCH_SIZE, IMAGE_SIZE, IMAGE_SIZE, NUM_CHANNELS], dtype=tf.int32);
l2d = tf.nn.relu(tf.nn.conv2d_transpose(l2da, wd2, output_shapel2d, strides=[1, 1, 1, 1], padding='VALID'))
return l2d
complete_image = extract_data(0, 1000)
trX = complete_image[0:900]
trY = trX
teX = complete_image[900:1000]
teY = teX
X = tf.placeholder("float", [BATCH_SIZE, IMAGE_SIZE, IMAGE_SIZE, NUM_CHANNELS])
Y = tf.placeholder("float", [BATCH_SIZE, IMAGE_SIZE, IMAGE_SIZE, NUM_CHANNELS])
w = init_weights([7, 7, 1, 32])
w2 = init_weights([5, 5, 32, 64])
wd = init_weights([5, 5, 32, 64])
wd2 = init_weights([7, 7, 1, 32])
py_x = encoder(X, w, w2, wd, wd2)
cost = tf.reduce_mean(tf.squared_difference(py_x, Y, name = None))
train_op = tf.train.RMSPropOptimizer(0.001, 0.9).minimize(cost)
predict_op = py_x;
global_step = tf.Variable(0, name='global_step', trainable=False)
saver = tf.train.Saver()
with tf.Session() as sess:
tf.initialize_all_variables().run()
start = global_step.eval() # get last global_step
print "Start from:", start
if FLAGS.output == "train":
for i in range(start, 500):
training_batch = zip(range(0, num_images - BATCH_SIZE, batch_size),
range(batch_size, num_images - BATCH_SIZE, batch_size))
for start, end in training_batch:
sess.run(train_op, feed_dict={X: trX[start:end], Y: trY[start:end]})
total_epoch_cost += sess.run(cost, feed_dict={X: trX[start:end], Y: trY[start:end]})
avg_epoch_cost = total_epoch_cost/BATCH_SIZE
print "cost during epoch " + `i` + "is ", avg_epoch_cost
I have added the complete code in this gist with slight modifications. I am training this with around 10,000 images, and the error after 488 epochs is 74.8.
Z3Py online is a very powerful tool to determine the DC operating point of a given MOSFET amplifier. With the aim to illustrate that we will consider the following circuit
The parameters of the MOSFET amplifier are:
k = 1.25 * 10^(-4) , V_T = 1.5 , R_D = 10^4 , V = 15
To determine the DC operating point we use the following Z3Py code:
I_D, k, V_GS, V_T, V_DS, V, R_D = Reals('I_D k V_GS V_T V_DS V R_D')
equations = [
I_D == k * (V_GS - V_T)**2, V_GS == V_DS,
V_DS == V - R_D * I_D,
]
print "MOSFET equations:"
print equations
problem = [
k == 1.25*10**(-4),
V_T == 1.5,
R_D == 10**4,
V == 15, V_GS > V_T
]
print "Problem:"
print problem
print "Solution:"
solve(equations + problem)
Using this code online, we obtain the following output
MOSFET equations:
[I_D = kĀ·(V_GS - V_T)2, V_GS = V_DS, V_DS = V - R_DĀ·I_D]
Problem:
[k = 1/8000, V_T = 3/2, R_D = 10000, V = 15, V_GS > V_T]
Solution:
[I_D = 0.0010589410?,
V = 15,
R_D = 10000,
V_T = 3/2,
k = 1/8000,
V_GS = 4.4105890714?,
V_DS = 4.4105890714?]
It can also try it online here.
As we can see Z3PY is able to compute the correct solution I_D , V_GS and V_DS in a very compact and efficient form.
Other example
This problem is solved using the following code
I_D, k, V_GS = Reals('I_D k V_GS')
V_T, V_I, R_S = Reals('V_T V_I R_S')
V_O, V_DD, R_L = Reals('V_O V_DD R_L')
equations = [
I_D == (k/2) * (V_GS - V_T)**2, V_I == V_GS + R_S * I_D,
V_O == V_DD - R_L * I_D,
]
print "MOSFET equations:"
print equations
problem = [
k == 2,
V_T == 2,
V_DD == 145,
V_I == 6.5, R_S == 22, R_L ==82, V_GS > V_T
]
print "Problem:"
print problem
print "Solution:"
solve(equations + problem)
problem1 = [
k == 2,
V_T == 2,
V_DD == 145,
V_I == 6.5 + 1, R_S == 22, R_L ==82, V_GS > V_T
]
print "Problem 1"
print problem1
print "Solution 1:"
solve(equations + problem1)
problem2 = [
k == 2,
V_T == 2,
V_DD == 145,
V_I == 6.5 + 10**(-3), R_S == 22, R_L ==82, V_GS > V_T
]
print "Problem 2"
print problem2
print "Solution 2:"
solve(equations + problem2)
Using this code online we obtain the following output
MOSFET equations:
[I_D = (k/2)Ā·(V_GS - V_T)2, V_I = V_GS + R_SĀ·I_D, V_O = V_DD - R_LĀ·I_D]
Problem:
[k = 2, V_T = 2, V_DD = 145, V_I = 13/2, R_S = 22, R_L = 82, V_GS > V_T]
Solution:
[I_D = 0.1849949805?,
R_L = 82,
R_S = 22,
V_I = 13/2,
V_DD = 145,
V_T = 2,
k = 2,
V_O = 129.8304115963?,
V_GS = 2.4301104282?]
Problem 1
[k = 2, V_T = 2, V_DD = 145, V_I = 15/2, R_S = 22, R_L = 82, V_GS > V_T]
Solution 1:
[I_D = 0.2282823186?,
R_L = 82,
R_S = 22,
V_I = 15/2,
V_DD = 145,
V_T = 2,
k = 2,
V_O = 126.2808498705?,
V_GS = 2.4777889896?]
Problem 2
[k = 2, V_T = 2, V_DD = 145, V_I = 6501/1000, R_S = 22, R_L = 82, V_GS > V_T]
Solution 2:
[I_D = 0.1850381539?,
R_L = 82,
R_S = 22,
V_I = 6501/1000,
V_DD = 145,
V_T = 2,
k = 2,
V_O = 129.8268713797?,
V_GS = 2.4301606140?]
It can also try it online here.
Other example
This problem is solved using the following code
I_D, k, V_GS = Reals('I_D k V_GS')
V_T, V_EQ, R_S = Reals('V_T V_EQ R_S')
V_DS, V_DD, R_D = Reals('V_DS V_DD R_D')
equations = [
I_D == (k/2) * (V_GS - V_T)**2, V_EQ == V_GS + R_S * I_D,
V_DS == V_DD - (R_D + R_S )* I_D,
]
print "MOSFET equations:"
print equations
problem = [
k == 25*10**(-6),
V_T == 1,
V_DD == 10,
V_EQ == 4, R_S == 39*10**3, R_D == 75*10**3, V_GS > V_T
]
print "Problem:"
print problem
print "Solution:"
solve(equations + problem)
Using this code online we obtain the following output
MOSFET equations:
[I_D = (k/2)Ā·(V_GS - V_T)2, V_EQ = V_GS + R_SĀ·I_D, V_DS = V_DD - (R_D + R_S)Ā·I_D]
Problem:
[k = 1/40000, V_T = 1, V_DD = 10, V_EQ = 4, R_S = 39000, R_D = 75000, V_GS > V_T]
Solution:
[I_D = 0.0000343918?,
R_D = 75000,
R_S = 39000,
V_EQ = 4,
V_DD = 10,
V_T = 1,
k = 1/40000,
V_DS = 6.0793307846?,
V_GS = 2.6587184263?]
It can also try it online here .
Other example:
This problem is solved using the following code
I_D, k, V_GS = Reals('I_D k V_GS')
V_T = Real('V_T')
R_D = Real('R_D')
V_DS, V_DD = Reals('V_DS V_DD')
equations = [
I_D == (k) * (V_GS - V_T - (V_DS) /2)*V_DS, V_DD == V_GS,
V_DS == V_DD - (R_D)* I_D,
]
print "MOSFET equations:"
print equations
problem = [
k == 250*10**(-6),
V_T == 1,
V_DD == 4,
R_D == 1600, V_DS < V_GS - V_T
]
print "Problem:"
print problem
print "Solution:"
solve(equations + problem)
Using this code online we obtain the following output
MOSFET equations:
[I_D = kĀ·(V_GS - V_T - V_DS/2)Ā·V_DS, V_DD = V_GS, V_DS = V_DD - R_DĀ·I_D]
Problem:
[k = 1/4000, V_T = 1, V_DD = 4, R_D = 1600, V_DS < V_GS - V_T]
Solution:
[I_D = 0.0010634763?,
R_D = 1600,
V_DD = 4,
V_T = 1,
k = 1/4000,
V_GS = 4,
V_DS = 2.2984378812?]
It can also try it online here .
Please let me know what do you think about this and if you know a more efficient code for such class of problems. Many thnaks.