Lagrange Çarpanı – Değişik bir bakış

Lagrange Çarpanı yöntemi genelde 2 fonksiyonun gradyanlarının birbirine paralel olmasıyla açıklanır. Bu yazıda maksimizasyon/minimizasyon problemlerinde Lagrange Çarpanları kullanımının biraz daha garip fakat daha kolay bir çıkarımından bahsedeceğim.

Diyelim ki elimizde bir $f(x, y)$ fonksiyonu var ve bu fonksiyonun aldığı en büyük değeri bulmaya çalışıyoruz. Matematiksel olarak ifade edecek olursak:

$$
\max\limits_{x,y} f(x,y)
$$

Ve diyelim ki çözümün $g(x, y)=c$ gibi bir koşulu da sağlaması gereksin. Eğer böyle bir kısıtımız olmasaydı $f()$in kısmi türevlerini alıp sıfıra eşitlerdik ve çözüme ulaşırdık (fonksiyon limitlerde sonsuza büyümüyorsa tabi).

 

Lagrange multiplier

Şimdi bu kısıtımızı denkleme yedirelim. Maximize edeceğimiz fonksiyona $0$ değerini eklemek ya da çıkartmak ifadeyi maximize eden değerleri değiştirmeyecektir. Yani:

$$
\max\limits_{x,y} f(x,y) = \max\limits_{x,y}  \left[ f(x,y) + 0 \right]
$$

Aynı şekilde sıfırın herhangi bir katını da ekleyip çıkarmam sonucu değiştirmeyecektir:

$$
\max\limits_{x,y} f(x,y) = \max\limits_{x,y}  \left[ f(x,y) + k\cdot 0 \right]
$$

$g(x, y)=c$ olan kısıtımızı da düzenlersek  $0=g(x, y)-c$ elde ederiz. Sıfırı yerine koyarsak üstteki denklemde:

$$
\max\limits_{x,y} f(x,y) = \max\limits_{x,y}  \left[ f(x,y) + k(g(x, y)-c) \right]
$$

Elde ettiğimiz ifade Lagrange Çarpanları ifadesi; $k$lar da Lagrange Çarpanı denilen şeyler. Kısıtmızı esas başladığımız maksimizasyon problemine Lagrange Çarpanlarını kullanarak yedirmiş olduk. Şimdi bu elde ettiğimiz yeni denklemin x’e ve y’ye göre kısmı türevini alıp sıfıra eşitleyip kısıtımıza göre en büyük aldığı değeri bulabiliriz.

Using OpenCV 2.3.1 with Visual Studio 2010 (tutorial)

Here in this tutorial I am going to show how to configure Visual Studio 2010 to use OpenCV 2.3.1 in your computer vision projects. Also, I am going to write a couple of lines of code to show new OpenCV C++ API.

By the time the tutorial was written the latest version of OpenCV was 2.3.1. The methods described below should, but may not, work for different versions. This tutorial targets computer vision course students at Computer Engineering in BOUN, but I will be generalizing as much as I can, so everyone can enjoy it.

Foreword

Before starting I would like to suggest a couple of things.

First, if you are ever going to write C++ code, read Effective C++, 3rd edition by Scott Meyers (CAUTION! 2nd edition is outdated, it is not worth reading imho). This book has many topics on how to write correct, working, easily maintainable C++ code. I see lots of boilerplate code around when it comes to C++, not only reading this book will reduce such practices, it will save you time. Besides, you will feel healthy mind-wise :) If there was to be only one book on C++, and the rest was to disappear, I would select this book. Be careful though, this book is *NOT* for beginners, you need to know a little bit of C++ to understand what it means.

Effective C++ 3rd edition

For BOUN students who are taking Computer Vision course, the book is available as an electronic resource in the library.

Second, Google has really good guidelines on different programming languages, including C++. Although they are specialized for their internal use, I recommend following those guidelines. The guideline provide the motivation behind the rules, so it is also great place to learn how to write C++ properly. Again, it is not a place to learn C++, but to master C++.

