2016年12月27日火曜日
2016年11月29日火曜日
感知机对偶形式实现
import os
import numpy as np
# An example in that book, the training set and parameters' sizes are fixed
training_set = np.array([[[3, 3], 1], [[4, 3], 1], [[1, 1], -1]])
a = np.array([0, 0, 0])
b = 0
Gram = np.array([])
y = np.array(range(len(training_set))).reshape(1, 3)# used for labels
x = np.array(range(len(training_set)) * 2).reshape(3, 2)# used for features
# calculate the Gram matrix
def cal_gram():
g = np.array([[0, 0, 0], [0, 0, 0], [0, 0, 0]])
for i in range(len(training_set)):
for j in range(len(training_set)):
g[i][j] = np.dot(training_set[i][0], training_set[j][0])
return g
# update parameters using stochastic gradient descent
def update(i):
global a, b
a[i] = a[i] + 1
b = b + training_set[i][1]
# print a, b # you can uncomment this line to check the process of stochastic gradient descent
# calculate the judge condition
def cal(key):
global a, b, x, y
i = 0
for item in training_set:
y[0][i] = item[1]
i = i + 1
temp = a * y
res = np.dot(temp, Gram[key])
res = (res + b) * training_set[key][1]
return res[0]
# check if the hyperplane can classify the examples correctly
def check():
global a, b, x, y
flag = False
for i in range(len(training_set)):
if cal(i) <= 0:
flag = True
update(i)
if not flag:
i = 0
for item in training_set:
y[0][i] = item[1]
x[i] = item[0]
i = i + 1
temp = a * y
w = np.dot(temp, x)
print "RESULT: w: " + str(w) + " b: "+ str(b)
os._exit(0)
flag = False
if __name__=="__main__":
Gram = cal_gram()# initialize the Gram matrix
for i in range(1000):
check()
print "The training_set is not linear separable. "
import numpy as np
# An example in that book, the training set and parameters' sizes are fixed
training_set = np.array([[[3, 3], 1], [[4, 3], 1], [[1, 1], -1]])
a = np.array([0, 0, 0])
b = 0
Gram = np.array([])
y = np.array(range(len(training_set))).reshape(1, 3)# used for labels
x = np.array(range(len(training_set)) * 2).reshape(3, 2)# used for features
# calculate the Gram matrix
def cal_gram():
g = np.array([[0, 0, 0], [0, 0, 0], [0, 0, 0]])
for i in range(len(training_set)):
for j in range(len(training_set)):
g[i][j] = np.dot(training_set[i][0], training_set[j][0])
return g
# update parameters using stochastic gradient descent
def update(i):
global a, b
a[i] = a[i] + 1
b = b + training_set[i][1]
# print a, b # you can uncomment this line to check the process of stochastic gradient descent
# calculate the judge condition
def cal(key):
global a, b, x, y
i = 0
for item in training_set:
y[0][i] = item[1]
i = i + 1
temp = a * y
res = np.dot(temp, Gram[key])
res = (res + b) * training_set[key][1]
return res[0]
# check if the hyperplane can classify the examples correctly
def check():
global a, b, x, y
flag = False
for i in range(len(training_set)):
if cal(i) <= 0:
flag = True
update(i)
if not flag:
i = 0
for item in training_set:
y[0][i] = item[1]
x[i] = item[0]
i = i + 1
temp = a * y
w = np.dot(temp, x)
print "RESULT: w: " + str(w) + " b: "+ str(b)
os._exit(0)
flag = False
if __name__=="__main__":
Gram = cal_gram()# initialize the Gram matrix
for i in range(1000):
check()
print "The training_set is not linear separable. "
【メモ】svm実装
import numpy
from matplotlib import pyplot
import sys
def f(x, y):
return x - y
if __name__ == '__main__':
param = sys.argv
numpy.random.seed()
N = 30
d = 2
X = numpy.random.randn(N, d)
T = numpy.array([1 if f(x, y) > 0 else - 1 for x, y in X])
alpha = numpy.zeros(N)
beta = 1.0
eta_al = 0.0001 # update ratio of alpha
eta_be = 0.1 # update ratio of beta
itr = 1000
for _itr in range(itr):
for i in range(N):
delta = 1 - (T[i] * X[i]).dot(alpha * T * X.T).sum() - beta * T[i] * alpha.dot(T)
alpha[i] += eta_al * delta
for i in range(N):
beta += eta_be * alpha.dot(T) ** 2 / 2
index = alpha > 0
w = (alpha * T).T.dot(X)
b = (T[index] - X[index].dot(w)).mean()
if '-d' in param or '-s' in param:
seq = numpy.arange(-3, 3, 0.02)
pyplot.figure(figsize = (6, 6))
pyplot.xlim(-3, 3)
pyplot.ylim(-3, 3)
pyplot.plot(seq, -(w[0] * seq + b) / w[1], 'k-')
pyplot.plot(X[T == 1,0], X[T == 1,1], 'ro')
pyplot.plot(X[T == -1,0], X[T == -1,1], 'bo')
if '-s' in param:
pyplot.savefig('graph.png')
if '-d' in param:
pyplot.show()
from matplotlib import pyplot
import sys
def f(x, y):
return x - y
if __name__ == '__main__':
param = sys.argv
numpy.random.seed()
N = 30
d = 2
X = numpy.random.randn(N, d)
T = numpy.array([1 if f(x, y) > 0 else - 1 for x, y in X])
alpha = numpy.zeros(N)
beta = 1.0
eta_al = 0.0001 # update ratio of alpha
eta_be = 0.1 # update ratio of beta
itr = 1000
for _itr in range(itr):
for i in range(N):
delta = 1 - (T[i] * X[i]).dot(alpha * T * X.T).sum() - beta * T[i] * alpha.dot(T)
alpha[i] += eta_al * delta
for i in range(N):
beta += eta_be * alpha.dot(T) ** 2 / 2
index = alpha > 0
w = (alpha * T).T.dot(X)
b = (T[index] - X[index].dot(w)).mean()
if '-d' in param or '-s' in param:
seq = numpy.arange(-3, 3, 0.02)
pyplot.figure(figsize = (6, 6))
pyplot.xlim(-3, 3)
pyplot.ylim(-3, 3)
pyplot.plot(seq, -(w[0] * seq + b) / w[1], 'k-')
pyplot.plot(X[T == 1,0], X[T == 1,1], 'ro')
pyplot.plot(X[T == -1,0], X[T == -1,1], 'bo')
if '-s' in param:
pyplot.savefig('graph.png')
if '-d' in param:
pyplot.show()
2016年11月14日月曜日
Postgresqlでto_chorを使用してintegerからString変換
■
select to_char(5, '09');
実行した結果は
_05
である。スペースが入れている。
■
select to_char(5, 'FM09');
実行した結果は
05
である。スペースが入れていない。
select to_char(5, '09');
実行した結果は
_05
である。スペースが入れている。
■
select to_char(5, 'FM09');
実行した結果は
05
である。スペースが入れていない。
java日付比較時millisecond注意
Date dt3 = dateFormat("20161001", "yyyyMMdd");
Calendar cal = Calendar.getInstance();
cal.setTime(new Date(1475247600132L));
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = 1;
cal.set(year, month, day, 0, 0, 0);
Date dt4 = cal.getTime();
System.out.println(dt3.getTime()); //出力:1475247600000
System.out.println(dt4.getTime()); //出力:1475247600132
Calendar calnoMillSecond = Calendar.getInstance();
calnoMillSecond.setTime(new Date(1475247600132L));
int year1 = cal.get(Calendar.YEAR);
int month1 = cal.get(Calendar.MONTH);
int day1 = 1;
calnoMillSecond.set(year1, month1, day1, 0, 0, 0);
calnoMillSecond.set(Calendar.MILLISECOND, 0);
Date dt5 = calnoMillSecond.getTime();
System.out.println(dt3.getTime()); //出力:1475247600000
System.out.println(dt5.getTime()); //出力:1475247600000
ミリ秒の0設定を注意。
讲座PPT
http://toritris.weebly.com/
http://www.massey.ac.nz/~mjjohnso/notes/59302/l10.html
https://cw.fel.cvut.cz/wiki/_media/courses/ae3m33ui/lectures/linclass-slides.pdf
http://wenku.baidu.com/link?url=V3cS4pGEbT0N1BUdgFtprvwVL7C5VpmLNbfk-TorMJAu_oXPi_jL7mNL23aYjEkGH4nFUDGvtTy062ROrOOVeiba0G8gjLNyPtEjIEtHyAK
java source資料
http://lcn.epfl.ch/tutorial/english/
https://datasciencelab.wordpress.com/2014/01/10/machine-learning-classics-the-perceptron/
https://appliedgo.net/perceptron/
https://www.reddit.com/r/MachineLearning/comments/15zrpp/please_explain_support_vector_machines_svm_like_i/
why sigmoid not step
http://fedc.wiwi.hu-berlin.de/fedc_homepage/xplore/tutorials/sfehtmlnode96.html
点到超平面计算
https://segmentfault.com/a/1190000005129669
http://blog.csdn.net/han_xiaoyang/article/details/50856583
Must Know Tips/Tricks in Deep Neural Networks
http://www.roguewave.com/getattachment/80bd5b86-ea29-457a-a0e1-db07e4cc5157/Neural-Networks-An-Introductiontarget=
https://mattmazur.com/2015/03/17/a-step-by-step-backpropagation-example/
http://www.massey.ac.nz/~mjjohnso/notes/59302/l10.html
https://cw.fel.cvut.cz/wiki/_media/courses/ae3m33ui/lectures/linclass-slides.pdf
http://wenku.baidu.com/link?url=V3cS4pGEbT0N1BUdgFtprvwVL7C5VpmLNbfk-TorMJAu_oXPi_jL7mNL23aYjEkGH4nFUDGvtTy062ROrOOVeiba0G8gjLNyPtEjIEtHyAK
java source資料
http://lcn.epfl.ch/tutorial/english/
https://datasciencelab.wordpress.com/2014/01/10/machine-learning-classics-the-perceptron/
https://appliedgo.net/perceptron/
https://www.reddit.com/r/MachineLearning/comments/15zrpp/please_explain_support_vector_machines_svm_like_i/
why sigmoid not step
http://fedc.wiwi.hu-berlin.de/fedc_homepage/xplore/tutorials/sfehtmlnode96.html
点到超平面计算
https://segmentfault.com/a/1190000005129669
http://blog.csdn.net/han_xiaoyang/article/details/50856583
Must Know Tips/Tricks in Deep Neural Networks
http://www.roguewave.com/getattachment/80bd5b86-ea29-457a-a0e1-db07e4cc5157/Neural-Networks-An-Introductiontarget=
https://mattmazur.com/2015/03/17/a-step-by-step-backpropagation-example/
2016年10月28日金曜日
简单感知机实现
# coding: UTF-8
# 2次元のパーセプトロンの学習規則の実装例
import numpy as np
import matplotlib.pyplot as plt
import sys
def train(wvec, xvec, label):
low = 0.5#学習係数
if (np.dot(wvec,xvec) * label < 0):
wvec_new = wvec + label*low*xvec
return wvec_new
else:
return wvec
if __name__ == '__main__':
train_num = 100#学習データ数
#class1の学習データ
x1_1=np.random.rand(train_num/2) * 5 + 1 #x成分
x1_2=np.random.rand(int(train_num/2)) * 5 + 1 #y成分
label_x1 = np.ones(train_num/2) #ラベル(すべて1)
#class2の学習データ
x2_1=(np.random.rand(train_num/2) * 5 + 1) * -1 #x成分
x2_2=(np.random.rand(train_num/2) * 5 + 1) * -1 #y成分
label_x2 = np.ones(train_num/2) * -1 #ラベル(すべて-1)
x0=np.ones(train_num/2) # x0は常に1
x1=np.c_[x0, x1_1, x1_2]
x2=np.c_[x0, x2_1, x2_2]
xvecs=np.r_[x1, x2]
labels = np.r_[label_x1, label_x2]
wvec = np.array([2,-1,3])#初期の重みベクトル 適当に決める
loop = 100
for j in range(loop):
for xvec, label in zip(xvecs, labels):
wvec = train(wvec, xvec, label)
print(wvec)
plt.scatter(x1[:,1], x1[:,2], c='red', marker="o")
plt.scatter(x2[:,1], x2[:,2], c='yellow', marker="o")
#分離境界線
x_fig = np.array(range(-8,8))
y_fig = -(wvec[1]/wvec[2])*x_fig - (wvec[0]/wvec[2])
plt.plot(x_fig,y_fig)
plt.show()
http://iamtrask.github.io/2015/07/12/basic-python-network/
# 2次元のパーセプトロンの学習規則の実装例
import numpy as np
import matplotlib.pyplot as plt
import sys
def train(wvec, xvec, label):
low = 0.5#学習係数
if (np.dot(wvec,xvec) * label < 0):
wvec_new = wvec + label*low*xvec
return wvec_new
else:
return wvec
if __name__ == '__main__':
train_num = 100#学習データ数
#class1の学習データ
x1_1=np.random.rand(train_num/2) * 5 + 1 #x成分
x1_2=np.random.rand(int(train_num/2)) * 5 + 1 #y成分
label_x1 = np.ones(train_num/2) #ラベル(すべて1)
#class2の学習データ
x2_1=(np.random.rand(train_num/2) * 5 + 1) * -1 #x成分
x2_2=(np.random.rand(train_num/2) * 5 + 1) * -1 #y成分
label_x2 = np.ones(train_num/2) * -1 #ラベル(すべて-1)
x0=np.ones(train_num/2) # x0は常に1
x1=np.c_[x0, x1_1, x1_2]
x2=np.c_[x0, x2_1, x2_2]
xvecs=np.r_[x1, x2]
labels = np.r_[label_x1, label_x2]
wvec = np.array([2,-1,3])#初期の重みベクトル 適当に決める
loop = 100
for j in range(loop):
for xvec, label in zip(xvecs, labels):
wvec = train(wvec, xvec, label)
print(wvec)
plt.scatter(x1[:,1], x1[:,2], c='red', marker="o")
plt.scatter(x2[:,1], x2[:,2], c='yellow', marker="o")
#分離境界線
x_fig = np.array(range(-8,8))
y_fig = -(wvec[1]/wvec[2])*x_fig - (wvec[0]/wvec[2])
plt.plot(x_fig,y_fig)
plt.show()
http://iamtrask.github.io/2015/07/12/basic-python-network/
2016年10月20日木曜日
postgresqlデータベース numericデータタイプ
NUMERIC(precision, scale)
precision精度、
scale位取り
上記の説明は理解しにくいです。
簡単にいうと、
precisionは全体桁数(小数点含む)である
scaleは小数桁数である
例:
numeric(13, 4)
⇒12345678901234 OK
⇒1234567890.123 OK
⇒123456789.1234 OK
⇒1234567890.1234 NG
2016年10月19日水曜日
translate api関連
http://ec.europa.eu/dgs/translation/translationresources/machine_translation/index_en.htm
https://www.quora.com/Which-is-a-good-reliable-free-language-translation-API-available
https://www.quora.com/Which-is-a-good-reliable-free-language-translation-API-available
2016年10月18日火曜日
ml学习路径
概述(历史,现状)
PYTHON基础
感知机
激励函数
神经网络初步
梯度下降
反向传递
神经网络优化
成本函数
正规化
初始化
过拟合
海森矩阵
深度学习
卷积神经网络
RNN
リンク:
http://www.kdnuggets.com/2016/09/poll-algorithms-used-data-scientists.html
https://appliedgo.net/perceptron/
http://tjo.hatenablog.com/entry/2013/05/01/190247
https://www.youtube.com/playlist?list=PLD63A284B7615313A
http://www.itcast.cn/subject/pythonzly/index.shtml?from=161101a9
storm vs spark streaming
http://www.slideshare.net/ptgoetz/apache-storm-vs-spark-streaming
http://www.36dsj.com/archives/10223
感知机
http://web.donga.ac.kr/yjko/usefulthings/Perceptron_Ko.pdf
http://lxw1234.com/archives/2016/05/649.htm
http://www.slideshare.net/tw_dsconf/ss-62245351?qid=108adce3-2c3d-4758-a830-95d0a57e46bc&v=&b=&from_search=3
PYTHON基础
感知机
激励函数
神经网络初步
梯度下降
反向传递
神经网络优化
成本函数
正规化
初始化
过拟合
海森矩阵
深度学习
卷积神经网络
RNN
リンク:
http://www.kdnuggets.com/2016/09/poll-algorithms-used-data-scientists.html
https://appliedgo.net/perceptron/
http://tjo.hatenablog.com/entry/2013/05/01/190247
https://www.youtube.com/playlist?list=PLD63A284B7615313A
http://www.itcast.cn/subject/pythonzly/index.shtml?from=161101a9
storm vs spark streaming
http://www.slideshare.net/ptgoetz/apache-storm-vs-spark-streaming
http://www.36dsj.com/archives/10223
感知机
http://web.donga.ac.kr/yjko/usefulthings/Perceptron_Ko.pdf
http://lxw1234.com/archives/2016/05/649.htm
http://www.slideshare.net/tw_dsconf/ss-62245351?qid=108adce3-2c3d-4758-a830-95d0a57e46bc&v=&b=&from_search=3
2016年10月13日木曜日
springboot+domaページング
SQL:
ファイル名:
{プロジェクトパス}\src\main\resources\META-INF\com\example\MenuDao\selectAll.sql
ファイル内容
@Entity
@Table(name = "menus")
public class Menus {
@Id
@Column(name = "menu_id")
private Integer menuId;
@Column(name = "menu_name")
private String menuName;
//getter,setter略
}
Dao:
ファイル名:
@Dao
@ConfigAutowireable
public interface MenuDao {
@Select
List<TElecRyokinLowMenuM> selectAll(SelectOptions options);
}
Controller:
ファイル名:
@RestController
public class MenuController {
final MenuDao menuDao;
@Autowired
public MenuController(MenuDao menuDao){
this.menuDao = menuDao;
}
@RequestMapping(value="/menu",method=RequestMethod.GET)
List<Menus> list(@PageableDefault Pageable pageable){
List<Menus> menus = menuDao.selectAll(Pageables.toSelectOptions(pageable));
return menus;
}
}
使用方法:
http://localhost:8080/menu?page=5&size=30
ログをみると、下記のようなSQLを出力する:
select
menu_id
,menu_name
from menus
order by menu_id limit 30 offset 150
参照リンク:
http://ankushs92.github.io/tutorial/2016/05/03/pagination-with-spring-boot.html
ファイル名:
{プロジェクトパス}\src\main\resources\META-INF\com\example\MenuDao\selectAll.sql
ファイル内容
SELECT
menu_id
,menu_namer
FROM menus
ORDER BY menu_id
Entity:ファイル名:{プロジェクトパス}\src\main\ava\com\example\Menus.java@Entity
@Table(name = "menus")
public class Menus {
@Id
@Column(name = "menu_id")
private Integer menuId;
@Column(name = "menu_name")
private String menuName;
//getter,setter略
}
Dao:
ファイル名:
{プロジェクトパス}\src\main\java\com\example\MenuDao.java@Dao
@ConfigAutowireable
public interface MenuDao {
@Select
List<TElecRyokinLowMenuM> selectAll(SelectOptions options);
}
Controller:
ファイル名:
{プロジェクトパス}\src\main\java\com\example\MenuController.java@RestController
public class MenuController {
final MenuDao menuDao;
@Autowired
public MenuController(MenuDao menuDao){
this.menuDao = menuDao;
}
@RequestMapping(value="/menu",method=RequestMethod.GET)
List<Menus> list(@PageableDefault Pageable pageable){
List<Menus> menus = menuDao.selectAll(Pageables.toSelectOptions(pageable));
return menus;
}
}
使用方法:
http://localhost:8080/menu?page=5&size=30
ログをみると、下記のようなSQLを出力する:
select
menu_id
,menu_name
from menus
order by menu_id limit 30 offset 150
参照リンク:
http://ankushs92.github.io/tutorial/2016/05/03/pagination-with-spring-boot.html
转贴:C中的const
const是一个C语言的关键字,它限定一个变量不允许被改变。使用const在一定程度上可以提高程序的健壮性,另外,在观看别人代码的时候,清晰理解const所起的作用,对理解对方的程序也有一些帮助。 虽然这听起来很简单,但实际上,const的使用也是c语言中一个比较微妙的地方,微妙在何处呢?请看下面几个问题。
问题:const变量 & 常量
为什么我象下面的例子一样用一个const变量来初始化数组,ANSI C的编译器会报告一个错误呢?
const int n = 5;
int a[n];
答案与分析:
1)、这个问题讨论的是“常量”与“只读变量”的区别。常量肯定是只读的,例如5, “abc”,等,肯定是只读的,因为程序中根本没有地方存放它的值,当然也就不能够去修改它。而“只读变量”则是在内存中开辟一个地方来存放它的值,只不过这个值由编译器限定不允许被修改。C语言关键字const就是用来限定一个变量不允许被改变的修饰符(Qualifier)。上述代码中变量n被修饰为只读变量,可惜再怎么修饰也不是常量。而ANSI C规定数组定义时维度必须是“常量”,“只读变量”也是不可以的。
2)、注意:在ANSI C中,这种写法是错误的,因为数组的大小应该是个常量,而const int n,n只是一个变量(常量 != 不可变的变量,但在标准C++中,这样定义的是一个常量,这种写法是对的),实际上,根据编译过程及内存分配来看,这种用法本来就应该是合理的,只是ANSI C对数组的规定限制了它。
3)、那么,在ANSI C 语言中用什么来定义常量呢?答案是enum类型和#define宏,这两个都可以用来定义常量。
问题:const变量 & const 限定的内容
下面的代码编译器会报一个错误,请问,哪一个语句是错误的呢?
typedef char * pStr;
char string[4] = "abc";
const char *p1 = string;
const pStr p2 = string;
p1++;
p2++;
答案与分析:
问题出在p2++上。
1)、const使用的基本形式: const char m;
限定m不可变。
2)、替换1式中的m, const char *pm;
限定*pm不可变,当然pm是可变的,因此问题中p1++是对的。
3)、替换1式char, const newType m;
限定m不可变,问题中的charptr就是一种新类型,因此问题中p2不可变,p2++是错误的。
问题:const变量 & 字符串常量
请问下面的代码有什么问题?
char *p = "i'm hungry!";
p[0]= 'I';
答案与分析:
上面的代码可能会造成内存的非法写操作。分析如下, “i'm hungry”实质上是字符串常量,而常量往往被编译器放在只读的内存区,不可写。p初始指向这个只读的内存区,而p[0] = 'I'则企图去写这个地方,编译器当然不会答应。
问题:const变量 & 字符串常量2
请问char a[3] = "abc" 合法吗?使用它有什么隐患?
答案与分析:
在标准C中这是合法的,但是它的生存环境非常狭小;它定义一个大小为3的数组,初始化为“abc”,,注意,它没有通常的字符串终止符'\0',因此这个数组只是看起来像C语言中的字符串,实质上却不是,因此所有对字符串进行处理的函数,比如strcpy、printf等,都不能够被使用在这个假字符串上。
问题:const & 指针
类型声明中const用来修饰一个常量,有如下两种写法,那么,请问,下面分别用const限定不可变的内容是什么?
1)、const在前面
const int nValue; //nValue是const
const char *pContent; //*pContent是const, pContent可变
const (char *) pContent;//pContent是const,*pContent可变
char* const pContent; //pContent是const,*pContent可变
const char* const pContent; //pContent和*pContent都是const
2)、const在后面,与上面的声明对等
int const nValue; // nValue是const
char const * pContent;// *pContent是const, pContent可变
(char *) const pContent;//pContent是const,*pContent可变
char* const pContent;// pContent是const,*pContent可变
char const* const pContent;// pContent和*pContent都是const
答案与分析:
const和指针一起使用是C语言中一个很常见的困惑之处,在实际开发中,特别是在看别人代码的时候,常常会因为这样而不好判断作者的意图,下面讲一下我的判断原则:
沿着*号划一条线,const和谁在一边,那么谁就是const,即const限定的元素就是它。你可以根据这个规则来看上面声明的实际意义,相信定会一目了然。
另外,需要注意:对于const (char *) ; 因为char *是一个整体,相当于一个类型(如 char),因此,这是限定指针是const。
问题:const变量 & 常量
为什么我象下面的例子一样用一个const变量来初始化数组,ANSI C的编译器会报告一个错误呢?
const int n = 5;
int a[n];
答案与分析:
1)、这个问题讨论的是“常量”与“只读变量”的区别。常量肯定是只读的,例如5, “abc”,等,肯定是只读的,因为程序中根本没有地方存放它的值,当然也就不能够去修改它。而“只读变量”则是在内存中开辟一个地方来存放它的值,只不过这个值由编译器限定不允许被修改。C语言关键字const就是用来限定一个变量不允许被改变的修饰符(Qualifier)。上述代码中变量n被修饰为只读变量,可惜再怎么修饰也不是常量。而ANSI C规定数组定义时维度必须是“常量”,“只读变量”也是不可以的。
2)、注意:在ANSI C中,这种写法是错误的,因为数组的大小应该是个常量,而const int n,n只是一个变量(常量 != 不可变的变量,但在标准C++中,这样定义的是一个常量,这种写法是对的),实际上,根据编译过程及内存分配来看,这种用法本来就应该是合理的,只是ANSI C对数组的规定限制了它。
3)、那么,在ANSI C 语言中用什么来定义常量呢?答案是enum类型和#define宏,这两个都可以用来定义常量。
问题:const变量 & const 限定的内容
下面的代码编译器会报一个错误,请问,哪一个语句是错误的呢?
typedef char * pStr;
char string[4] = "abc";
const char *p1 = string;
const pStr p2 = string;
p1++;
p2++;
答案与分析:
问题出在p2++上。
1)、const使用的基本形式: const char m;
限定m不可变。
2)、替换1式中的m, const char *pm;
限定*pm不可变,当然pm是可变的,因此问题中p1++是对的。
3)、替换1式char, const newType m;
限定m不可变,问题中的charptr就是一种新类型,因此问题中p2不可变,p2++是错误的。
问题:const变量 & 字符串常量
请问下面的代码有什么问题?
char *p = "i'm hungry!";
p[0]= 'I';
答案与分析:
上面的代码可能会造成内存的非法写操作。分析如下, “i'm hungry”实质上是字符串常量,而常量往往被编译器放在只读的内存区,不可写。p初始指向这个只读的内存区,而p[0] = 'I'则企图去写这个地方,编译器当然不会答应。
问题:const变量 & 字符串常量2
请问char a[3] = "abc" 合法吗?使用它有什么隐患?
答案与分析:
在标准C中这是合法的,但是它的生存环境非常狭小;它定义一个大小为3的数组,初始化为“abc”,,注意,它没有通常的字符串终止符'\0',因此这个数组只是看起来像C语言中的字符串,实质上却不是,因此所有对字符串进行处理的函数,比如strcpy、printf等,都不能够被使用在这个假字符串上。
问题:const & 指针
类型声明中const用来修饰一个常量,有如下两种写法,那么,请问,下面分别用const限定不可变的内容是什么?
1)、const在前面
const int nValue; //nValue是const
const char *pContent; //*pContent是const, pContent可变
const (char *) pContent;//pContent是const,*pContent可变
char* const pContent; //pContent是const,*pContent可变
const char* const pContent; //pContent和*pContent都是const
2)、const在后面,与上面的声明对等
int const nValue; // nValue是const
char const * pContent;// *pContent是const, pContent可变
(char *) const pContent;//pContent是const,*pContent可变
char* const pContent;// pContent是const,*pContent可变
char const* const pContent;// pContent和*pContent都是const
答案与分析:
const和指针一起使用是C语言中一个很常见的困惑之处,在实际开发中,特别是在看别人代码的时候,常常会因为这样而不好判断作者的意图,下面讲一下我的判断原则:
沿着*号划一条线,const和谁在一边,那么谁就是const,即const限定的元素就是它。你可以根据这个规则来看上面声明的实际意义,相信定会一目了然。
另外,需要注意:对于const (char *) ; 因为char *是一个整体,相当于一个类型(如 char),因此,这是限定指针是const。
2016年10月7日金曜日
batch起動eclipse
@echo off
rem eclipse起動!
cd C:\ma\eclipse
echo Eclipse起動!
start "" C:\ma\eclipse\eclipse.exe
rem eclipse起動!
cd C:\ma\eclipse
echo Eclipse起動!
start "" C:\ma\eclipse\eclipse.exe
2016年10月6日木曜日
2016年9月24日土曜日
python datetime日付操作
# -*- coding: utf-8 -*- import datetime today = datetime.datetime.today() # 今日の日付 print today # 明日の日付 print today + datetime.timedelta(days=1) newyear = datetime.datetime(2010, 1, 1) # 2010年1月1日の一週間後 print newyear + datetime.timedelta(days=7) # 2010年1月1日から今日までの日数 calc = today - newyear # 計算結果の戻り値は「timedelta」 print calc.days--実行結果--
2010-05-08 15:36:24.006000 2010-05-09 15:36:24.006000 2010-01-08 00:00:00 127
2016年9月23日金曜日
【python】regexでURLを認識
#!/usr/bin/python
# -*- coding:utf-8 -*-
import re
url = "http://www.sankei.com/economy/news/160923/ecn1609230018-n1.html"
pattern = re.compile("^(https?|ftp)://www\.sankei\.com*?")
m = pattern.search(url)
if m:
print(url)
else:
print(None)
python年月日stringからDateを抽出
#!/usr/bin/python
# -*- coding:utf-8 -*-
import sys
import datetime
strdate = "2016年9月23日(金)"
locale.setlocale(locale.LC_ALL, "")
print(locale.getlocale())
#出力
d = datetime.datetime.today()
print (d.strftime("%Y年%m月%d日(%a)") )
print (d.strftime("%p") )
print (d.strftime("%x %X") )
#抽出
print(datetime.datetime.strptime(strdate, "%Y年%B%d日(%a)"))
# -*- coding:utf-8 -*-
import sys
import datetime
strdate = "2016年9月23日(金)"
locale.setlocale(locale.LC_ALL, "")
print(locale.getlocale())
#出力
d = datetime.datetime.today()
print (d.strftime("%Y年%m月%d日(%a)") )
print (d.strftime("%p") )
print (d.strftime("%x %X") )
#抽出
print(datetime.datetime.strptime(strdate, "%Y年%B%d日(%a)"))
python で正規表現を用いて日付表現を抽出
#!/usr/bin/python
# -*- coding:utf-8 -*-
import sys
import datetime
import locale # import文はどこに書いてもOK(可読性などの為、慣例でコードの始めの方)
import re
date_pattern = re.compile('(\d{4})年(\d{1,2})月(\d{1,2})日')
strdate = "2016年9月23日(金)"
result = date_pattern.search(strdate)
if result:
y, m, d = result.groups()
print( {'year': y, 'month': m, 'day': d})
else:
print( None)
参照:https://gist.github.com/otknoy/10256402
# -*- coding:utf-8 -*-
import sys
import datetime
import locale # import文はどこに書いてもOK(可読性などの為、慣例でコードの始めの方)
import re
date_pattern = re.compile('(\d{4})年(\d{1,2})月(\d{1,2})日')
strdate = "2016年9月23日(金)"
result = date_pattern.search(strdate)
if result:
y, m, d = result.groups()
print( {'year': y, 'month': m, 'day': d})
else:
print( None)
参照:https://gist.github.com/otknoy/10256402
2016年8月30日火曜日
selectプレースホルダ―実装
説明:
selectのプレースホルダ―機能を提供されていないため、似ている効果を試して実装しました。
まず、空のoptionを用意します。
空のoptionを選択すると、空optionはプレースホルダ―のdefault色で空のoptionテキストを表示します。
<select name="a">
<option value="0">都道府県</option>
<option value="1">北海道</option>
<option value="10">群馬県</option>
<option value="11">埼玉県</option>
<option value="12">千葉県</option>
<option value="13">東京都</option>
</select>
説明:
selectのプレースホルダ―機能を提供されていないため、似ている効果を試して実装しました。
まず、空のoptionを用意します。
空のoptionを選択すると、空optionはプレースホルダ―のdefault色で空のoptionテキストを表示します。
<select name="a">
<option value="0">都道府県</option>
<option value="1">北海道</option>
<option value="10">群馬県</option>
<option value="11">埼玉県</option>
<option value="12">千葉県</option>
<option value="13">東京都</option>
</select>
プレースホルダ―のdefault色:'#999'
普通文字色:'#555'
①画面初期化時、
$("select[name=a]").find("option[value='0']").css({'color': '#999'});
②select変更時
$("select[name=a]").change(function(){
if($(this).val() == '0'){
$(this).css({'color': '#999'});
$(this).find("option").css({'color': '#555'});
$(this).find("option[value='0']").css({'color': '#999'});
} else {
$(this).css({'color': '#555'});
}
});
2016年7月7日木曜日
Deep Learning notes:Techniques improving backpropogation
Deep Learning notes:Techniques improving backpropogation
1. a better choice of cost function
⇒ the cross-entropy cost function
2. "regularization" methods
L1
L2 regularization,
dropout,
artificial expansion of the training data
3. better method for initializing the weights in the network
4. set of heuristics to help choose good hyper-parameters for the network
1. a better choice of cost function
⇒ the cross-entropy cost function
2. "regularization" methods
L1
L2 regularization,
dropout,
artificial expansion of the training data
3. better method for initializing the weights in the network
4. set of heuristics to help choose good hyper-parameters for the network
2016年5月18日水曜日
java listからarrayへ変換
■Array to List
List<String> keys = new ArrayList<>(Arrays.asList("a", "b", "c"));
Arrays.asList("a", "b", "c")の結果は固定Listである、add, removeが不可です。
new ArrayList<>()を使用して、普通Listへ変換した後、add, removeが可能となります。
■List to Array
List<String> keys = new ArrayList<>(Arrays.asList("a", "b", "c"));
Arrays.asList("a", "b", "c")の結果は固定Listである、add, removeが不可です。
new ArrayList<>()を使用して、普通Listへ変換した後、add, removeが可能となります。
■List to Array
List<String> list = ..;
String[] array = list.toArray(new String[0]);
上記コードに、もともと list.toArray(new String[list.size()])を使用すると、理解しやすいけど、JVM optimizationsの利便性を考えたうえで、new String[0]方がいい。
登録:
投稿 (Atom)