Preparation

Make sure that you have Visual Studio 2010 (VS2010) installed.

For BOUN students, it is available in license server. I don’t quite know the details, you may need to work it on your own.

Download OpenCV 2.3.1 and extract the contents to a folder. I prefer to put directly under root like “C:\OpenCV-2.3.1\”.

Optionally, I recommend using Visual Assist X to write and refactor code easily.

Configuring VS2010

There are a couple of ways to configure Visual Studio 2010, I am going to show a way which I find convenient. We are going to configure it using property sheets. Whenever we need to create another project, we just need to add same property sheets to new project. Let’s start.

Launch VS2010 and select “New project…”.

Select “Empty Project”, enter “hello-opencv” as Name, select a location to place project. I also prefer, for simplicity, not creating directory for solution so I unchecked that option. See the image below.

When done, press “OK”.

Now we have created a project from scratch. It is time to link the libraries and make our project use OpenCV.

Switch to Property manager by clicking on the tab below.

The default properties are for 32-bit systems (note the Win32 suffixes), because I am using 64-bit system, from now on I am going to describe the configuration for 64-bit systems.

From the “Build” menu, select “Configuration Manager”. Under “Active solution platform” Win32 should be selected by default. Click on it and select “New…”.

Select “x64″ as the new platform and select Win32 to copy settings from. Make sure that “Create new project platforms” is checked.

Now your Property Manager view should look like this:

Select the Win32 configurations and delete them, you won’t be needing those. Let me remind this one more time, these steps are only required if you are using 64-bit system and want to develop 64-bit applications.

To add a property sheet right click on “Debug | x64″ and select “Add New Project Property Sheet”. This property sheet will/should only include the details on how to link the OpenCV library to our project. Once this is done, the property sheet can be shared between projects on the same computer.

On the add new property sheet dialog, I entered “OpenCV-Debug” as the sheet name, because this sheet will link debug libraries. After pressing “Add” the new property sheet will show up in Property Manager. Double click on it, a dialog with lots of properties will be shown.

Under “Common Properties” -> “C/C++” -> “General”, edit “Additional Include Directories” and add “C:\OpenCV-2.3.1\build\include”. Of course don’t forget to change the path accordingly if you have put OpenCV files to a different place. It is important that you select the “include” folder under “build” folder, not any other “include” folder.

Under “Common Properties” -> “Linker” -> “General”, edit “Additional Library Directories” and add “C:\OpenCV-2.3.1\build\x64\vc10\lib”. I won’t tell you to change the path to your OpenCV path next time :) Here “x64″ stands for 64-bit systems, if you are using 32-bit change it to x86. “vc10″ stands for Visual C++ 2010, leave it as it is assuming you are using VS2010.

Under “Common Properties” -> “Linker” -> “Input”, edit “Additional Dependencies” and add the following lib files:

opencv_calib3d231d.lib
opencv_contrib231d.lib
opencv_core231d.lib
opencv_features2d231d.lib
opencv_flann231d.lib
opencv_gpu231d.lib
opencv_haartraining_engined.lib
opencv_highgui231d.lib
opencv_imgproc231d.lib
opencv_legacy231d.lib
opencv_ml231d.lib
opencv_objdetect231d.lib
opencv_ts231d.lib
opencv_video231d.lib

Actually you won’t probably need all the libraries. Linking the only necessary ones may make linking operation a little bit faster but for our case, that speed up is not worth the effort. Note the letter “d” in filenames just before the dot, that “d” stands for “Debug”.

The steps are the same for “Release” configuration except the linked library filenames. You just need to get rid of the “d” letters before the dot. Debug libraries includes additional instructions for debugging purposes such as variable watching, and they are not optimized. This makes debug libraries run slower. When you are dealing with lots of data or you just need more processing power you should switch to release configuration which is free of extra instructions and optimizes your code, hence runs much faster.

Hello OpenCV

OK. Now we are (almost) ready to write our first lines of code. Switch to “Solution Explorer” by clicking the tab below. Right click on “Source Files”, select “Add” -> “New Item…”. Select “C++ File” from the menu and type “main” as name.

Insert the following lines into the main.cpp and run the code (press F5).

#include <opencv2/opencv.hpp>

using namespace cv;

int main()
{
    Mat img(Mat::zeros(100, 100, CV_8U));

    imshow("window", img);

    waitKey();

    return 0;
}

You should get an error about a missing dll. Locate “hello-opencv.exe” in your project folder. Copy the dll files (preferably the ones that ends with letter “d”) from “C:\OpenCV-2.3.1\build\x64\vc10\bin” to that folder.

By the way, using full namespaces like “using namespace cv;” is discouraged. I recommend using “using cv::Mat;”, this will prevent name collisions and make the code more maintainable. See this discussion for details.

Some people prefer adding these dll into PATH environment variable, I prefer my projects to be self sufficient. It is good to be in control of which dll the project is using. If you are dealing with multiple projects using the different versions of the same library, if the dll names are the same, PATH approach will not work.

Run the code again. It should work fine and display a 100×100 black image in a window. If not that means there is a problem that you need to figure out. Try until you solve that problem.

Now modify the main.cpp so it is like:

#include <opencv2 /opencv.hpp>

using namespace cv;

int main()
{
    Mat img;
    VideoCapture cap(0);

    while (true)
    {
        cap >> img;

        Mat edges;
        cvtColor(img, edges, CV_BGR2GRAY);

        Canny(edges, edges, 30, 60);

        imshow("window label", edges);
        waitKey(1);
    }

    return 0;
}

The code above needs a webcam connected to the computer, it captures images from a camera.

And run the code. You should get a missing “tbb_debug.dll” error. This is a bug of OpenCV-2.3.1. It should be shipped with tbb_debug.dll but it is missing in the package. That dll is the part of Threading Building Blocks project by Intel, you should download the latest version from here. The zip file that you have downloaded contains the dll, and you should copy that dll to the same folder under your project like other dlls (same directory as hello-opencv.exe).

Now run the code again. “Canny” is an edge detection algorithm, if the program runs well, you should see the detected edges of the captured image.

This completes our tutorial.

Closure

The documentation of OpenCV is quite good. Use it extensively.

I highly recommend using new OpenCV C++ API. The new API is clean, slick and well-designed. Avoid using old API, e.g. IplImage, unless you really know what you are doing. There are lots of information on internet about OpenCV which is outdated, beware of those. Always use the latest official documentation first.

Çalışma kültürü

Burada study dedikleri bir kavram var. Öğrencilerin gidip birlikte çalışabilecekleri ortak çalışma alanlarına verilen isim study. Örnek cümle içinde kullanımı: “Madem öyle yemekten sonra study‘ye gideriz”. Kütüphane’nin giriş katında ayrı bir bölümde büyük bir study var, bir de benim gördüğüm bölüm binalarının içerisinde de küçük küçük study‘ler var.

Eski laptopum çok külüstür olduğundan fişe takılmadan çalışmıyor, bir keresinde acil laptop açıp internete bağlanmam gerekti, o zamanlar da bi lab’da çalışmadığım için mekansızım, kütüphaneye girip kurulmak zor geldiğinden bölümdeki study‘ye giriverdim.


İçerisi öğrenci evi bozması bir oda, ortada masalar sandalyeler, duvar diplerinde çiçek desenli, kirli kanepeler, boş duvarlar. Buraya ne zaman baksam içeride insanlar görüyordum, merak da ediyordum. Bir yanda uzay mekiği üzerine konuşan ufak bir grup var. Diğer tarafta tıkır tıkır kod yazıp ödev yapan çömezler. O sırada muhtemelen sınavı olduğu için bir gün önceden uyumamış her bölümün olmazsa olmazı bıyıklı kel, benden dahi yaşlı gösteren bi öğrenci geldi kanepelerden birine uzandı uyumaya başladı.

Study‘ler sadece ders çalışma alanları olmaktan çıkmış, öğrencilerin sosyalleştiği alanlar haline de gelmiş, ki bu acayip sevindirici. Çünkü çalışmayı inanılmaz teşvik ediyor, içeriye girince hem çalışıyorsunuz hem eğleniyorsunuz. Bir nevi garaj bu study‘ler. Study‘lerin dışında bölümün içerisinde de benzer bir anlayış var, bölüm binasının girişindeki koltuklarda da her daim çalışan, muhabbet eden öğrenciler var.

Study‘ler sadece bir örnek. Boğaziçi Üniversitesinde her alanda çalışmaya teşvik ediliyorsunuz ve bu zorlama olarak değil bir yaşam biçimi olarak hayatınıza nüfuz etmeye başlıyor. İTÜ ile gördüğüm en büyük fark bu herhalde, İTÜ’de çevre koşulları sizi bir yöne itmiyordu, bireysel çabalarınızla ayakta tutmalıydınız çalışma kültürünüzü. Başka bir deyişle kendinize ya da başkasına faydalı olmanızı sağlayacak maddi ve manevi koşullar sağlanmıyordu. Benim zamanında olduğum gibi, çalışmaya niyetiniz yoksa gayet tembel bir öğrenci olarak hayatta kalabiliyordunuz. Bunun İTÜ’de gerçekleşmemesinin nedeninin maddi olduğunu da zannettmiyorum, benzer fiziksel ortamlar yaratmanın maliyeti çok değil (çirkin masa ve sandalye neticede).

Boğaziçi Üniversitesi, hadi genellemeyeyim, Bilgisayar Mühendisliği bölümü bu şekilde bir çalışma kültürü oluşturduğu için çok doğru yapmış. Bu kadar ünlü olmasının altında bu kültürün önemli payı var (geldiğimden bu yana ününü de hakettiğini gördüm, o da ayrı). Bu kültür sayesinde güncel kalabiliyor, başarılı işler ortaya koyuyor ve bu iyi niteliklerin insanlar arasında yayılmasını sağlıyor.

Fotoğraf: Cliff http://www.flickr.com/photos/nostri-imago/2866399803/

Ebeyin nöronu

Transhümanizm, insanın hastalık, güçsüzlük, ölüm vb. gibi sorunlarının insana geliştirmeler yapılarak üstesinden gelinceğini savunan, başka bir deyişle insanın bir sonraki versiyonunu üretmeye çalışan akımı tarif eden bir terim. Transhümanizmin popüler kültürde çoğunlukla karşılaştığımız uygulaması insan ile makinenin biraraya gelmesi. İnsanoğlu öyle bir noktaya ulaşmıştır ki ne tam anlamıyla etten kemikten insandır ne de makinedir. İnsan artık et, metal ve elektriktendir.

Yapay kalpÖrneğin daha kuvvetli olmak için bacak ya da kollarını daha dayanıklı olan robotik implantlarla değiştirmiştir. Ya da solunum sistemindeki bir sorundan dolayı akciğerler, yine aynı işi yapacak yapay organla değiştirilmiş olabilir. Eğer verdiğim kurgusal örnekler çok uçuk geliyorsa bir kaç kere uygulanmış yapay kalbi incelemenizi öneririm.

Fakat sözkonusu beyin olunca yerine yenisini koyma fikri biraz sorunlu. Diyelim ki bir insanın beynini yapay olan dengiyle değiştireceğiz. Elimizdeki e-beyin değiştireceğimiz beynin birebir elektronik kopyası olsun. Kurgu bu ya, birinin beynini çıkartıp yerine yenisini takma süreci de sorunsuz olsun. Buna rağmen aslında yapılan şey, yerine yenisi konacak olsa bile, eski beyni öldürmektir. Çünkü varolduğunu bilen, düşünen, üzülen, kişilik sahibi olan, kısaca bizi biz olarak vareden şey beynimiz. Yeni beyinle hareket eden, yaşayan insan, eskisinden farklı bir insandır demiyorum. Yaptığımız şey, o insanın bir kopyasını yaratıp eskisini öldürmekten/yoketmekten farksızdır.

Kafadaki çiviPeki hal böyleyken beyni daha dayanıklı bir dengiyle nasıl değiştiririz? Beynin elastik bir yapıda olduğunu biliyoruz. Elastikiyetten kastettiğim, fiziksel elastikiyet değil. Günde onbinlerce nöronumuzun ölmesine rağmen, yeni üretilen ve yeni kurulan bağlantılarla yok olan nöronların eksikliğini hissetmeden hayatımıza devam edebiliyoruz. Demek istediğim şu ki, beynimizden hayati olmayan bir sinir hücresi grubunu çıkartmamız ne kişiliğimiz üzerinde ne de yaşamsal faaliyetlerimiz üzerinde etkili olur. Hatta popüler basın kafasına çivi girip de yaşayan insanların örnekleriyle doludur. İşi bir adım ileriye götürürsek, beynimizden, hayati bölgeden de olsa, bir adet nöronu çıkartmamızın hiçbir etkisini hissedemeyiz.

Yapılacak şey şudur: Komple beyni bir seferde değiştirmek yerine, beyinden bir nöronu çıkartıp yerine dengi olan bir e-nöron koymak, ve bu işlemi tüm beyin hücreleri daha dayanıklı olan e-nöronlarla değişinceye kadar tekrar etmek.

Bir nöron çıkartınca nasıl makro ölçekte etkisini hissetmiyorsak tersi de doğrudur. Bir nöron eklemenin de makro ölçekte hiçbir etkisi olmayacaktır.

Elbette yazıda tartışmaya açık birsürü nokta var. Yazıyı yazarken ana fikrin daha iyi anlaşılabilmesi için, bu belirsiz noktaları açıklamaya girişme dürtüsünün özellikle önüne geçtim.

Bir sonraki bölümde bu fikrin ışınlanma problemine uygulanışını tartışacağım inşallah. The Prestige filmini izleyenler zaten bilirler bu problemi ;)

Kangal v0.1

Kangal logo

Giriş

Kangal, mikroskop ile aldığınız görüntülerde yüzeyin kaplanma oranını hesaplamanıza yarayan bir programcıktır. Esas kullanım alanı florasan mikroskobu ile alınan görüntülerde yüzeye bağlanma oranlarının hesaplanmasıdır.

İndir

Kangal v0.1

Kullanım

Building Gods

building gods Kadim dostum noktafa‘nın bitmek tükenmek bilmeyen araştırmacılığı sayesinde bulduğu bir belgeselimsi izledim. Belgeselin ismi Building Gods. Aslında belgesel demek doğru olmaz, temelde, alanının en iyilerinden olan 4 ayrı kişiyle yapılan röportajları içeren bir video Building Gods. Fikir beyanında bulunan kişilerin nitelikleri ise gerçekten ilginç: bir teolog (Anne Foerst), bir beyin mühendisi (Hugo de Garis), bir filozof (Nick Bostrom ) ve bir sayborg (Kevin Warwick). Konu ise singularity.

brain builder, theologist, cyborg, philosopher

şimdiye kadar singularity konusu yazılı ortamın dışına pek çıkmamıştı; bildiğim kadarıyla konu üzerine yapılan ilk ve en kapsamlı görsel çalışma bu. Building Gods, singulartiy hakkında fikri olmayanlar için güzel bir başlangıç niteliğinde. Kabaca bahsetmem gerekirse, Makineler bilinç kazanınca ne olacak? Teknolojik gelişim varacağı en son nokta neresidir? Tanrı nerede? Ölümsüzlük nasıl mümkün? gibi oldukça fantastik soruları enine boyuna tartışıyorlar. Konu ile yakından ilgilenenler için pek fazla yeni bilgi ya da yaklaşımlar içerdiğini söyleyemeyeceğim fakat konuşanların mimiklerini, hissettiklerini görmek gerçekten hoş, insan mutlu oluyor.

Building Gods’ı izlemenizi şiddetle tavsiye ediyorum.
Google Video linki.